Skip to content

fix(gateway): scope the JSONL transcript usage estimate to the live window across boundaries - #150641

Open
he-yufeng wants to merge 15 commits into
openclaw:mainfrom
he-yufeng:fix/transcript-usage-estimate-active-window
Open

he-yufeng wants to merge 15 commits into
openclaw:mainfrom
he-yufeng:fix/transcript-usage-estimate-active-window

Conversation

@he-yufeng

@he-yufeng he-yufeng commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Refs #150579

What Problem This Solves

A compacted session's transcript usage report (the JSONL artifact seam behind diagnostic reads) counted the whole append-only archive as live context. Content superseded by a compaction or reset stays in the file, and the chars-based estimate summed every user/assistant message ever written, so the reported total kept growing across clean compactions while the model's actual context stayed small.

A second gap sat next to it: once the estimate restarted at a boundary, eligibility was re-derived only from model-tagged assistant entries in the retained window. A summary-only window (the cut names an entry outside the message window) or a retained-user-only window (overflow compaction with a pending user message as its tail) lost the estimate until the next assistant reply, even though the summary and retained text were sitting in the model context.

Root cause

aggregateSessionTranscriptUsage fills totalTokens from a chars estimate when no per-call usage snapshot provides one. readLatestSessionUsageFromTranscriptFileAsync feeds it the full JSONL transcript, and the estimate accumulated estimatedTranscriptChars over the whole scanned set with no notion of boundary markers or the retained window they name. The boundary restart also reset sawEstimateModelIdentity from the retained entries alone, while finish() requires that flag, so any window without a surviving model-tagged assistant reported no estimate at all.

Fix

  • The JSONL reader passes compaction/reset boundary records through with their summary/firstKeptEntryId fields, and forwards each entry's id, instead of skipping markers.
  • The accumulator keeps per-entry char counts for the current window. At a boundary it keeps the retained tail named by firstKeptEntryId plus the compaction summary, matching the model-context contract (compactionSummary + retained entries + post-boundary messages) and the transcript tree selector's fallback (an unknown kept target drops the pre-boundary window). The previous revision restarted the estimate at zero, which undercounts a compacted session that retains a large summary or window.
  • A boundary leaves the window estimate-eligible whenever it holds counted text. A compaction or reset marker is only written by a live model session, so requiring a model-tagged assistant to survive the cut only masked reads taken between the boundary and the next reply.
  • Usage snapshots (input/output/cache/cost) still aggregate over the whole record, and a fresh per-call totalTokens snapshot still wins over any estimate, unchanged.

Scope

This change lives entirely in the JSONL artifact seam: readLatestSessionUsageFromTranscriptFileAsync reads bounded transcript artifacts and its callers are diagnostic paths. The live budget-preflight path from #150579 reads the SQLite seam, which already scopes to the active context and is untouched here; that preflight symptom stays with #150579 and the PRs addressing it directly. This branch does not close the issue.

