Skip to content

fix(agents): honor account-scoped history limits instead of silently ignoring them - #119326

Merged
steipete merged 6 commits into
openclaw:mainfrom
ayaangazali:fix/history-limit-account-scope
Aug 29, 2026
Merged

steipete merged 6 commits into
openclaw:mainfrom
ayaangazali:fix/history-limit-account-scope

Conversation

@ayaangazali

@ayaangazali ayaangazali commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where channel users received the wrong amount of conversation history when the active account or peer policy differed from the channel default. Fixes connected cases where a short history window evicted a provider compaction checkpoint, causing context loss or replay rejection on later turns.

Related: #129599. This is a maintainer rewrite of the existing account-history PR, preserving @ayaangazali's contribution and covering the checkpoint lifecycle exposed by realistic short-window testing.

Why This Change Was Made

Account policy now uses normalized account configuration and admitted route facts, including peer and conversation kind. Manual Gateway compaction reads the existing current-primary conversation registry; it does not infer routing from a possibly ambiguous session key or create another routing store. Explicit zero and whole-map per-peer replacement retain their existing semantics.

Provider replay owns checkpoint continuity. The existing v1 assistant-owned envelope retains the complete validated OpenAI compact output, or the complete native xAI item, and preserves the opaque field for old readers. A transient projection carries at most one eligible original owner across history trimming, after identity/auth checks and before pairing. It neither copies checkpoints into later durable messages nor resurrects covered prelude messages. Prompt pressure measures the canonical checkpoint plus uncovered tail once and does not trust context totals that lack checkpoint/auth lineage. The actually prepared outgoing request determines checkpoint authority.

The complete output is bounded to 16 MiB, including serialized-envelope escaping/duplication; raw successful HTTP bodies are bounded before JSON parsing, with depth capped at 64. Capture falls back to ordinary client compaction if current payload/image/redaction policy would alter the checkpoint. Later redaction or a legacy retained-user checkpoint without its complete output requires explicit /compact recovery from full durable history. Provider/model/endpoint/session/auth fences remain intact. Anthropic replay uses its existing canonical resolved-key classifier, passing only a prepared eligibility boolean into core.

The compact-only fetch wrapper bounds successful response bytes before the ordinary OpenAI SDK parser consumes them. The SDK still owns per-attempt body deadlines, retries and typed caller cancellation. This replaces the rewrite's raw .asResponse() reader, which bypassed those SDK lifecycle guarantees; ordinary streaming and non-success HTTP responses retain their existing paths.

No database schema/version, index, protocol, dependency, or new configuration setting changes. The additive persisted checkpoint field is an explicitly approved data contract, not a claim of zero persistence impact. Existing database newer-schema guards remain enforced.

User Impact

Per-account and per-peer history limits are applied consistently through ordinary turns, queued turns, and explicit compaction. Tight limits no longer silently discard valid provider context. Unsupported or redacted legacy checkpoint state fails visibly with a recovery action rather than sending a misleading partial transcript. Existing durable messages remain available for explicit recovery.

Telegram's native-ID supplemental history and linked-peer embedded turn history remain distinct documented policies. This does not change native Codex behavior, add Buzz multi-account support, or implement Buzz DM/reaction/media features.

Evidence

Land-ready candidate: bb3d9a22eeb79362f9f58f2f6a9e36d9eeb8bea6, rebased onto f93be5b5fe56be6293a5517bd57ddcc135375fda after checkout-cleanup repairs #132169, #132204 and #132203 landed. The six-commit range-diff preserves the patch, with only context around upstream's isolated compaction-test workspace changed. All 154 compaction-hook tests and nine real HTTP lifecycle controls passed on this head. Normal and private-QA builds passed, including the UI budget (344732 B below 345947 B); the canonical build stamp matches the full candidate SHA. Exact-head CI run 33228608553 passed, including openclaw/ci-gate.