Evidence

  • New regressions in session-usage-estimate.test.ts: a compaction keeps its 500-char summary plus the 2000-char retained message named by firstKeptEntryId while dropping the 4000-char superseded prefix; a reset keeps its named retained tail; an unknown kept target drops the pre-boundary window but still counts the summary. Three further regressions end the transcript right at the boundary (summary-only window, compaction retaining only user messages, reset retaining only user text), covering the read between the boundary and the next assistant reply; earlier versions of these tests appended that reply, which masked the eligibility drop.
  • Red/green: the boundary-terminal three fail on the previous head (no estimate reported). The consolidated table preserves all 10 independent scenarios, including snapshot precedence, reset boundaries, retained-user-only windows and the structural anchor.
  • Runtime proof on a real compacted session (regenerated after the earlier /tmp artifact expired): isolated Gateway plus embedded agent against the scripted provider; a real injected 400 context_length_exceeded, one committed auto-compaction, then one more turn. The committed marker carries a 464-char summary and names a retained 91-char user message as firstKeptEntryId, so the boundary leaves a summary-plus-retained-user window. The artifact is the session's real settled transcript events serialized back to legacy JSONL, with redacted variants that drop usage fields and the model-snapshot entry so the chars estimate is what gets measured. The after-fix reader reports totalTokens: 139 on the redacted prefix ending at the boundary (ceil((464 + 91) / 4), the summary plus the retained user text) and 176 on the full redacted artifact (ceil((464 + 91 + 56 + 90) / 4), adding the post-boundary assistant and user text). On the usage-carrying artifact the reader still reports the real provider aggregates (input 105 / output 25, latest context snapshot 120 total and available), so the estimate path and the snapshot path stay separate.
  • Current head dcfc49a70dfb, including upstream main 3f2e7078de23: node scripts/test-projects.mts src/gateway/session-usage-estimate.test.ts src/gateway/session-transcript-derived-readers.usage.test.ts src/gateway/session-utils.fs.test.ts src/gateway/session-utils.transcript-usage.test.ts --maxWorkers=1 passes 4 files and 50 tests. oxfmt and direct type-aware oxlint pass on the consolidated test; the net PR diff passes git diff --check.
  • Shipped diagnostic builder proof on 591ef68b2e9: the real settled Gateway compaction events drive the production buildReplyDiagnosticsPayload raw diagnostic path through readLatestSessionUsageFromTranscriptAsync, not just a direct reader call. With usage fields removed, the boundary-terminal artifact emits total=139 and the full artifact emits total=176. The measured control emits input=105, output=25, cacheRead=0, cacheWrite=0, total=120. The probe prints only the session usage block, with no transcript text, credentials or endpoints.
  • Shipped request proof on 1ea8830335d8: agent-runner-result.shipped-diagnostic-usage.test.ts drives finalizeReplyAgentRun, the exported entry the reply pipeline calls, and reads the rendered Usage (Session Total) block out of the returned payloads. The diagnostic is reached through prepareReplyAgentPayloads and accountAgentTurn, not by naming the builder. Two cases: the retained window plus compaction summary is estimated while the superseded archive is not (total=629 tok against a 4000-char archived prefix that would otherwise inflate it), and a later per-call snapshot still wins (total=1,234 tok). Red-green through that same shipped path: dropping the boundary's window reset in session-transcript-derived-readers.ts renders total=1,504 tok and fails the first case; restoring it passes, and the production file is byte-identical to its committed state afterwards. 2 + 2 + 1 tests pass across the new file, the builder-level file and the existing silent-reply usage test. oxlint and oxfmt are clean on the new file; the repo-wide oxlint wrapper cannot run in this checkout because its plugin-sdk boundary step rejects a node_modules realpath resolving into a sibling worktree, so the binary was invoked directly on the changed file. A 112-line allocation is registered and the test-lines ratchet passes with slack 0.
  • Test budget: the four repeated retained-window fixtures now share one table helper, preserving all 10 scenarios while reducing the new test file from 157 to 145 lines. config/test-lines-allocations/session-usage-active-window.txt grants exactly those 145 added lines. The full-index ratchet on current head dcfc49a70dfb, using hosted CI's current main 3f2e7078de23 with --no-merge-base, reports Test lines OK: 6561328; ceiling: 6561328; slack: 0. An earlier sparse local run omitted 566 tracked test lines and produced a false slack result; materializing those files reproduced hosted CI's over-10 failure before this consolidation.

[AI-assisted] prepared with Kimi K3; verified locally as described above and reviewed line by line.

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 17, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Scope fallback token estimates to the compaction summary, retained entries, and subsequent messages while preserving measured usage.

Example: A JSONL artifact contains a 4000-character archived message, a retained 2000-character message, a 500-character summary, and a 15-character live tail.

  • Before: The estimate includes archived text and reports 1504 tokens.
  • After: The estimate includes the retained window and summary and reports 629 tokens.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused repair has useful production-path regression coverage, but submitted runtime evidence stops short of the required request boundary.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Raw diagnostics can present superseded transcript history as current context when provider usage telemetry is absent.
Reason: The remaining diagnostic defect is concrete, and the production repair uses the existing reader and accumulator without adding configuration or changing persistence.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this PR fixes a distinct JSONL diagnostic overestimate still present on current main; no blocking correctness defect was found.

Priority: P2
Reviewed head: 1ea8830335d806d804dac5e95f6315ea47746a10

Before merge

  • Add real behavior proof - Earlier real-compaction artifacts produced 139/176-token estimates and an unchanged 120-token measured control through direct reader/builder calls; the latest head adds a synthetic-artifact finalization test reporting 629/1234, but neither demonstrates the required shipped CLI or Gateway diagnostic request. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Await maintainer action - Authorize the exact-head GitHub Actions workflows currently marked action_required and allow the required checks to complete.

Findings

None.

Tests

  • Low-value test src/auto-reply/reply/agent-runner-result-diagnostics.artifact-usage.test.ts: Remove this builder-level suite and its allocation: both retained-window rendering and snapshot precedence are repeated with the same fixtures through the stronger finalizeReplyAgentRun integration, without a distinct transport or lifecycle failure.
  • Missing end-to-end proof: Provide redacted terminal output or logs from an actual CLI or Gateway diagnostic request reading a compacted JSONL artifact, showing the retained-window estimate and measured-snapshot control; redact IPs, API keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

Authorized raw reply diagnostics read legacy JSONL artifacts through the transcript usage seam and render the resulting usage snapshot in reply payloads.

flowchart TD
  A[Raw reply diagnostic] --> B[Reply finalization]
  B --> C[Transcript usage seam]
  C --> D[JSONL artifact reader]
  D --> E[Usage accumulator]
  E --> F[Rendered session usage]
Loading

Technical review

Best possible solution:

Keep the focused boundary-aware estimate in the existing accumulator and retain one diagnostic integration suite alongside the distinct reader regressions.

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

Current-main source demonstrably sums superseded JSONL messages; contributor-reported red/green results cover the same failure, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The production change repairs the estimate at its existing owner, preserves snapshot precedence, and leaves SQLite behavior unchanged; the redundant builder-level tests can be removed.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit a6b8eb5 adds src/gateway/session-transcript-derived-readers.ts:151 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a6b8eb5b418d; files: src/gateway/session-transcript-derived-readers.ts)

PR surface