The final compiled-boundary repeat also passed: both Gateway client/endpoint compaction cases (12 and 18 turns respectively, two endpoint generations with exact checkpoint hashes), 27 provider-replay tests and seven transcript-rewrite tests using real SQLite. Command: OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs test/gateway-account-history.e2e.test.ts packages/ai/src/transports/provider-compaction-replay.test.ts src/agents/embedded-agent-runner/transcript-rewrite.test.ts --reporter=verbose; three shards completed in 245.79 seconds. Source remained clean and the build stamp was checked before and after. This is actual compiled Gateway behavior with controlled channel/model services, not authenticated Telegram/OpenAI. Current native review baseline 5d8ef653 has no overlapping production, test or documentation changes since the pinned base; only unrelated assertion-ratchet entries overlap by filename.

The preceding aa463aaa candidate passed final local changed checks and normal pnpm build, including the UI budget (346606 B below 347037 B), but CI run 33222068278 failed in the main-introduced checkout-cleanup test. This rebase incorporates the existing repairs; no duplicate cleanup patch or relaxed assertion was added. The older 70382159812587afc4f9c00240449b6f1190987e run is not proof for the SDK-lifetime repair.

The preceding failed merge job reported cleanup-failure fatal125 in the process-boundary assertion (small47, job99018176316). That test was introduced on main by #132105 and was absent from the pre-rebase aa463aaa head. A separate isolated Linux diagnostic completed 80 cases and 568 boundary checks with 264 later ENOENT probes, all passing including the original implementation; this is not a local RED/GREEN reproduction and does not classify the failed CI processes as zombies or active writers. Diagnostic details and coordination are recorded with the existing repair owner.

  • Regression evidence includes actual caller-level account precedence failures, checkpoint eviction across a compiled Gateway's short window, discarded-checkpoint admission, explicit-account override with known conversation kind, covered-prelude duplication, and retained-user runtime-carrier placement across two tool rounds.
  • Integrated focused suite: 280 tests across 11 files passed. The review-fix suite then passed 267 tests across nine files with refreshed dependencies; final preflight and failure-owner tests passed 22 cases across two files. Counts overlap and are not summed. The complete outgoing checkpoint route/budget is independent of the diagnostic raw-history maximum. Whole-candidate changed checks and the final five-path follow-up gate passed. Independent Codex review of the complete candidate found no actionable P0–P2 findings; the final test-only JSON-serialization comment also received a clean review.
  • Hosted CI exposed three stale context-engine assertions. They reproduced RED before the test repair; both complete owner suites then passed (73 tests across two files). Assertions now check ordinary-admission deferral and actual preassembly snapshots while retaining checkpoint validation. The follow-up's changed-file gate and independent P0–P2 review passed; no production workaround or weakened checkpoint guard was added.
  • Pre-land installed OpenAI 7.5.0 source inspection and a real loopback HTTP server exposed four failures in the raw-reader rewrite: explicit and host-derived body deadlines, body-timeout retries and typed cancellation. The regression was RED before repair, then all 83 focused tests across five files passed, including nine HTTP/lifecycle controls. A standalone stalled-body repeat settled at 107 ms for the fixed 100 ms deadline instead of waiting for fixture cleanup; the existing embedded compaction safety owner remained bounded throughout. The final lint/type-only cleanup passed all core-test type shards, the nine new controls and fresh independent P0–P2 review. Lint and test-library-target failures were repaired, not waived.
  • Before the SDK-lifetime follow-up, the normal production build and private QA runtime passed through their supported profiles and canonical build-provenance writer. A source-blind validator completed 19 replies, 19 initial provider requests, and two endpoint generations through the compiled Gateway. Both explicit RPC compactions used the linked-peer limit of 2 rather than account 10 or root 20; complete output hashes stayed exact across repeated trimming, and rejected controls made no requests. The subsequent SDK transport repair has its own real HTTP and authenticated-provider repeats described above and below; it does not change the history, persistence or routing owners.
  • Synthetic legacy import through the actual compiled canonical rewrite preserved all 43 original raw rows and IDs byte-for-byte, with only 15 intentional suffix copies and no extra checkpoint appends. The next chat visibly requested /compact without a provider call. Public sessions.compact made one client-summary request containing first and later durable markers, with zero endpoint calls or opaque checkpoint bytes. A further Gateway restart and continuation retained the resulting summary. The deterministic summary derives only from the actual model request; this proves persistence/continuation, not model semantic quality.
  • The rewrite regression first failed on keyed replacement/suffix messages: global ingestion deduplication was incorrectly suppressing deliberate canonical copies. The rewrite owner now marks only those already-checked appends explicitly, preserving ordinary ingress deduplication and original row identity. Focused rewrite/old-reader tests passed. A separate failure-owner regression first reproduced the generic /new response, then proved that only the native precheck error selects the fixed /compact instruction; mutated, serialized, and spoofed errors do not become trusted copy.
  • Final runtime build passed. The actual official pre-change reader at 3270b4d3e6e35a4980757e5bdff535d120697f35 opened the candidate database, retained the additive v1 field on read, and dropped only that field during its real rewrite. Exactly three intentional message appends preserved seven original rows byte-for-byte. Final-candidate reopen retained all six ordinary messages, added no rows, and required explicit /compact recovery. Both revisions use unchanged state/agent schema guards 13/18. This is matching-schema pre-change-reader proof, not certification of a released older version; public full-history recovery is tested separately.
  • Real OpenAI proof was repeated after the SDK-lifetime repair: two compact calls and six continuations, all HTTP 200; whole-output hashes stayed exact across HTTP egress, JSON reopen and repeated owner eviction, with three then seven retained items and synthetic recall. This is external provider transport proof, separate from the controlled-service Gateway/database and Linux Testbox proofs. It is not a claim that Testbox exercised authenticated OpenAI.
  • Linux compiled Gateway E2E: both client-compaction and 18-turn/two-generation endpoint scenarios passed through Blacksmith Testbox; run 33208500509. Transport/model services were controlled fixtures, not authenticated Telegram/OpenAI calls. The lease completed.

Production/tooling LOC: +1021/-233 (net +788); tests/support: +2675/-146; docs: +40/-3; assertion inventory +1/-1. The production growth is primarily the complete-output validator/bounds and shared replay projection/pressure owner needed for a lossless provider contract; caller plumbing reuses the existing route and conversation owners. A lossy single-item projection, copy-forward checkpoint writes, or downstream retry would not repair the demonstrated lifecycle failure.

Provenance: account-history introduction is not reliably traceable through the available shallow boundary. The endpoint implementations carried the incomplete-output assumption forward: #123622 (xAI, merged 2026-08-14, author/merger @steipete) and #124974 (retained Responses messages, merged 2026-08-18, author/merger @steipete). This does not attribute the original account bug to the author at the shallow boundary. Actual upstream Codex source was inspected at d47e5cc0e2bbd35774dff15c83570519735d2ac4; complete-vector ownership informed the review, without claiming native-runtime parity.

Both rank-up moves from the earlier review are addressed: Gateway compaction consumes the persisted current-primary peer/chat-kind facts, and a real compiled RPC trace distinguishes the peer override from the account default. The latest ClawSweeper review, updated August 29 at 02:30 UTC for this exact head, reports no code or security findings. Its requests for final-head compatibility/session validation and confirmation of rank-up requirements are satisfied by the final compiled-boundary, persistence and CI results above; no requirement was waived. The previous review's 30-second runner interruption was not a terminal product failure; the Linux and final local executions completed.

Release context:

  • Agents/history: honor active account and peer history limits and retain complete eligible provider checkpoints across short windows, with visible full-history recovery for unsupported legacy checkpoints. Thanks @ayaangazali.

@ayaangazali
ayaangazali marked this pull request as ready for review August 4, 2026 19:55
Copilot AI lite review requested due to automatic review settings August 4, 2026 19:55
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Aug 4, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 4, 2026

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 4, 2026
@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 10:28 PM ET / August 29, 2026, 02:28 UTC.

ClawSweeper review

What this changes

This PR makes embedded-agent history selection and compaction honor channel account and peer policy, preserves provider replay checkpoints, and adds tests and documentation.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open: current main still lacks account-aware history selection, while the branch has coherent source and gateway-boundary coverage. Exact-head integration checks and the latest ClawSweeper rank-up requirements need confirmation before merge.

Priority: P1
Reviewed head: bb3d9a22eeb79362f9f58f2f6a9e36d9eeb8bea6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A well-covered owner-boundary repair whose final integration evidence still needs to reach the exact commit proposed for merge.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The branch's gateway E2E starts an ephemeral Gateway with controlled channel and model services, drives ingress and authenticated compaction through the production owners, and observes the resulting provider request and persisted checkpoint continuity. It is boundary proof for the changed path, though not an external-provider or live-Telegram demonstration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The branch's gateway E2E starts an ephemeral Gateway with controlled channel and model services, drives ingress and authenticated compaction through the production owners, and observes the resulting provider request and persisted checkpoint continuity. It is boundary proof for the changed path, though not an external-provider or live-Telegram demonstration.
Evidence reviewed 6 items Current-main gap: The current-main resolver derives policy from the session key and root configuration, without the account and peer facts this branch forwards.
Proposed owner-boundary repair: The branch resolver accepts routed account and peer facts, resolves account configuration through the canonical helper, and retains whole-map DM replacement semantics.
Route propagation: Normal prompt preparation and direct compaction both forward account, peer, and chat-type facts to the history owner.
Findings None None.
Security None None.

How this fits together

The embedded agent runner selects transcript history and compacts conversations before sending context to model providers. Channel and Gateway route facts determine the account policy; the selected or compacted checkpoint is persisted for the next model request.

flowchart LR
  A[Channel or Gateway session] --> B[Account and peer facts]
  B --> C[Embedded agent history]
  C --> D[Provider compaction]
  D --> E[Persisted checkpoint]
  E --> F[Next model request]
Loading

Before merge

  • Resolve merge risk (P1) - This changes per-account history policy and persisted replay checkpoints; exact-head compatibility and session-lifecycle integration checks remain incomplete.
  • Resolve merge risk (P1) - The latest ClawSweeper rank-up-move text could not be verified from the supplied review context.
  • Complete next step (P2) - This active PR already owns the repair; it needs final integration validation rather than a parallel fix PR.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production vs test LOC Contributor-reported production/tooling +1,021/-233; tests/support +2,675/-146 The production growth implements account-aware replay and compaction behavior, so final compatibility and session validation matter before merge.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/history.ts, serialized state: src/config/sessions/conversation-registry.ts, serialized state: src/gateway/server-methods/sessions-compaction-runner.ts, unknown-data-model-change: src/agents/embedded-agent-runner/history.ts, unknown-data-model-change: src/agents/sessions/agent-session-inspection.ts, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete exact-head session validation (recommended)
    Finish the pending exact-head compatibility and session-lifecycle checks before merging a change to account policy and retained compaction state.
  2. Pause for integration evidence
    Pause the PR if exact-head validation cannot establish safe replay and session continuity on the final commit.

Technical review

Best possible solution:

Merge only after exact-head checks pass and the current ClawSweeper rank-up requirements are confirmed satisfied or explicitly waived.

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

Yes, from source: current main resolves history policy without account and peer facts, while the branch passes those facts through the prompt and compaction owners.

Is this the best way to solve the issue?

Yes: the repair places account and peer policy resolution in the shared history owner and forwards authoritative route facts through each caller instead of adding downstream fallbacks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0b0a64e7e30e.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The PR repairs account-specific history and compaction behavior in a live agent/session path.
  • merge-risk: 🚨 compatibility: Existing per-account channel configuration can change which retained history policy is selected after upgrade.
  • merge-risk: 🚨 session-state: The branch changes persistence and replay rules for compacted transcript checkpoints.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The branch's gateway E2E starts an ephemeral Gateway with controlled channel and model services, drives ingress and authenticated compaction through the production owners, and observes the resulting provider request and persisted checkpoint continuity. It is boundary proof for the changed path, though not an external-provider or live-Telegram demonstration.
  • proof: sufficient: Contributor real behavior proof is sufficient. The branch's gateway E2E starts an ephemeral Gateway with controlled channel and model services, drives ingress and authenticated compaction through the production owners, and observes the resulting provider request and persisted checkpoint continuity. It is boundary proof for the changed path, though not an external-provider or live-Telegram demonstration.

Evidence

Acceptance criteria:

  • [P1] Complete exact-head compatibility and session-lifecycle checks.
  • [P1] Verify the latest ClawSweeper rank-up requirements against the final head.

What I checked:

Likely related people:

  • steipete: The current branch rewrite and the surrounding embedded-runner history work are attributed to this contributor in the supplied PR history. (role: recent area contributor; confidence: medium; commits: bb3d9a22eeb7; files: src/agents/embedded-agent-runner/history.ts, src/agents/embedded-agent-runner/compaction-session-execution.ts)

Rank-up moves

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

  • Complete the pending exact-head compatibility and session-lifecycle checks.
  • Confirm that the latest ClawSweeper rank-up moves are satisfied or explicitly waived.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (44 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-25T06:57:15.722Z sha 77e926f37a100599c0f2d8e6d2951a771c0d9529 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-25T21:21:45.074Z sha 7cf55cfba6a96105dd7fcd2a80552ae640b365a1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-25T22:48:36.793Z sha af7f0522022fc9291e0d72501485510836b7bef1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-26T22:33:35.203Z sha 38a5767eed9b3aa333b0329289e01e811a0d4b28 :: needs real behavior proof before merge. :: [P1] Forward the route peer to Gateway compaction
  • reviewed 2026-08-28T22:39:31.292Z sha 1c087b97b7bb602187959f68493013dfc0b04e7b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T23:12:14.622Z sha 70382159812587afc4f9c00240449b6f1190987e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T00:10:25.400Z sha aa463aaa14a2538f1f7ec915bb0f7d3f2de88cf7 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-29T02:09:53.969Z sha aa463aaa14a2538f1f7ec915bb0f7d3f2de88cf7 :: needs maintainer review before merge. :: none

@ayaangazali

Copy link
Copy Markdown
Contributor Author

The P1 is correct and my PR body was wrong. I wrote that there was a single production call site; there are two, and I missed the second because I truncated my own call-site enumeration with head. Piping a completeness check into head is exactly the wrong move, and it cost the more important half of this fix.

src/agents/embedded-agent-runner/compaction-session-execution.ts:343 calls the same resolver with only session key and config, so an account-scoped limit applied correctly during prompt preparation and then reverted to the channel root the first time that session compacted. That is arguably worse than the original bug, because the limit would appear to work and then quietly change under the operator.

Fixed by forwarding the account id that file already had in scope (it passes params.agentAccountId to the compaction session at line 280):

getHistoryLimitFromSessionKey(params.sessionKey, params.config, params.agentAccountId),

For coverage I exposed the history mock the compaction harness was already installing (compact.hooks.harness.ts mocked ./history.js with an inline vi.fn, so nothing could assert against it) and added a compaction-path case in compact.hooks.test.ts that drives compactEmbeddedAgentSessionDirect with agentAccountId: "work" and asserts the resolver receives it as the third argument.

I checked the test actually pins the wiring by reverting the one-line fix and rerunning:

× passes the account id to the history limit resolver during compaction
Tests  1 failed | 124 passed (125)

then restored it for 125/125.

Current state on the rebased branch: compact.hooks.test.ts 125/125, history.test.ts 13/13, attempt.test.ts 120/120, oxlint clean, git diff --check clean. I am running the core test-types lane before I push, since that gate caught a real error on another PR of mine today that Vitest could not see.

I have corrected the "single production call site" claim in the PR body rather than leaving it there.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 4, 2026
@ayaangazali

Copy link
Copy Markdown
Contributor Author

build-artifacts is red here, and there is now cross-PR evidence that it is the suite rather than the diff.

The identical failure is happening on two of my open PRs whose diffs have nothing in common:

Both fail the same way, in the same suite:

src/tui/tui-pty-local.e2e.test.ts  "TUI PTY real backends > with shared Gateway fixture"
GatewayClientRequestTimeoutError: gateway request timeout for chat.history
Serialized Error: { method: 'sessions.create', timeoutMs: 30000, requestSent: true }
Error: Test timed out in 150000ms.

There is no single change that is simultaneously in the embedded agent runner and in a QQBot command string, so a shared real-Gateway PTY end-to-end suite timing out on 30s RPCs is the far more likely explanation than either diff.

Supporting detail: the string qqbot appears zero times in the #119357 failing log, there are no Cannot find module / ERR_MODULE / missing-export errors in either log, and a full rm -rf dist && pnpm build is clean on both branches with zero INEFFECTIVE_DYNAMIC_IMPORT warnings.

I am not pushing speculative commits to retrigger, and I cannot rerun jobs myself (gh run rerun returns "Must have admin rights to Repository"). A rerun of build-artifacts on either PR should settle it. If it reproduces on an unchanged head I will stop calling it flaky and go dig into the TUI fixture properly.

@ayaangazali

Copy link
Copy Markdown
Contributor Author

I dug into this properly rather than repeating my earlier "looks flaky", because you are right that build-artifacts is not failing on main. I confirmed that myself: it is success on main runs 30955211486, 30953366239, and 30953312453. So absence-on-main is not an argument, and this diff touches the core embedded agent runner, which the TUI end-to-end path genuinely exercises. That was a real mechanism I had not excluded.

So I ran the exact failing suite locally on this branch head (f5243ec81a3):

$ node scripts/run-vitest.mjs src/tui/tui-pty-local.e2e.test.ts
Test Files  1 passed (1)
     Tests  21 passed (21)
exit 0

It passes. And the durations explain the CI failure:

87695ms   83840ms   77887ms   62386ms   57870ms   53942ms

Those are individual test durations on a fast local machine, against the 150000ms per-test cap that CI reports hitting. A single test already consumes about 58% of the timeout budget when nothing else is competing for the box. On a loaded CI runner that margin disappears, which is exactly the failure signature in the log: Test timed out in 150000ms plus gateway request timeout for chat.history and sessions.create at timeoutMs: 30000, rather than any assertion failure.

The other reasons I do not think this diff is the cause:

  • the identical suite, with identical errors, also failed on fix(qqbot): honor the configured upgradeUrl in /bot-upgrade #119357, whose diff is a QQBot slash-command response string and cannot reach the agent runner at all
  • the failing log for this PR contains zero compact.hooks references, so the files I actually changed are not implicated
  • the production part of the last push is one line adding an existing in-scope argument to a pure synchronous function call; the rest is a test harness and a test

I am not pushing a speculative commit, per your instruction. I cannot rerun the job myself (gh run rerun returns "Must have admin rights to Repository"), so a rerun of build-artifacts is what I am asking for. If it reproduces on an unchanged head I will treat the timing margin above as a real regression signal and profile the TUI fixture rather than keep calling it environmental.

Separately, that margin looks worth a maintainer eye on its own: a real-backend suite whose slowest test sits at 87s against a 150s cap will keep producing red on unrelated PRs. Happy to file that as its own issue if useful.

@ayaangazali

Copy link
Copy Markdown
Contributor Author

The P1 is real and fixed, and it was a good catch on a subtlety I got wrong.

I had copied the exact-key lookup style from resolveChannelAccountMediaMaxMb, but the routed account identity is canonicalized, so accounts["Work Team"] never matched the routed work-team and those configs kept silently falling back to the root. That is the same bug this PR set out to fix, just moved one level down, which makes it worse than a cosmetic issue.

Now using the shared normalized lookup, the same way src/agents/acp-spawn-parent-stream.ts:163 handles the identical problem:

const accountConfig = trimmedAccountId
  ? resolveNormalizedAccountEntry(
      providerConfig.accounts,
      normalizeAccountId(trimmedAccountId),
      normalizeAccountId,
    )
  : undefined;

Note that plain resolveAccountEntry would not have been enough here: it falls back to a lowercase compare, so "Work Team" normalizes to "work team" and still misses the canonical "work-team". resolveNormalizedAccountEntry applies the canonical rule to both sides, which is why it is the right helper.

Coverage for the human-form key, as requested, across channel, DM, and per-DM precedence:

for (const accountId of ["work-team", "Work Team", "WORK TEAM"]) {
  expect(getHistoryLimitFromSessionKey("telegram:channel:c1", config, accountId)).toBe(40);
  expect(getHistoryLimitFromSessionKey("telegram:dm:999", config, accountId)).toBe(41);
  expect(getHistoryLimitFromSessionKey("telegram:dm:123", config, accountId)).toBe(42);
}

I confirmed that test fails against the old exact-key lookup (1 failed | 13 passed) and passes after, so it pins the behavior rather than just describing it.

On the real-behavior proof, being straight about what I have and have not got. I added coverage that drives the real resolver and the real limitHistoryTurns together and asserts on retained user turns, so the evidence is now about the transcript actually shrinking rather than about a returned number: an account limit of 2 keeps materially fewer turns than the channel root limit of 20 on the same 40-turn transcript, and an unrelated account id still gets the root behavior.

What I have not produced is a live channel transcript. The built dist is bundled, so I cannot import the resolver from it for a CLI-style before/after the way I did for the schema PRs, and history limiting has no operator-visible CLI surface to read back. The honest options I see are a qa mock-gateway scenario (needs OPENCLAW_BUILD_PRIVATE_QA=1 and a multi-turn scenario asserting retained context) or a live multi-account channel run. Say which you would accept and I will produce it rather than guess; I would rather ask than attach something that looks like runtime proof but is not.

Gates on the new head: history.test.ts 16/16, compact.hooks.test.ts 125/125, tsgo -p tsconfig.core.json clean, oxlint clean, git diff --check clean.

One local note in case it bites anyone else: right after rebasing onto current main I saw five TS2353 ... 'rejectSymlinks' does not exist in type 'OpenRootFileSyncParams' errors in files I had not touched. They reproduce on clean main and disappear after a pinned pnpm install, so it was stale node_modules against a dependency bump, not a code issue.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 5, 2026
@ayaangazali
ayaangazali force-pushed the fix/history-limit-account-scope branch from 7cf55cf to af7f052 Compare August 25, 2026 22:41
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 25, 2026
@steipete steipete self-assigned this Aug 26, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Improved the original repair in 38a5767eed9: authoritative route-peer disambiguation, queue propagation, numeric/colon peer regressions, and real endpoint message-input coverage. Configured Gateway and independent source-blind proof now cover 12 Telegram turns, whole-request account windows, actual sessions.compact, saved-checkpoint summary readback, and post-compaction prompt continuity. The updated body records both earlier failures and final passing evidence, exact production/test LOC, and the two deliberately preserved compatibility/product follow-ups. No native-runtime parity or authenticated external-service proof is claimed.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 26, 2026
@steipete
steipete force-pushed the fix/history-limit-account-scope branch from 38a5767 to 1c087b9 Compare August 28, 2026 22:31
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Rewritten head 1c087b97b7bb602187959f68493013dfc0b04e7b addresses both prior rank-up moves and the Gateway peer-routing finding. Manual compaction reads admitted current-primary peer/chat-kind facts from the existing conversation registry; no routing store was added. The compiled linked-DM flow now proves peer limit 2 instead of account 10/root 20.

Final local proof completed: full normal build and changed-file gates, independent Codex review, source-blind 19-turn/two-checkpoint Gateway continuity, visible no-provider-call /compact recovery, public full-history compaction followed by restart/continuation, and an actual pre-change reader/writer round trip with original rows preserved. Real OpenAI compact/continuation transport and Linux Gateway proof are separately identified in the updated body; controlled services are not described as authenticated provider proof.

The broader checkpoint repair was necessary to prevent short-window eviction from losing provider context. Complete output validation and replay stay with the provider/history owners. Deliberate transcript rewrite copies bypass only the already-checked ingestion lookup; ordinary ingestion remains deduplicated. Unsupported legacy checkpoints fail with the native recovery instruction rather than generic session-reset advice. Contributor credit is preserved. Exact-head hosted CI is pending; no merge is being claimed.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete

steipete commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Update: repaired and now rebased/pushed at bb3d9a22eeb79362f9f58f2f6a9e36d9eeb8bea6. The compact-only response byte limit runs before the normal OpenAI SDK parser; SDK-owned per-attempt body deadlines, retries and typed cancellation are restored. No duplicate timeout/retry implementation or relaxed size limit was added.

The installed OpenAI 7.5.0 regression first reproduced four failures, then all 83 focused tests across five files passed, including nine real HTTP/lifecycle controls. A stalled body now settles at 107 ms for a 100 ms deadline, with all fixture sockets closed. The embedded compaction safety owner remained bounded before and after. Authenticated OpenAI was repeated after the repair: two compact calls and six continuations, all HTTP 200, with exact complete-output hashes across reopen and eviction.

The preceding head passed changed-file checks and normal pnpm build; independent P0–P2 review is clean. Its CI 33222068278 failed in the main-introduced checkout-cleanup test. Repairs #132169, #132204 and #132203 are integrated through a clean rebase onto f93be5b5; the patch is unchanged apart from test-harness context. Rebased compaction hooks (154 tests) and nine real HTTP controls pass. Exact-head CI 33228608553, normal/private-QA builds and the final compiled-boundary repeat now pass. The repeat covers both Gateway compaction flows, 27 provider-replay tests and seven actual SQLite rewrite tests; the endpoint flow completes 18 turns across two checkpoint generations. Source stayed clean and the canonical build stamp matches the candidate. The SDK hold is resolved and native landing is proceeding. Gateway/database and Linux Testbox runs use controlled provider services; authenticated OpenAI transport is separate, not authenticated OpenAI inside Testbox.

Original pre-land finding: the rewrite's .asResponse() reader bypassed SDK body parsing and its timeout/retry/cancellation guarantees. A real loopback server sending HTTP 200 headers plus partial JSON stalled until fixture cleanup; body-timeout retries did not occur and caller cancellation returned a raw DOMException. The ordinary success, HTTP-status retry and 16 MiB controls passed. The reusable transport was defective even though the embedded agent's separate safety owner stayed bounded. That path has now been removed.

steipete and others added 6 commits August 28, 2026 19:10
Honor admitted account and peer policy, retain complete bounded provider checkpoints across short history windows, and recover unsupported replay from durable conversation history.

Co-authored-by: ayaangazali <[email protected]>
Bound compaction response bytes before SDK parsing so request deadlines, body retries, and typed cancellation retain their canonical owner.

Co-authored-by: ayaangazali <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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: anthropic gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

3 participants