Source +61, Tests +344, Other +6. Total +411 across 8 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 2 64 3 +61
Tests 3 344 0 +344
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 6 0 +6
Total 8 414 3 +411

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test growth Production +64/-3 lines; tests +344/-0 lines Per-entry counts support retained-window selection; the additional builder-level suite duplicates scenarios now covered through reply finalization.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Incorrect fallback usage appears in optional raw diagnostics; the live preflight repair is separate and already merged.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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 (19 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-09T00:02:09.980Z sha 6c35a02 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-16T17:11:49.096Z sha 6c35a02 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-05T21:33:32.593Z sha c48e0fc :: needs changes before merge. :: [P2] Allocate the added regression-test lines
  • reviewed 2026-11-06T21:59:36.063Z sha ba75424 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-06T22:21:13.079Z sha 591ef68 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-06T22:51:52.726Z sha 591ef68 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-08T17:47:14.313Z sha dcfc49a :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-15T02:23:25.229Z sha e860cb8 :: needs real behavior proof before merge. :: none

Reviewed November 15, 2026, 6:46 AM ET / 11:46 UTC (Revision 20).

@he-yufeng
he-yufeng force-pushed the fix/transcript-usage-estimate-active-window branch from c102fb1 to a1fedb4 Compare September 17, 2026 21:33
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 17, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Sep 17, 2026
@he-yufeng
he-yufeng force-pushed the fix/transcript-usage-estimate-active-window branch from a1fedb4 to e0eae47 Compare September 17, 2026 23:26
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Sep 17, 2026
@he-yufeng
he-yufeng force-pushed the fix/transcript-usage-estimate-active-window branch from e0eae47 to 8de22e7 Compare September 18, 2026 05:15
@he-yufeng
he-yufeng requested a review from a team as a code owner September 18, 2026 05:15
@github-actions github-actions Bot added the dependencies-changed PR changes dependency-related files label Sep 18, 2026
@he-yufeng
he-yufeng force-pushed the fix/transcript-usage-estimate-active-window branch from 8de22e7 to 7467d58 Compare September 18, 2026 05:16
@github-actions github-actions Bot removed the dependencies-changed PR changes dependency-related files label Sep 18, 2026
@he-yufeng

Copy link
Copy Markdown
Contributor Author

CI note on the checks-node-compact-small-28 red: the failing assertion (ci-node-test-plan.mts > "preserves coverage and execution policies with committed compact measurements") passes locally on this head, and the same lane family is red on unrelated current PRs (e.g. #152127 fails -12/-14, #152128 fails -12/-14 while their other variants pass), which reads as committed-plan drift against current main rather than anything in this diff. The rest of the lanes are green. If a maintainer has the sanctioned refresh for the committed compact plan, I'll run it; otherwise this should clear once main's plan is refreshed.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

CI refresh on 44bc990 (merged current main in to clear the stale-plan drift behind the checks-node-compact-small-28 red, which is green again on the merged tree locally).

The merge needed one real repair, and I want it on record: main's accumulator refactor (createSessionTranscriptUsageAccumulator) landed on the same lines as this PR's boundary-reset block, and the textual merge produced two silent breakages that only the tests caught:

  • the PR's continue inside the old loop body became an illegal continue inside main's add arrow function (SyntaxError at import), now return;
  • the PR's messages.push({ type }) boundary forwarding referenced the array main's streaming reader deleted, so boundary markers hit a ReferenceError swallowed by the inner catch and were dropped — the chars estimate never restarted. Now forwarded as usageAccumulator.add({ type: record.type }).

Evidence (macOS arm64, Node 22, merged tree): the previously red plan test (preserves coverage and execution policies with committed compact measurements) passes; session-usage-estimate.test.ts red on the un-repaired merge (expected 1004 to be 4 — the estimate was counting the superseded archive) and green after; the session-area sweep (session-transcript-readers, session-utils.fs, session-utils.fs.preview, session-usage-estimate: 94 tests) is green; oxlint 0/0 and oxfmt clean on the two touched files. A fresh-context independent review of the merged delta found 0 issues.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Runtime follow-up on a real compacted session (after-fix, redacted).

Setup: isolated OPENCLAW_HOME, gateway plus embedded agent, OpenRouter deepseek/deepseek-chat pinned to contextTokens: 12000 so compaction fires naturally. Drove one long turn (a 16,258-char request); the runtime auto-compacted the session twice during the run, and openclaw sessions read the meter at 49k/12k (409%), which is the production symptom of this issue.

Artifact: the session's real transcript events from the canonical store, serialized back to the legacy JSONL shape (11 lines: session header, three 16,258-char user messages, compaction #1, a user message, a short assistant tail, a bootstrap event, compaction #2). Nothing hand-authored. A redacted variant drops the usage fields and the model-snapshot event so the chars estimate is what gets measured (older transcripts genuinely lack usage).

After-fix reader output on the real file:

{
  "modelProvider": "openrouter",
  "model": "deepseek/deepseek-chat"
}

The estimate now covers only the live window after the latest compaction: empty here, so no totalTokens is reported. The same reader on the same archive without the later boundary (exactly what the old code measures on the full file, since it never restarts):

{
  "modelProvider": "openrouter",
  "model": "deepseek/deepseek-chat",
  "totalTokens": 4065,
  "totalTokensFresh": true
}

4065 tokens of superseded history read as live context on a twice-compacted session: that is the misfire, and it is gone after the fix.

The aggregate side is untouched: on the usage-carrying artifact the reader still reports the real provider totals (49,037 input / 1 output / $0.0126), confirming that usage snapshots aggregate across boundaries by design while only the estimate restarts.

[AI-assisted] — session driven and outputs captured locally as described.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

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

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed 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. labels Sep 21, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 6, 2026
@he-yufeng

Copy link
Copy Markdown
Contributor Author

The first hosted run on ba754249ac3 exposed a different base state from the local acceptance command: its merge with e29577b7d7df was over the test-line ceiling by 49 despite the exact 157-line allocation. I did not inflate the allocation or delete unrelated tests.

Current main 936f38793bab now includes #194326, which consolidates 610 UI test lines and removes that base debt. Merged it into 591ef68b2e9. On this exact merge head, the four usage suites still pass 50/50 and the ratchet against current main reports 6555349 / 6555910, slack 561. The net PR diff remains the two production files, the consolidated regression file and its 157-line allocation.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Correction to my previous ratchet note: slack 561 came from a non-staged sparse-worktree count that omitted 566 tracked test lines. The full-index command reproduces hosted CI exactly: 6555915 / 6555910, over 5 with net delta +157. That slack claim was my measurement error and is withdrawn in the PR body. The 157-line allocation remains exact, and I have not inflated it or changed the shared scalar.

Shipped diagnostic proof on 591ef68b2e9, using the same real isolated Gateway compaction's 19 settled events documented earlier. The probe calls production buildReplyDiagnosticsPayload, which follows the shipped raw reply diagnostic path into readLatestSessionUsageFromTranscriptAsync and the changed artifact reader. It prints only the session usage block, with no transcript text, credentials or endpoints.

Boundary-terminal artifact, ending at the real compaction whose 464-char summary names the 91-char retained user message, with usage fields removed:

🔎 Usage (Session Total):
input=n/a
output=n/a
cacheRead=n/a
cacheWrite=n/a
total=139 tok (139)

Full artifact with usage fields removed:

🔎 Usage (Session Total):
input=n/a
output=n/a
cacheRead=n/a
cacheWrite=n/a
total=176 tok (176)

Full measured control, preserving the real provider usage fields:

🔎 Usage (Session Total):
input=105 tok (105)
output=25 tok (25)
cacheRead=0 tok (0)
cacheWrite=0 tok (0)
total=120 tok (120)

The estimates still match ceil((464 + 91) / 4) = 139 and ceil((464 + 91 + 56 + 90) / 4) = 176. The measured control is unchanged. The PR body now records this shipped-path evidence.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@he-yufeng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

The reviewer asked for a shipped request path, not only the reader in
process. Drive buildReplyDiagnosticsPayload with an absolute JSONL
sessionFile and read the rendered "Usage (Session Total)" block, which is
what a raw trace reply shows.
@he-yufeng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the remaining "real behavior proof" item with a shipped request path rather than more in-process output.

src/auto-reply/reply/agent-runner-result-diagnostics.artifact-usage.test.ts calls buildReplyDiagnosticsPayload — the same function finalizeReplyAgentRun uses for a raw trace reply — with an absolute .jsonl sessionFile, then reads the rendered 🔎 Usage (Session Total) block out of the payload text. That is the diagnostic a user actually sees, not the reader's return value.

Two cases, both on the real artifact reader with no mocks:

  • A transcript with a 4000-char archived assistant message, a retained 2000-char user message, a compaction naming that message as firstKeptEntryId with a 500-char summary, and a short live tail. The rendered block reports total=629 tok, the retained window plus summary plus tail. It also asserts that number is strictly below the whole-archive estimate, so a pass cannot come from counting everything.
  • A later per-call snapshot (input: 1000, cacheRead: 234) still renders total=1,234 tok, so the estimate never overtakes a measured total.

Red-green on this head: with the boundary handling in createSessionTranscriptUsageAccumulator removed so a compaction no longer restarts the window, the first case renders total=1,504 tok (1.5k) and fails; restored, it passes. The snapshot case passes both ways, which is the point — it is the control.

src/gateway/session-usage-estimate.test.ts                                    10 passed
src/auto-reply/reply/agent-runner-result-diagnostics.artifact-usage.test.ts    2 passed
src/auto-reply/reply/agent-runner-result-diagnostics.test.ts                   5 passed
src/auto-reply/reply/agent-runner-result.usage-diagnostics.test.ts             1 passed

oxlint and the repo formatter are clean on the new file. check-test-lines-ratchet.mts --base HEAD passes with the 87-line allocation in config/test-lines-allocations/raw-diagnostic-artifact-usage.txt.

Still not covered: a live Gateway session against a real provider. This host has no channel credentials, so the proof is the shipped diagnostic builder over a real JSONL artifact rather than a recorded production session. Saying so plainly rather than implying more.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

The reviewer asked for a shipped CLI or Gateway diagnostic request, not
the reader in process. The previous test drove buildReplyDiagnosticsPayload
directly, which is the composition step, not the request a user issues.

Drive finalizeReplyAgentRun instead. That is the exported entry the reply
pipeline calls, and it reaches the diagnostic through prepareReplyAgentPayloads
and accountAgentTurn rather than by naming the builder. Read the rendered
"Usage (Session Total)" block out of the returned payloads.

Two cases, same contract as the reader-level test: the retained window and
compaction summary are estimated while the superseded archive is not, and a
later per-call snapshot still wins over any estimate.

Red-green through the shipped path: dropping the boundary's window reset in
session-transcript-derived-readers.ts makes the first case render
total=1,504 tok instead of total=629 tok and fail; restoring it passes. The
production file is byte-identical to its committed state afterwards.

  agent-runner-result.shipped-diagnostic-usage.test.ts   2 passed
  agent-runner-result-diagnostics.artifact-usage.test.ts 2 passed
  agent-runner-result.usage-diagnostics.test.ts          1 passed

oxlint and oxfmt clean on the new file. The repo-wide oxlint wrapper cannot
run in this checkout: its plugin-sdk boundary step rejects a node_modules
realpath that resolves into a sibling worktree, so the binary was invoked
directly on the changed file instead. Test-lines ratchet passes with a
112-line allocation registered for the new file.
@he-yufeng

Copy link
Copy Markdown
Contributor Author

The shipped-request gate is now addressed on 1ea8830335d8.

agent-runner-result.shipped-diagnostic-usage.test.ts drives finalizeReplyAgentRun, the exported entry the reply pipeline calls, and reads the rendered Usage (Session Total) block out of the returned payloads. The diagnostic is reached through prepareReplyAgentPayloads and accountAgentTurn; the test never names buildReplyDiagnosticsPayload.

Two cases through that path:

  • retained window plus compaction summary estimated, superseded archive excluded: total=629 tok, with an assertion that this is strictly below the estimate that would include the 4000-char archived prefix
  • a later per-call snapshot still wins over any estimate: total=1,234 tok

Red-green through the shipped path, not just the reader: dropping the boundary's window reset in session-transcript-derived-readers.ts makes the first case render total=1,504 tok and fail; restoring it passes. The production file is byte-identical to its committed state afterwards (sha256 350e030ce522… before and after).

Getting the shipped path to actually reach the artifact reader took two corrections worth recording, since they are properties of the path rather than of the fixture: the reply context carries a concrete storePath, so the reader takes the store-scoped branch and the artifact must resolve inside that sessions directory; and the chars estimate requires a model-tagged assistant entry, so the archived and tail entries carry provider/model. Without both, the shipped reply renders the Context Window and Request Shaping blocks but no Session Total at all, which is what my first three probes showed.

Tests: 2 passed in the new file, 2 in the builder-level file, 1 in the existing silent-reply usage test. oxlint and oxfmt clean on the new file. The repo-wide oxlint wrapper cannot run in this checkout because its plugin-sdk boundary step rejects a node_modules realpath resolving into a sibling worktree, so I invoked the binary directly on the changed file and am reporting that rather than claiming the wrapper passed. A 112-line allocation is registered; the test-lines ratchet passes with slack 0.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@he-yufeng

Copy link
Copy Markdown
Contributor Author

@vincentkoc @steipete Could I get a human review of 1ea88303?

The usage estimate should cover the live model window across compaction boundaries: the compaction summary, the retained tail named by firstKeptEntryId, and post-boundary messages, rather than restarting from zero or counting the whole transcript again.

Could you check that ownership against the current transcript accumulator and the shipped diagnostic reply path? The PR includes a real compacted-session reproduction and shipped-entry tests. The current rollup still has one failure and two cancellations, so this is a request for the correctness and ownership decision, not a merge-ready claim.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant