Skip to content

chore(cli): cover Claude multi-call turn usage - #148676

Open
RileyJJY wants to merge 1 commit into
openclaw:mainfrom
RileyJJY:sunlit/fix/issue-148603
Open

RileyJJY wants to merge 1 commit into
openclaw:mainfrom
RileyJJY:sunlit/fix/issue-148603

Conversation

@RileyJJY

@RileyJJY RileyJJY commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

This follow-up adds regression coverage for Claude CLI turns that previously persisted only the final model call's usage.

Related: #148603

Why This Change Was Made

The CLI output contract separates latest-call usage from terminal cumulative diagnosticUsage. Following the rebase, the canonical transcript persistence path and the companion context-marker and aggregate-pricing consumer fixes are present in current main; the consumer PR #148682 has merged. This branch adds regression coverage for terminal cumulative counters, preservation of the latest-call marker, and memory-flush preflight sizing from that marker. Backends without terminal cumulative usage keep their existing unmarked counters.

User Impact

No direct user-visible change; the tests keep multi-call turn totals and final-call context accounting covered.

Evidence

  • Production call chain: runPreparedCliAgent and command transcript persistence use the canonical CLI usage projection; the added tests cover terminal totals, the final-call context marker, and preflight sizing from the marker-derived 86,876 prompt plus 2,000 output tokens.
  • Fresh production call-chain proof: runPreparedCliAgent launched the installed Claude CLI (claude 2.1.263) with --output-format stream-json; Claude completed a tool-using turn through a localhost Anthropic-compatible boundary, and OpenClaw persisted terminal cumulative counters plus the final-call context marker to SQLite.
  • At exact HEAD 485814f8900f8ba5d38c02bf6105a0a5746c1330, agentMeta.usage and lastCallUsage were 30/15; diagnosticUsage and transcript counters were 52/27 (79 total), with a transcript context marker of 30/45. The process exited 0 after writing the SQLite clean-close receipt.
  • Direct external Claude access was unavailable in this environment: the configured proxy returned 402 Insufficient Balance, while the official endpoint had no usable login. The loopback server replaces only that external network boundary; the Claude CLI process, tool execution, JSONL parsing, settlement, and transcript persistence are real.
  • Canonical contract: diagnosticUsage is terminal cumulative usage while usage remains the per-call snapshot; transcript writers preserve the latest-call contextUsage marker, and the parser contract is covered by src/agents/cli-output-jsonl.test.ts.
  • Compaction and upgrade compatibility: pre-prompt memory flush stops at unavailable context, ignores legacy CLI usage on the first upgraded turn, and accepts the additive contextUsage marker; these mixed legacy/new cases are covered in src/auto-reply/reply/agent-runner-memory.test.ts. No migration is required because the marker is optional and legacy rows remain readable.
  • Regression negative control: on pre-fix parent 16a3787ba105b71a72843941dcdf1c78634b752c, the new production-path test fails at persistence: it records last-call usage 2/1/27376 with no context marker instead of 6/77/54631 and marker 27378/27379. Redacted failure excerpt SHA-256: bca7a823257493cf44129e945775cb78ed87965f780d78a6146ed01c0c983881.
  • At exact current HEAD 485814f8900f8ba5d38c02bf6105a0a5746c1330, the fresh Claude CLI proof passed. After review edits, three focused suites passed 12/12; the mock-export ratchet, agents-root test type graph, and git diff --check passed.
  • Review cleanup removes the duplicate command-persistence test, preserves real exports in the CLI runner mocks, and documents the four isolated state mocks required by src/agents/AGENTS.md. Prior CI's admissionGraceMs test type error and mock-export failure match those fixes; the production type job reports DOM type errors only in untouched UI files. Fresh proof output SHA-256: 84a40bb3812f1acce2ffa46fa744efe1f54ea61c394366819fb902da475cbdcb.
$ rtk ./node_modules/.bin/tsx proof-live.mts
entrypoint: runPreparedCliAgent -> claude -p --output-format stream-json -> SQLite transcript persistence
dependency-boundary: localhost Anthropic Messages API loopback
head: 485814f8900f8ba5d38c02bf6105a0a5746c1330
claude: 2.1.263; cliRequests=3; toolResultRequests=1
visibleAssistantText: DONE; persistedAssistantText: DONE
agentMeta.usage: input=30, output=15
agentMeta.lastCallUsage: input=30, output=15
agentMeta.diagnosticUsage: input=52, output=27
transcript.usage: input=52, output=27, totalTokens=79, contextUsage.promptTokens=30, contextUsage.totalTokens=45
latest-call context stayed 30/15 while transcript counters used the 52/27 turn total
proof-live.mts
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { createServer } from "node:http";
import { execFileSync } from "node:child_process";
import { loadTranscriptEvents } from "./src/config/sessions/session-accessor.js";
import { upsertSessionEntry } from "./src/plugin-sdk/session-store-runtime.js";
import { prepareSystemAgentRunAdmission } from "./src/agents/admitted-run-context.js";
import { runPreparedCliAgent } from "./src/agents/cli-runner.js";
import { buildPreparedCliRunContext } from "./src/agents/cli-runner.test-helpers.js";
import {
  closeOpenClawAgentDatabasesAsync,
  closeOpenClawAgentDatabasesForTest,
} from "./src/state/openclaw-agent-db.js";

let requestCount = 0;
let toolResultRequests = 0;
function event(response: import("node:http").ServerResponse, name: string, data: unknown) {
  response.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
}

function sendResponse(
  response: import("node:http").ServerResponse,
  toolTurn: boolean,
  toolId: string,
) {
  const input = toolTurn ? 11 : 30;
  const output = toolTurn ? 6 : 15;
  event(response, "message_start", {
    type: "message_start",
    message: {
      id: toolTurn ? "msg-proof-tool" : "msg-proof-final",
      type: "message",
      role: "assistant",
      model: "claude-sonnet-4-6",
      content: [],
      stop_reason: null,
      stop_sequence: null,
      usage: { input_tokens: input, output_tokens: output, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 },
    },
  });
  if (toolTurn) {
    event(response, "content_block_start", {
      type: "content_block_start",
      index: 0,
      content_block: { type: "tool_use", id: toolId, name: "Bash", input: {} },
    });
    event(response, "content_block_delta", {
      type: "content_block_delta",
      index: 0,
      delta: { type: "input_json_delta", partial_json: '{"command":"printf tool-turn-proof"}' },
    });
  } else {
    event(response, "content_block_start", {
      type: "content_block_start",
      index: 0,
      content_block: { type: "text", text: "" },
    });
    event(response, "content_block_delta", {
      type: "content_block_delta",
      index: 0,
      delta: { type: "text_delta", text: "DONE" },
    });
  }
  event(response, "content_block_stop", { type: "content_block_stop", index: 0 });
  event(response, "message_delta", {
    type: "message_delta",
    delta: { stop_reason: toolTurn ? "tool_use" : "end_turn", stop_sequence: null },
    usage: toolTurn
      ? { output_tokens: output }
      : { input_tokens: 41, output_tokens: 21 },
  });
  event(response, "message_stop", { type: "message_stop" });
  response.end();
}

const server = createServer((request, response) => {
  const requestPath = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  if (request.method !== "POST" || requestPath !== "/v1/messages") {
    response.writeHead(404).end();
    return;
  }
  requestCount += 1;
  const requestBody: Buffer[] = [];
  request.on("data", (chunk: Buffer) => requestBody.push(chunk));
  request.on("end", () => {
    const requestText = Buffer.concat(requestBody).toString("utf8");
    let contentTypes: string[] = [];
    let requestShape = "unavailable";
    try {
      const parsed = JSON.parse(requestText) as {
        model?: string;
        tools?: Array<{ name?: string }>;
        messages?: Array<{ role?: string; content?: Array<{ type?: string }> | string }>;
      };
      const messages = parsed.messages ?? [];
      contentTypes = messages.flatMap((message) =>
        Array.isArray(message.content)
          ? message.content.flatMap((content) => (content.type ? [content.type] : []))
          : [],
      );
      requestShape = JSON.stringify({
        model: parsed.model,
        tools: (parsed.tools ?? []).map((tool) => tool.name),
        roles: messages.map((message) => message.role),
        hasPrompt: requestText.includes("Use the Bash tool to run printf tool-turn-proof, then reply DONE."),
        hasToolResult: contentTypes.includes("tool_result"),
      });
    } catch {
      contentTypes = ["invalid-json"];
    }
    const markers = ["Bash", "tool-turn-proof", "tool_result"].filter((marker) =>
      requestText.includes(marker),
    );
    console.error(`PROOF_REQUEST=${requestCount} bytes=${requestText.length} contentTypes=${contentTypes.join(",") || "none"} shape=${requestShape} markers=${markers.join(",") || "none"}`);
    const hasToolResult = contentTypes.includes("tool_result");
    if (hasToolResult) toolResultRequests += 1;
    response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
    sendResponse(response, !hasToolResult, `toolu-proof-${requestCount}`);
  });
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("proof server did not bind");

const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cli-usage-proof-"));
const sessionTarget = {
  agentId: "main",
  sessionId: "proof-session",
  sessionKey: "agent:main:proof-usage",
  storePath: path.join(root, "agents", "main", "agent", "openclaw-agent.sqlite"),
};
process.env.OPENCLAW_STATE_DIR = root;
process.env.OPENCLAW_CLI_BACKEND_LOG_OUTPUT = "1";
await upsertSessionEntry({ ...sessionTarget, entry: { sessionId: sessionTarget.sessionId, updatedAt: Date.now() } });

const context = buildPreparedCliRunContext({
  provider: "claude-cli",
  model: "claude-sonnet-4-6",
  workspaceDir: root,
  sessionId: sessionTarget.sessionId,
  sessionKey: sessionTarget.sessionKey,
  sessionTarget,
  prompt: "Use the Bash tool to run printf tool-turn-proof, then reply DONE.",
  timeoutMs: 20_000,
  backend: {
    command: "claude",
    args: [
      "-p",
      "--output-format",
      "stream-json",
      "--verbose",
      "--no-session-persistence",
      "--setting-sources",
      "local",
      "--allowedTools",
      "Bash(printf *)",
      "--permission-mode",
      "dontAsk",
    ],
    sessionMode: "none",
    systemPromptFileArg: undefined,
  },
  preparedEnv: {
    ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
    ANTHROPIC_API_KEY: "loopback-proof",
  },
});
context.params.sessionFile = sessionTarget.sessionKey;
context.params.storePath = sessionTarget.storePath;
context.params.persistAssistantTranscript = true;
context.hadSessionFile = true;
const admission = prepareSystemAgentRunAdmission({}, context.params.runId, "main", "proof");
context.params.admittedRunContext = await admission.admit("embedded");

try {
  const result = await runPreparedCliAgent(context);
  const messages = (await loadTranscriptEvents(sessionTarget)).flatMap((eventRecord) =>
    typeof eventRecord === "object" && eventRecord !== null && "message" in eventRecord
      ? [eventRecord.message]
      : [],
  );
  const assistant = messages.find(
    (message): message is { role: "assistant"; usage?: unknown; content?: unknown } =>
      typeof message === "object" && message !== null && "role" in message && message.role === "assistant",
  );
  const persistedAssistantText = Array.isArray(assistant?.content)
    ? assistant.content
        .flatMap((part) =>
          typeof part === "object" &&
          part !== null &&
          "text" in part &&
          typeof part.text === "string"
            ? [part.text]
            : [],
        )
        .join("")
    : "";
  const visibleAssistantText = result.meta.finalAssistantVisibleText?.trim() ?? "";
  const transcriptUsage = assistant?.usage as
    | {
        input?: number;
        output?: number;
        totalTokens?: number;
        contextUsage?: { state?: string; promptTokens?: number; totalTokens?: number };
      }
    | undefined;
  const agentMetaUsage = result.meta.agentMeta?.usage;
  const diagnosticUsage = result.meta.agentMeta?.diagnosticUsage;
  const lastCallUsage = result.meta.agentMeta?.lastCallUsage;
  if (requestCount < 2 || toolResultRequests < 1) {
    throw new Error(`unexpected Claude CLI turn shape: requests=${requestCount}, toolResults=${toolResultRequests}`);
  }
  if (visibleAssistantText !== "DONE" || persistedAssistantText !== "DONE") {
    throw new Error(`assistant output was not preserved: visible=${visibleAssistantText}, persisted=${persistedAssistantText}`);
  }
  if (
    agentMetaUsage?.input !== 30 ||
    agentMetaUsage.output !== 15 ||
    diagnosticUsage?.input !== 52 ||
    diagnosticUsage.output !== 27 ||
    lastCallUsage?.input !== 30 ||
    lastCallUsage.output !== 15 ||
    transcriptUsage?.input !== 52 ||
    transcriptUsage.output !== 27 ||
    transcriptUsage.totalTokens !== 79 ||
    transcriptUsage.contextUsage?.promptTokens !== 30 ||
    transcriptUsage.contextUsage.totalTokens !== 45
  ) {
    throw new Error(
      `usage mismatch: ${JSON.stringify({ agentMetaUsage, diagnosticUsage, lastCallUsage, transcriptUsage })}`,
    );
  }
  console.log(
    `PROOF_RESULT=${JSON.stringify({
      headSha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(),
      cliRequests: requestCount,
      toolResultRequests,
      visibleAssistantText,
      persistedAssistantText,
      agentMetaUsage,
      lastCallUsage,
      diagnosticUsage,
      transcriptUsage,
    })}`,
  );
} finally {
  admission.close();
  await closeOpenClawAgentDatabasesAsync(root);
  closeOpenClawAgentDatabasesForTest(root);
  await new Promise<void>((resolve) => server.close(() => resolve()));
  await fs.rm(root, { recursive: true, force: true });
}

AI-assisted: built with Codex

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds Claude CLI accounting and context-sizing regressions plus a compile-time usage-shape check.

Example: A Claude CLI turn reports 52 input and 27 output tokens overall, with 30 input and 15 output tokens in its latest call.

  • Before: Current main already persists the whole-turn totals while preserving latest-call context.
  • After: Additional regressions protect that separation through parsing, transcript persistence, and preflight sizing.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, correct regression coverage with real-CLI production-path evidence and green exact-head CI; overlapping writer coverage limits the patch's test value.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): At the reviewed head, runPreparedCliAgent launched Claude CLI 2.1.263 against an isolated Anthropic-compatible loopback endpoint, completed a tool turn, and persisted cumulative 52/27 usage with latest-call context 30/45 to SQLite; the real CLI, parsing, settlement, and persistence were exercised while the external model boundary was controlled. Inspected companion screenshots show context display correction but are supporting historical evidence rather than proof of this coverage-only diff.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Test only · Worth it: Yes
User problem: Future accounting changes could again confuse whole-turn totals with the latest call's context size.
Reason: The useful additions exercise real parsing and persistence together and distinguish aggregate output from context-marker output, without introducing another runtime owner.

Merge readiness

✅ Ready for maintainer review

Keep this PR as a useful regression-coverage follow-up. The previous mock-export finding is resolved, exact-head CI is green, and no introduced correctness defect was found.

Priority: P3
Reviewed head: 485814f8900f8ba5d38c02bf6105a0a5746c1330

Before merge

None.

Findings

None.

Tests

  • Low-value test src/agents/cli-runner/cli-run-transcript.test.ts: The added terminal-counters/latest-call-marker case repeats the persistence contract already asserted through the real runner in cli-runner.turn-usage.test.ts and the new stream-parsing regression; consolidate or remove this duplicate case.
Agent review details

How this fits together

The CLI runner parses backend events, persists assistant usage in SQLite, and supplies latest-call context facts to compaction consumers.

flowchart LR
  A[Claude CLI events] --> B[CLI stream parser]
  B --> C[CLI runner settlement]
  C --> D[Shared usage projection]
  D --> E[SQLite transcript]
  E --> F[Preflight context sizing]
Loading

Technical review

Best possible solution:

Retain focused coverage of parser-to-transcript wiring and aggregate-output context sizing under the existing accounting owners.

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

The current diff is a coverage follow-up; the contributor provides an original-defect negative control and an exact-head real-CLI accounting trace, which were inspected without executing target code.

Is this the best way to solve the issue?

The parser-to-storage regression and inflated-output context-sizing case protect distinct boundaries using existing owners; the direct writer case overlaps coverage already exercised through the runner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • CLI transcript usage projection keeps the original intent (2f22858: Persist whole-turn counters while retaining latest-call context sizing, as documented in the merged companion PR.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduced diff: The introduced production edit adds only a satisfies assertion; the remaining changes add accounting regressions. (src/agents/cli-transcript-usage.ts:16, 485814f8900f)
  • Existing accounting owner: Current main already selects terminal counters while deriving contextUsage from the latest call; the merged companion fix: usage undercounts Claude CLI turns that make several model calls #148682 owns that behavioral repair. (src/agents/cli-transcript-usage.ts:29, 84e79644fa09)
  • Prior finding resolved: The runner mocks preserve original exports, and the four isolated memory-test mocks now explain their state-isolation requirements. (src/auto-reply/reply/agent-runner-memory.usage.test.ts:29, 485814f8900f)
  • Exact-head production-path evidence: The full PR body supplies the loopback server and real Claude CLI trace: three requests, one tool-result request, visible and persisted DONE, cumulative usage 52/27, and latest-call usage 30/15; source body identity supplied by the host is a55b663f98adaa74e9d4551a0755642ccd1e580f0ad6840f99fc7688a06ad904. (485814f8900f)
  • Exact-head CI: Both check-run pages were inspected; the CI gate, changed-test lanes, type checks, and baseline ratchets succeeded, with no failed check reported. (485814f8900f)
  • History and inspection limits: Feature history identifies mcaldas's accounting repair and obviyus's cache-pricing follow-up. Some historical blobs and the previous reviewed head are unavailable locally; older review-cycle context is bounded and title-only, so no unsupported late-finding or introduction claim is made. (src/agents/cli-transcript-usage.ts:19, 84e79644fa09)

Likely related people:

  • Mathias Caldas: Raw commit 2f22858 adds src/agents/cli-transcript-usage.ts:19 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2f228582f354; files: src/agents/cli-transcript-usage.ts)

PR surface

Source 0, Tests +434. Total +434 across 4 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 1 1 1 0
Tests 3 435 1 +434
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 436 2 +434

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P3: This follow-up protects already-correct accounting behavior without changing runtime behavior.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • 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 (16 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-28T07:46:37.845Z sha b112c6fb8de78014bde3b17e6401ba9c5b7823c8 :: blocked before merge. :: [P1] Share one CLI transcript usage projection
  • reviewed 2026-09-28T10:08:51.892Z sha 055ef903ebf0a79e53c8525961f702a96f3b7ae5 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T00:38:38.789Z sha 21e1816dee803e8e5921aadd64c05f667abb34ed :: needs changes before merge. :: [P1] Remove the unused duplicate transcript accounting owner
  • reviewed 2026-10-07T15:07:00.449Z sha c3f9c74861de4389206048436e319e6f5f39f732 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-09T02:02:36.241Z sha e48f855acbd83c134e4adc42f99a9b9fae6ec38f :: needs changes before merge. :: [P2] [P2] Replace the removed runner test setters
  • reviewed 2026-10-09T03:23:02.706Z sha beeacac6b5f0e088b6dfd145299657d4d2878244 :: blocked before merge. :: [P2] [P2] Carry latest-call context through chat consumers | [P2] [P2] Avoid pricing aggregate CLI usage as one tiered request
  • reviewed 2026-10-13T02:09:36.546Z sha adac326d48b0b36637f95d64e9cdc5dd96d11ad6 :: needs changes before merge. :: [P2] Carry latest-call context through chat consumers | [P2] Avoid pricing aggregate CLI usage as one tiered request | [P2] Derive context output from the latest-call marker | [P2] Import the transcript replacement fixture from test support
  • reviewed 2026-10-20T09:41:36.125Z sha b3f2e6af96a969ad081a062a70f82fc7a8df4950 :: needs changes before merge. :: [P2] Preserve real exports or explain isolation for the six new mocks

Reviewed October 20, 2026, 9:48 AM ET / 13:48 UTC (Revision 17).

@clawsweeper clawsweeper Bot added 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 15, 2026
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from 44997bd to a90ec7f Compare September 15, 2026 04:02
@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. 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 15, 2026
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from a90ec7f to d242004 Compare September 17, 2026 13:42
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 17, 2026
@fuller-stack-dev fuller-stack-dev self-assigned this Sep 18, 2026
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from d242004 to 8e4741f Compare September 18, 2026 03:54
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 18, 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. 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. labels Oct 7, 2026
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from c3f9c74 to e48f855 Compare October 9, 2026 01:54
@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed 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 Oct 9, 2026
@ekinnee

ekinnee commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

@RileyJJY, related contract discussion: mcaldas's follow-up on #148682 proposes keeping that PR to transcript accounting and reviewing the live agentMeta.usage change separately, pending a maintainer decision.

At this PR's current head beeacac6, buildCliRunResult still changes to usage: output.diagnosticUsage ?? output.usage, and the context-engine test changes live usage from 11/7 to 21/9. The description meanwhile says settled metadata retains its existing per-call view.

Could the description and implementation be aligned, and the live-metadata scope settled alongside the sibling discussion before these repairs converge? Whole-turn accounting and latest-call context sizing should remain explicit whichever scope is chosen.


October 12 follow-up — bounded help for this branch

I refreshed both PRs and read the CI logs tied to this head. A few concrete next steps may save you a broader repair loop:

  • Patch-owned CI work: the mock-export ratchet flags six new mock factories: hook-runner-global and tts-settings in cli-runner.usage.reliability.test.ts, plus embedded-agent, run-entry, agent-run-registry, and session-updates in agent-runner-memory.usage.test.ts. Preserve real exports where appropriate, or add a specific // mock-isolation: reason immediately above a mock that must isolate real state. This is separate from the removed-setter fix you already completed.
  • Inherited CI failures: lint reports two unbound methods in scripts/e2e/lib/upgrade-survivor/package-activation-fault.mjs; architecture reports the prepared-model-catalog fingerprints/worker cycle. All three implicated files have identical Git blobs in the run's main baseline 98eb5759 and tested merge 7a53b9b2. These are inherited source failures, not reasons to expand this accounting patch. I did not rerun the checks locally.
  • Consumer fixes already available for comparison: fix: usage undercounts Claude CLI turns that make several model calls #148682 now forwards the context marker through chat history and web/shared-native displays, guards ambiguous aggregate tier pricing, and invalidates cached cost rollups. Its October 9 review at 4f6d8a83 reports no actionable findings. Those changes directly address this branch's two remaining consumer findings; they are worth comparing with @mcaldas before independently rebuilding the same fixes.

@fuller-stack-dev, could you confirm or route the live-metadata scope decision above? Keeping the transcript repair separate is one concrete option; including the live switch needs the corresponding contract/docs and consumer coverage, including the missing-prompt-token fallback. Once that choice is made, the authors can agree which existing PR carries the shared repair and credit any code actually incorporated.

Both branches currently conflict with main. This was read-only source/log analysis, not a new runtime reproduction. RileyJJY's October 9 repair and existing accounting proof remain useful evidence; I am not proposing a competing PR or treating the stale label as abandonment.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 12, 2026
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from beeacac to adac326 Compare October 13, 2026 01:58
@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 Oct 13, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Oct 13, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 13, 2026
obviyus added a commit that referenced this pull request Oct 15, 2026
…#148682)

Related: #148603 (this PR fixes the whole-turn accounting; the issue's final per-call output count is listed under Not in scope below)

## What Problem This Solves

Fixes: session usage, `usage.cost`, and the Usage page count only the last model call (with its stream-start output count) for Claude CLI turns. Turns that make several model calls, such as tool-using turns, are therefore heavily undercounted.

## User Impact

User impact: Claude CLI turns now record the whole turn's tokens in the session transcript, so usage reports and anything built on them (cost estimates, budget alerts) match what Claude Code reports.

- Context-window sizing, preflight compaction, and memory-flush gating keep using the latest model call.
- Chat context displays (Control UI message footer, iOS/macOS chat) keep showing the latest call's context size.
- Turns recorded before this change keep their existing counts.
- No config, schema, or migration change (see compatibility below).

## Why This Change Was Made

Claude Code's terminal `result` event already carries whole-turn usage, and the stream parser keeps it as `diagnosticUsage` (#120100). Both CLI transcript writers still persisted the last call.

- **Both writers:** they now persist the turn total as the usage counters. `contextUsage` is derived from the last call through one shared helper (`resolveCliTranscriptUsage`), so every context reader still sizes the window from the latest call.
- **Reply-path writer:** it adds that context marker only when the backend reports a turn total separately. Other CLI backends keep their unmarked records, which context readers already refuse to treat as a fresh context size (#120497).
- **Memory flush and preflight:** their transcript snapshot now takes the last completion's output from the context marker instead of the turn counters.

- **Chat context displays:** chat history now forwards an available, coherent `contextUsage` marker with assistant usage. The Control UI message footer and the native context control and footer size context from it. Rows without an available marker keep sizing from the counters, as before.
- **Tiered pricing:** summed tokens cannot recover each request's tier. `usage.cost` now leaves a turn unpriced when its counters exceed the marker's prompt and their sum reaches past the lowest tier.
  - A sum inside the lowest tier keeps every call there, so it is still estimated. Flat pricing is unchanged.
  - The rule reads the usage shape, so it also applies to Codex harness rows whose summed prompt crosses a tier boundary.
  - `USAGE_COST_ROLLUP_VERSION` moves to 8 so cached usage summaries rebuild with the new rule. `main` is at 7 since #169660, which also carries version-6 summaries forward; both were priced under the old rule, so this PR accepts only version 8. The schema cutover still moves version-6 rows, and readers rebuild them.

Live `agentMeta.usage` / `lastCallUsage` and the context-engine hook message are unchanged.

## Evidence

### Real behavior proof (after the fix, live OpenClaw)

Setup:
- A production OpenClaw 2026.9.2 gateway with Claude Code 2.1.263 on a Claude subscription.
- This PR's three production edits applied as a local backport, with identical logic, because the host runs the published build.
- Output is redacted to usage counters; the session id is replaced.

Two non-delivering `openclaw agent` turns ran on one dedicated session:
- Turn 1 makes two model calls: a Read tool call, then the reply.
- Turn 2 reuses the existing session.

```text
$ openclaw agent --agent main --session-key agent:main:<proof> --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."

# live run metadata (unchanged by this PR)
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# persisted assistant transcript records, read back from the session's SQLite transcript
turn 1  usage {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
               contextUsage {state available, promptTokens 74920, totalTokens 74921}}
turn 2  usage {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
               contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# Claude Code's own transcript for the bound CLI session (deduplicated by message id)
turn 1  model calls 2  sum input 4 / output 89 / cacheRead 74593 / cacheWrite 74918  last-call prompt 74920
turn 2  model calls 1  sum input 2 / output 3  / cacheRead 74918 / cacheWrite 102    last-call prompt 75022

# usage.cost for the agent's day, read back before and after the two proof turns (rollup refresh)
before  totalTokens 404634  output 13   cacheWrite 45337   totalCost 0.3800  missingCostEntries 0
after   totalTokens 629263  output 105  cacheWrite 120357  totalCost 0.8764  missingCostEntries 0
delta   totalTokens +224629 (= 149604 + 75025)  output +92 (= 89 + 3)  cacheWrite +75020 (= 74918 + 102)
```

What this shows:
- The persisted counters equal Claude Code's per-turn totals exactly.
- The usage report's delta equals the two persisted records. The dollar figure comes from a locally configured `claude-cli` price entry; this PR does not change pricing.
- `contextUsage.promptTokens` equals the last call's prompt.
- Without this change, turn 1 would have been persisted as output 1 / cacheWrite 325.
- A scheduled heartbeat turn on the same gateway also persisted its final output count (9) and not the stream-start value (1): `usage {input 2, output 9, cacheRead 69062, cacheWrite 10885, totalTokens 79958, contextUsage {state available, promptTokens 79949, totalTokens 79950}}`.

### Real behavior proof for the chat display and pricing follow-ups

Setup:
- OpenClaw built from this branch at 4f6d8a8, run as an isolated local gateway (own state directory, loopback only, channels off).
- Both turns ran with `openclaw agent` through the real `claude-cli` backend. The `claude` binary on `PATH` was a stand-in that emits the usage of the live turns above as Claude Code stream records: one `assistant` record per model call and the terminal `result`. No model call was made.
  - The first call's record is derived: turn total minus the last call.
  - `qa/scenarios/channels/telegram-claude-cli-compaction-final-priority.yaml` uses the same stand-in technique.
- The runner, transcript writer, chat history, `usage.cost` and the Control UI are the built product with no proof-only changes. The only stand-in is the `claude` binary.
- **Before** is this branch with the source changes of fa8ed7c and db6439b reverted and rebuilt. That is the state reviewed at 9366812: whole-turn counters stored, displays and pricing not yet following the marker. **After** is the head.
- The turns ran once, on the before build. The after build read the same session from the same state directory. The transcript writer is identical in both builds.
- Proof configuration: a 200,000-token context window, and a `claude-cli/claude-sonnet-4-5` price entry with a tier boundary at 100,000 prompt tokens (`$3 / $15 / $0.30 / $3.75` per million tokens below it, `$6 / $22.50 / $0.60 / $7.50` above). Each call of turn 1 stays below the boundary (74,595 and 74,920 prompt tokens). Their sum (149,515) crosses it.

```text
$ openclaw agent --agent main --session-key agent:main:proof --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."
$ openclaw agent --agent main --session-key agent:main:proof --json --message "Reply with only the word ok."

# run metadata from the stand-in, equal to the live run above
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# openclaw gateway call chat.history: assistant usage as the Control UI and the apps receive it
before  turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025}
after   turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
                 contextUsage {state available, promptTokens 74920, totalTokens 74921}}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
                 contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# openclaw gateway call usage.cost --params '{"days":1}': totals
before  totalTokens 224629  totalCost 0.6315762  missingCostEntries 0
after   totalTokens 224629  totalCost 0.0229089  missingCostEntries 1
        missingCostByModel {"claude-cli/claude-sonnet-4-5": 1}
```

What this shows:
- **`usage.cost`, before:** turn 1 is priced from its summed prompt at the upper tier. That is `$0.6086673` of the total; the rest is turn 2. Both of its calls sit in the lower tier, where the same tokens cost about `$0.3047`.
- **`usage.cost`, after:** turn 1 is left unpriced and counted in `missingCostEntries`. Turn 2 is a single call and keeps its estimate, `$0.0229089`.
- Token totals are the same in both builds (224,629 = 149,604 + 75,025).
- The before build stored its usage rollup under version 6. On the head, the first `usage.cost` read reported it stale and refreshing. The next read, 3 s later, was fresh with the new totals, and the stored rollup carries version 7. No manual step was needed.

**Control UI** (web): the usage details of turn 1's reply in the chat view. They show when the message footer is hovered.

Before: `75% ctx`

![Control UI message footer before: 75% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-before.png)

After: `37% ctx`

![Control UI message footer after: 37% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-after.png)

**Native** (iOS): the message footer (top) and the context control's menu (bottom).

Before: `75% ctx` with a warning, and "149.6k of 200.0k tokens used"

![iOS chat before: 75% ctx, 149.6k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-before.png)

After: `37% ctx`, and "74.9k of 200.0k tokens used"

![iOS chat after: 37% ctx, 74.9k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-after.png)

- The iOS app target is a Debug build of `apps/ios` on an iPhone 17 simulator (iOS 26.4.1), from a reduced project without the watch app, in the app's screenshot fixture mode (`--openclaw-screenshot-mode`).
- A local, uncommitted patch to the fixture transport seeds the chat history with turn 1's usage row and a 200,000-token window. The chat text and the model label (`claude-sonnet-4-6`) are the fixture's own.
- Both runs receive the same history payload, marker included. Before reverts the Swift changes of fa8ed7c, so only the app code differs.
- The macOS app renders the same shared `OpenClawChatUI` views from `apps/shared/OpenClawKit`. It was not captured separately.
- The screenshots hold proof-session and fixture content only: no endpoints, addresses, keys or personal data.

### Tests and checks

Regression tests. Each one fails on `main` and passes with this change:
- `cli-runner.turn-usage.test.ts` › "persists the terminal Claude turn usage for a multi-call turn"
  - Runs a turn whose parsed output carries the last call and a separate turn total through `runPreparedCliAgent`, then reads the persisted transcript back.
  - Before: input 2 / output 1 / cacheRead 27,376.
  - After: 6 / 77 / 54,631, with `contextUsage` at the last call's 27,378 prompt tokens.
- `transcript-persistence.test.ts` › "persists the terminal CLI turn usage while keeping last-call context"
- `session-transcript-readers.test.ts` › "sizes CLI output from the context marker when counters cover the whole turn"
  - Before: 30,000 output tokens.
  - After: 2,000 output tokens.

- `chat-display-projection.test.ts` › "forwards an available context marker with assistant usage"
- `chat-message-timestamp.test.ts` (new file) › "sizes context from the marker when usage counters cover a whole turn"
  - Before: 75% ctx for a two-call turn in a 200k window.
  - After: 37% ctx.
- `ChatContextUsageTests.swift` › "whole-turn counters report the latest call's context marker" and "usage footer sizes context from the marker and keeps whole-turn counters"
  - Before: 149,000 tokens and "98% ctx".
  - After: 75,000 tokens and "49% ctx".
- `session-cost-usage-pricing.test.ts` (new file) › "leaves a multi-call turn unpriced when its sum crosses a tier" and "prices a multi-call turn whose sum stays in the lowest tier"

Guard test:
- `cli-run-transcript.test.ts` › "keeps CLI usage unmarked when the backend reports no separate turn total"

Suites and checks (branch merged with `main` at 035bf89):
- Merge history: the merge at efa6458 had three conflicts, all code `main` had moved: the transcript accounting reader now lives in `session-transcript-accounting-policy.ts`, and the chat footer's `extractGroupMeta` in the Solid `chat-message-timestamp-view.tsx`; this PR's two edits were re-applied there unchanged. The merge at 432d890 was clean. The merge at 035bf89 had one import conflict in `chat-message-timestamp-view.tsx`; both helpers are kept.
- #120008 (usage reports marked unavailable) landed in three files this PR also changes: the chat history projection, the usage pricing estimate and the Control UI footer. Both changes are kept side by side: an unavailable usage report is skipped before this PR's context marker and tier guard are read.
- On the merged head, `pnpm test <files> --maxWorkers=4` passed 2,239 tests across 171 files:
  - every test file in `src/agents/cli-runner/` and `src/agents/command/` (live and e2e files excluded);
  - the `cli-runner.*`, `cli-output*`, `usage*`, `agent-runner-memory*`, `session-transcript-readers*`, `chat-display-projection*`, `session-cost-usage*` and `usage-format*` suites;
  - the Control UI `chat-message*` suites, including the six chat browser tests;
  - the usage cache suites (`session-cost-usage-cache.*`), `doctor-usage-cost-cache.test.ts` and the schema cutover test `openclaw-agent-db.storage-migration.test.ts`.
- The version 8 move updates two cutover tests from #169660: a migrated version-6 report is still moved (the cache test checks it arrives byte for byte), but no longer decodes as current (`session-cost-usage-cache.sqlite.test.ts`, `openclaw-agent-db.storage-migration.test.ts`). Our earlier fixture change in the cutover test (4f6d8a8) is replaced by `main`'s stored version 6.
- CI on the first merge failed two of this PR's new tests and one existing e2e test:
  - `cli-runner.turn-usage.test.ts` and the guard test in `cli-run-transcript.test.ts` relied on runtime config being loaded on demand, which #169714 removed. Without config the persistence wrapper wrote no row, so both saw an empty transcript. Both now pass `config: {}`, as #169714 did for the neighbouring tests. Both fail on the new merge without that change and pass with it.
  - `cli-runner.fault-sequences.e2e.test.ts` › "dispatches bridge mode through one fresh CLI child and bypasses the native run budget" fails with "Runtime config is not prepared" on this head, and identically with all of this PR's source changes reverted (tests kept). It comes from `main`, not from this PR.
  - Left out of the local run: `session-cost-usage-cache.creation-race.test.ts`, new on `main`, fails on this Mac with "state … is undergoing offline maintenance", identically with this PR's source changes reverted.
- Test cost of the four added tests, from `pnpm test <file> --maxWorkers=1` on an M-series laptop:
  - `cli-runner.turn-usage.test.ts` (new file): 2.2 s for the test, 11 s for the file. It runs the real runner and transcript store, because that is the only layer that proves the turn total is wired from the runner into the writer.
  - `transcript-persistence.test.ts`: 63 ms for the added test.
  - `session-transcript-readers.test.ts`: 144 ms for the added test.
  - `cli-run-transcript.test.ts`: 201 ms for the added test.
- Gates re-run on the merged head: `oxfmt --check` and oxlint on the changed files, `tsgo:core`, `tsgo:ui`, `tsgo:core:test`, and the line-cap, assertion-safety and mock-export ratchets. `git diff --check` is clean.
- Gates last run before the merge of `main`: import cycles (0 runtime, 0 madge), dead-code exports, deprecated API usage, `lint:ui:i18n`, stylelint on the changed UI files, and the max-lines and test-timeout-race ratchets. The SQLite-worker ratchet last ran before the chat-display and pricing commits, which add no database code.
- The three regression tests moved out of `cli-runner.reliability.test.ts`, `attempt-execution.cli.test.ts` and `agent-runner-memory.test.ts`, which are over the line cap and may not grow.
- Chat display and pricing follow-up:
  - `swift test --package-path apps/shared/OpenClawKit --filter ChatContextUsageTests` passed 14 tests on the merged head; SwiftFormat and SwiftLint at the pinned versions report nothing on the changed files.
  - The added TypeScript tests take 0 to 2 ms each. Each new regression test fails with its source change reverted.
  - The iOS app target was built (Debug, simulator, reduced project without the watch app) for the screenshots above. Not run locally: the full OpenClawKit suite, the full iOS project and the macOS app build.

Live Claude Code semantics (stream-json, `--include-partial-messages`):
- A tool-using turn's `result` reported 77 output tokens, while its two `assistant` events carried 15 and 1.
- In one warm stdio process, each turn's `result.usage` covered only that turn (78 output tokens each time). Only `total_cost_usd` accumulates, so persisting `result` usage does not double count warm sessions.
  - Rechecked on Claude Code 2.1.293: two turns in one process reported cache writes of 28,094 and then 5,619, while `total_cost_usd` rose from 0.0057 to 0.0072.

## Upgrade and data compatibility

- **No schema, migration, or config change.** The persisted assistant `usage` keeps its existing shape. `contextUsage` is an existing optional field that the agent-command writer has persisted since #120497.
- **Existing records are untouched.** Older unmarked CLI records still hit the existing provenance barrier, so readers treat them exactly as before.
- **Old and new records mix safely in one session.** Accounting sums the counters, and context readers use the newest record's marker (proof turn 2 above ran in an existing session).
- **Upgrade.** Only turns recorded after the update carry turn totals, and nothing needs to run. Rolling back leaves new records readable, because their counters are ordinary usage fields.

## Related

- #148676 targets the same issue. Its current revision uses the same projection for both writers and the same reader change.
  - It also switches live `agentMeta.usage` to the turn total in `cli-run-settlement.ts`.
  - This PR leaves live `agentMeta.usage` on the last call.

Not in scope (possible follow-ups):
- `lastCallUsage` still takes its output count from the stream-start `assistant` event, because `readCliUsage` does not read `message_delta`. This only affects the small output side of the context marker.
- A run with several interim `result` events persists the last segment's total. That undercounts rather than double counts, and the behavior predates this change.
- Live `agentMeta.usage` for CLI runs (reply footer, session store counters, cron run records) still reflects the last call.
- Subscription dollar pricing (#102771).
- Turns whose reply goes out through the message tool, and room-event turns, write no CLI assistant row, so they still add nothing to `usage.cost`.
- Rows whose marker is `unavailable` (for example an aborted Codex turn) keep sizing context and choosing a tier from their counters, as on `main`.

AI-assisted (Claude Code).

## Maintainer simplification

Reviewed the complete diff and the contributing commits at `443a1722ce` before executing the branch. The changes stay within usage accounting, its existing consumers, and regression tests: no new network calls, credential/environment reads, package or lockfile changes, install hooks, or build-configuration changes.

The smallest complete fix is to persist the terminal whole-turn counters, preserve the latest call in `contextUsage`, and keep every context consumer on that marker. The pass preserves mcaldas's commits and implementation:

- Reused the shared `CliTranscriptUsage` contract instead of maintaining an identical local type in the command writer.
- Removed the new Control UI no-marker fallback test: the existing rendered-chat test, “uses the largest prompt for context and aggregates usage, cache, and nested cost,” already exercises that behavior more thoroughly. The distinct whole-turn marker regression remains.
- Kept chat-history forwarding and both web/native consumers: without them, the accounting correction inflates the displayed context size.
- Kept the tiered-pricing guard: a summed prompt cannot reconstruct each request's tier, and applying a higher tier to a sum would introduce incorrect dollar estimates. Flat pricing and sums below the first boundary remain estimated. The same shape-based protection applies to existing Codex rows; no separate backend policy was added.
- Kept rollup version 8 and the adjusted storage-cutover tests: cached versions 6/7 were priced under the old rule and must rebuild. The existing migration still preserves the old cache bytes; the reader correctly declines to treat them as current.
- Kept the small shared `cli-transcript-usage.ts` leaf: both transcript writers need the same projection; importing it from the command writer previously pulled its runtime dependency graph into the runner. There is no competing usage owner to remove.

No additional feature or split-out is needed for these retained pieces; all prevent regressions introduced by persisting totals. The existing “Not in scope” items above remain out of scope.

Line deltas against merge base `035bf8903442` (production includes the native and web consumers):

| | Before pass | After pass |
| --- | ---: | ---: |
| Production | +164 / −44 (net +120) | +165 / −51 (net +114) |
| Tests | +375 / −4 (net +371) | +371 / −4 (net +367) |
| Total | +539 / −48 (net +491) | +536 / −55 (net +481) |

The pass removes 6 net production lines and 4 test lines without removing any distinct regression boundary. GitHub reported the branch mergeable, so no extra merge or rebase was performed.

## Maintainer real-CLI verification

Verified the simplified code at `c8a5bb223bb0130863f2159640faa2adf674ecd6` using a full production build (pueue task 7067), real Claude Code **2.1.300**, and an isolated loopback Gateway launched in the GUI session so the CLI could use its existing login keychain. No stand-in binary was used. The setup and prompts match the main-branch reproduction: one Read-tool turn followed by a plain reply on the same fresh session. The test Gateway was stopped afterward.

These are separate live runs, so model token counts vary between main and PR. The invariant is equality between the CLI's own per-turn sum and the canonical persisted counters within each run.

| Revision / turn | Claude transcript output | Persisted output | Claude transcript cache write | Persisted cache write |
| --- | ---: | ---: | ---: | ---: |
| Main `3f1011275f`, Read (2 calls) | 104 | 1 | 61,090 | 216 |
| Main `3f1011275f`, plain reply (1 call) | 4 | 1 | 425 | 425 |
| PR simplified head, Read (2 calls) | 106 | **106** | 60,587 | **60,587** |
| PR simplified head, plain reply (1 call) | 4 | **4** | 427 | **427** |

PR-head details (Claude transcript assistant records deduplicated by `message.id`):

| Turn | Source | Input | Output | Cache read | Cache write | Total |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Read | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 4 | 106 | 60,369 | 60,587 | 121,066 |
| Read | Live lastCallUsage | 1 | 1 | 60,369 | 218 | — |
| Plain reply | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 3 | 4 | 60,587 | 427 | 61,021 |
| Plain reply | Live lastCallUsage | 3 | 1 | 60,587 | 427 | — |

- `contextUsage` persisted and returned by **chat.history** is `{state: available, promptTokens: 60588, totalTokens: 60589}` for the Read turn and `{state: available, promptTokens: 61017, totalTokens: 61018}` for the reply. Both prompts equal the native transcript's last-call prompt exactly.
- The Control UI receives the last-call marker, corresponding to **30%** and **31%** of the configured 200,000-token window, rather than sizing the first turn from its 120,960-token aggregate prompt. This was checked through the actual `chat.history` payload; no new browser/native screenshot is claimed.
- Combined `usage.cost` delta: input **7**, output **110**, cache read **120,956**, cache write **61,014**, total **182,087**. All equal the two canonical records and the deduplicated CLI sums.
- The exact reproduction config has no CLI dollar-price entry: dollar totals remain zero and `missingCostEntries` increases by two. This run proves token accounting, not subscription billing or a dollar estimate. The focused tier-pricing tests cover the guard separately.
- The last-call stream-start output count remains 1, as expected for the explicitly out-of-scope `message_delta` issue; it no longer replaces whole-turn output in stored usage.

Validation on the simplified code:
- **208 tests passed across 10 files**, including both transcript writers, real runner wiring, accounting reader, chat projection and rendering, tier pricing, SQLite usage-cache migration, and storage cutover.
- Passed `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`, `pnpm tsgo:ui`, and the matching `test/tsconfig` lanes: agents-root, agents-other, commands, gateway-root, infra, state-logging, ui-chat.
- Passed scoped oxlint and oxfmt, `git diff --check`, `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`.
- The full install/build passed. An initial test invocation before installation found no Vitest; the post-install invocation above passed. The combined validation command reached its overall deadline during the final assertion scan; that scan was rerun alone and passed.
- **Local Swift limitation:** after generating the required Mermaid resources, `swift test --filter ChatContextUsageTests` could not compile because this host's CommandLineTools toolchain lacks the `SwiftUIMacros.StateMacro` plugin. The OpenClawKit package-test CI lane remains responsible for native verification; no local Swift pass is claimed.

Only redacted counters are published here; session identifiers, credentials and raw transcripts are omitted. A fresh ClawSweeper review is requested for this new head; the prior ready review was for `4daf2fecd4`.

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

Related: openclaw#148603 (this PR fixes the whole-turn accounting; the issue's final per-call output count is listed under Not in scope below)

## What Problem This Solves

Fixes: session usage, `usage.cost`, and the Usage page count only the last model call (with its stream-start output count) for Claude CLI turns. Turns that make several model calls, such as tool-using turns, are therefore heavily undercounted.

## User Impact

User impact: Claude CLI turns now record the whole turn's tokens in the session transcript, so usage reports and anything built on them (cost estimates, budget alerts) match what Claude Code reports.

- Context-window sizing, preflight compaction, and memory-flush gating keep using the latest model call.
- Chat context displays (Control UI message footer, iOS/macOS chat) keep showing the latest call's context size.
- Turns recorded before this change keep their existing counts.
- No config, schema, or migration change (see compatibility below).

## Why This Change Was Made

Claude Code's terminal `result` event already carries whole-turn usage, and the stream parser keeps it as `diagnosticUsage` (openclaw#120100). Both CLI transcript writers still persisted the last call.

- **Both writers:** they now persist the turn total as the usage counters. `contextUsage` is derived from the last call through one shared helper (`resolveCliTranscriptUsage`), so every context reader still sizes the window from the latest call.
- **Reply-path writer:** it adds that context marker only when the backend reports a turn total separately. Other CLI backends keep their unmarked records, which context readers already refuse to treat as a fresh context size (openclaw#120497).
- **Memory flush and preflight:** their transcript snapshot now takes the last completion's output from the context marker instead of the turn counters.

- **Chat context displays:** chat history now forwards an available, coherent `contextUsage` marker with assistant usage. The Control UI message footer and the native context control and footer size context from it. Rows without an available marker keep sizing from the counters, as before.
- **Tiered pricing:** summed tokens cannot recover each request's tier. `usage.cost` now leaves a turn unpriced when its counters exceed the marker's prompt and their sum reaches past the lowest tier.
  - A sum inside the lowest tier keeps every call there, so it is still estimated. Flat pricing is unchanged.
  - The rule reads the usage shape, so it also applies to Codex harness rows whose summed prompt crosses a tier boundary.
  - `USAGE_COST_ROLLUP_VERSION` moves to 8 so cached usage summaries rebuild with the new rule. `main` is at 7 since openclaw#169660, which also carries version-6 summaries forward; both were priced under the old rule, so this PR accepts only version 8. The schema cutover still moves version-6 rows, and readers rebuild them.

Live `agentMeta.usage` / `lastCallUsage` and the context-engine hook message are unchanged.

## Evidence

### Real behavior proof (after the fix, live OpenClaw)

Setup:
- A production OpenClaw 2026.9.2 gateway with Claude Code 2.1.263 on a Claude subscription.
- This PR's three production edits applied as a local backport, with identical logic, because the host runs the published build.
- Output is redacted to usage counters; the session id is replaced.

Two non-delivering `openclaw agent` turns ran on one dedicated session:
- Turn 1 makes two model calls: a Read tool call, then the reply.
- Turn 2 reuses the existing session.

```text
$ openclaw agent --agent main --session-key agent:main:<proof> --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."

# live run metadata (unchanged by this PR)
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# persisted assistant transcript records, read back from the session's SQLite transcript
turn 1  usage {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
               contextUsage {state available, promptTokens 74920, totalTokens 74921}}
turn 2  usage {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
               contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# Claude Code's own transcript for the bound CLI session (deduplicated by message id)
turn 1  model calls 2  sum input 4 / output 89 / cacheRead 74593 / cacheWrite 74918  last-call prompt 74920
turn 2  model calls 1  sum input 2 / output 3  / cacheRead 74918 / cacheWrite 102    last-call prompt 75022

# usage.cost for the agent's day, read back before and after the two proof turns (rollup refresh)
before  totalTokens 404634  output 13   cacheWrite 45337   totalCost 0.3800  missingCostEntries 0
after   totalTokens 629263  output 105  cacheWrite 120357  totalCost 0.8764  missingCostEntries 0
delta   totalTokens +224629 (= 149604 + 75025)  output +92 (= 89 + 3)  cacheWrite +75020 (= 74918 + 102)
```

What this shows:
- The persisted counters equal Claude Code's per-turn totals exactly.
- The usage report's delta equals the two persisted records. The dollar figure comes from a locally configured `claude-cli` price entry; this PR does not change pricing.
- `contextUsage.promptTokens` equals the last call's prompt.
- Without this change, turn 1 would have been persisted as output 1 / cacheWrite 325.
- A scheduled heartbeat turn on the same gateway also persisted its final output count (9) and not the stream-start value (1): `usage {input 2, output 9, cacheRead 69062, cacheWrite 10885, totalTokens 79958, contextUsage {state available, promptTokens 79949, totalTokens 79950}}`.

### Real behavior proof for the chat display and pricing follow-ups

Setup:
- OpenClaw built from this branch at 4f6d8a8, run as an isolated local gateway (own state directory, loopback only, channels off).
- Both turns ran with `openclaw agent` through the real `claude-cli` backend. The `claude` binary on `PATH` was a stand-in that emits the usage of the live turns above as Claude Code stream records: one `assistant` record per model call and the terminal `result`. No model call was made.
  - The first call's record is derived: turn total minus the last call.
  - `qa/scenarios/channels/telegram-claude-cli-compaction-final-priority.yaml` uses the same stand-in technique.
- The runner, transcript writer, chat history, `usage.cost` and the Control UI are the built product with no proof-only changes. The only stand-in is the `claude` binary.
- **Before** is this branch with the source changes of fa8ed7c and db6439b reverted and rebuilt. That is the state reviewed at 9366812: whole-turn counters stored, displays and pricing not yet following the marker. **After** is the head.
- The turns ran once, on the before build. The after build read the same session from the same state directory. The transcript writer is identical in both builds.
- Proof configuration: a 200,000-token context window, and a `claude-cli/claude-sonnet-4-5` price entry with a tier boundary at 100,000 prompt tokens (`$3 / $15 / $0.30 / $3.75` per million tokens below it, `$6 / $22.50 / $0.60 / $7.50` above). Each call of turn 1 stays below the boundary (74,595 and 74,920 prompt tokens). Their sum (149,515) crosses it.

```text
$ openclaw agent --agent main --session-key agent:main:proof --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."
$ openclaw agent --agent main --session-key agent:main:proof --json --message "Reply with only the word ok."

# run metadata from the stand-in, equal to the live run above
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# openclaw gateway call chat.history: assistant usage as the Control UI and the apps receive it
before  turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025}
after   turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
                 contextUsage {state available, promptTokens 74920, totalTokens 74921}}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
                 contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# openclaw gateway call usage.cost --params '{"days":1}': totals
before  totalTokens 224629  totalCost 0.6315762  missingCostEntries 0
after   totalTokens 224629  totalCost 0.0229089  missingCostEntries 1
        missingCostByModel {"claude-cli/claude-sonnet-4-5": 1}
```

What this shows:
- **`usage.cost`, before:** turn 1 is priced from its summed prompt at the upper tier. That is `$0.6086673` of the total; the rest is turn 2. Both of its calls sit in the lower tier, where the same tokens cost about `$0.3047`.
- **`usage.cost`, after:** turn 1 is left unpriced and counted in `missingCostEntries`. Turn 2 is a single call and keeps its estimate, `$0.0229089`.
- Token totals are the same in both builds (224,629 = 149,604 + 75,025).
- The before build stored its usage rollup under version 6. On the head, the first `usage.cost` read reported it stale and refreshing. The next read, 3 s later, was fresh with the new totals, and the stored rollup carries version 7. No manual step was needed.

**Control UI** (web): the usage details of turn 1's reply in the chat view. They show when the message footer is hovered.

Before: `75% ctx`

![Control UI message footer before: 75% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-before.png)

After: `37% ctx`

![Control UI message footer after: 37% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-after.png)

**Native** (iOS): the message footer (top) and the context control's menu (bottom).

Before: `75% ctx` with a warning, and "149.6k of 200.0k tokens used"

![iOS chat before: 75% ctx, 149.6k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-before.png)

After: `37% ctx`, and "74.9k of 200.0k tokens used"

![iOS chat after: 37% ctx, 74.9k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-after.png)

- The iOS app target is a Debug build of `apps/ios` on an iPhone 17 simulator (iOS 26.4.1), from a reduced project without the watch app, in the app's screenshot fixture mode (`--openclaw-screenshot-mode`).
- A local, uncommitted patch to the fixture transport seeds the chat history with turn 1's usage row and a 200,000-token window. The chat text and the model label (`claude-sonnet-4-6`) are the fixture's own.
- Both runs receive the same history payload, marker included. Before reverts the Swift changes of fa8ed7c, so only the app code differs.
- The macOS app renders the same shared `OpenClawChatUI` views from `apps/shared/OpenClawKit`. It was not captured separately.
- The screenshots hold proof-session and fixture content only: no endpoints, addresses, keys or personal data.

### Tests and checks

Regression tests. Each one fails on `main` and passes with this change:
- `cli-runner.turn-usage.test.ts` › "persists the terminal Claude turn usage for a multi-call turn"
  - Runs a turn whose parsed output carries the last call and a separate turn total through `runPreparedCliAgent`, then reads the persisted transcript back.
  - Before: input 2 / output 1 / cacheRead 27,376.
  - After: 6 / 77 / 54,631, with `contextUsage` at the last call's 27,378 prompt tokens.
- `transcript-persistence.test.ts` › "persists the terminal CLI turn usage while keeping last-call context"
- `session-transcript-readers.test.ts` › "sizes CLI output from the context marker when counters cover the whole turn"
  - Before: 30,000 output tokens.
  - After: 2,000 output tokens.

- `chat-display-projection.test.ts` › "forwards an available context marker with assistant usage"
- `chat-message-timestamp.test.ts` (new file) › "sizes context from the marker when usage counters cover a whole turn"
  - Before: 75% ctx for a two-call turn in a 200k window.
  - After: 37% ctx.
- `ChatContextUsageTests.swift` › "whole-turn counters report the latest call's context marker" and "usage footer sizes context from the marker and keeps whole-turn counters"
  - Before: 149,000 tokens and "98% ctx".
  - After: 75,000 tokens and "49% ctx".
- `session-cost-usage-pricing.test.ts` (new file) › "leaves a multi-call turn unpriced when its sum crosses a tier" and "prices a multi-call turn whose sum stays in the lowest tier"

Guard test:
- `cli-run-transcript.test.ts` › "keeps CLI usage unmarked when the backend reports no separate turn total"

Suites and checks (branch merged with `main` at 05af73b):
- Merge history: the merge at a944978 had three conflicts, all code `main` had moved: the transcript accounting reader now lives in `session-transcript-accounting-policy.ts`, and the chat footer's `extractGroupMeta` in the Solid `chat-message-timestamp-view.tsx`; this PR's two edits were re-applied there unchanged. The merge at 6923fd4 was clean. The merge at 05af73b had one import conflict in `chat-message-timestamp-view.tsx`; both helpers are kept.
- openclaw#120008 (usage reports marked unavailable) landed in three files this PR also changes: the chat history projection, the usage pricing estimate and the Control UI footer. Both changes are kept side by side: an unavailable usage report is skipped before this PR's context marker and tier guard are read.
- On the merged head, `pnpm test <files> --maxWorkers=4` passed 2,239 tests across 171 files:
  - every test file in `src/agents/cli-runner/` and `src/agents/command/` (live and e2e files excluded);
  - the `cli-runner.*`, `cli-output*`, `usage*`, `agent-runner-memory*`, `session-transcript-readers*`, `chat-display-projection*`, `session-cost-usage*` and `usage-format*` suites;
  - the Control UI `chat-message*` suites, including the six chat browser tests;
  - the usage cache suites (`session-cost-usage-cache.*`), `doctor-usage-cost-cache.test.ts` and the schema cutover test `openclaw-agent-db.storage-migration.test.ts`.
- The version 8 move updates two cutover tests from openclaw#169660: a migrated version-6 report is still moved (the cache test checks it arrives byte for byte), but no longer decodes as current (`session-cost-usage-cache.sqlite.test.ts`, `openclaw-agent-db.storage-migration.test.ts`). Our earlier fixture change in the cutover test (4f6d8a8) is replaced by `main`'s stored version 6.
- CI on the first merge failed two of this PR's new tests and one existing e2e test:
  - `cli-runner.turn-usage.test.ts` and the guard test in `cli-run-transcript.test.ts` relied on runtime config being loaded on demand, which openclaw#169714 removed. Without config the persistence wrapper wrote no row, so both saw an empty transcript. Both now pass `config: {}`, as openclaw#169714 did for the neighbouring tests. Both fail on the new merge without that change and pass with it.
  - `cli-runner.fault-sequences.e2e.test.ts` › "dispatches bridge mode through one fresh CLI child and bypasses the native run budget" fails with "Runtime config is not prepared" on this head, and identically with all of this PR's source changes reverted (tests kept). It comes from `main`, not from this PR.
  - Left out of the local run: `session-cost-usage-cache.creation-race.test.ts`, new on `main`, fails on this Mac with "state … is undergoing offline maintenance", identically with this PR's source changes reverted.
- Test cost of the four added tests, from `pnpm test <file> --maxWorkers=1` on an M-series laptop:
  - `cli-runner.turn-usage.test.ts` (new file): 2.2 s for the test, 11 s for the file. It runs the real runner and transcript store, because that is the only layer that proves the turn total is wired from the runner into the writer.
  - `transcript-persistence.test.ts`: 63 ms for the added test.
  - `session-transcript-readers.test.ts`: 144 ms for the added test.
  - `cli-run-transcript.test.ts`: 201 ms for the added test.
- Gates re-run on the merged head: `oxfmt --check` and oxlint on the changed files, `tsgo:core`, `tsgo:ui`, `tsgo:core:test`, and the line-cap, assertion-safety and mock-export ratchets. `git diff --check` is clean.
- Gates last run before the merge of `main`: import cycles (0 runtime, 0 madge), dead-code exports, deprecated API usage, `lint:ui:i18n`, stylelint on the changed UI files, and the max-lines and test-timeout-race ratchets. The SQLite-worker ratchet last ran before the chat-display and pricing commits, which add no database code.
- The three regression tests moved out of `cli-runner.reliability.test.ts`, `attempt-execution.cli.test.ts` and `agent-runner-memory.test.ts`, which are over the line cap and may not grow.
- Chat display and pricing follow-up:
  - `swift test --package-path apps/shared/OpenClawKit --filter ChatContextUsageTests` passed 14 tests on the merged head; SwiftFormat and SwiftLint at the pinned versions report nothing on the changed files.
  - The added TypeScript tests take 0 to 2 ms each. Each new regression test fails with its source change reverted.
  - The iOS app target was built (Debug, simulator, reduced project without the watch app) for the screenshots above. Not run locally: the full OpenClawKit suite, the full iOS project and the macOS app build.

Live Claude Code semantics (stream-json, `--include-partial-messages`):
- A tool-using turn's `result` reported 77 output tokens, while its two `assistant` events carried 15 and 1.
- In one warm stdio process, each turn's `result.usage` covered only that turn (78 output tokens each time). Only `total_cost_usd` accumulates, so persisting `result` usage does not double count warm sessions.
  - Rechecked on Claude Code 2.1.293: two turns in one process reported cache writes of 28,094 and then 5,619, while `total_cost_usd` rose from 0.0057 to 0.0072.

## Upgrade and data compatibility

- **No schema, migration, or config change.** The persisted assistant `usage` keeps its existing shape. `contextUsage` is an existing optional field that the agent-command writer has persisted since openclaw#120497.
- **Existing records are untouched.** Older unmarked CLI records still hit the existing provenance barrier, so readers treat them exactly as before.
- **Old and new records mix safely in one session.** Accounting sums the counters, and context readers use the newest record's marker (proof turn 2 above ran in an existing session).
- **Upgrade.** Only turns recorded after the update carry turn totals, and nothing needs to run. Rolling back leaves new records readable, because their counters are ordinary usage fields.

## Related

- openclaw#148676 targets the same issue. Its current revision uses the same projection for both writers and the same reader change.
  - It also switches live `agentMeta.usage` to the turn total in `cli-run-settlement.ts`.
  - This PR leaves live `agentMeta.usage` on the last call.

Not in scope (possible follow-ups):
- `lastCallUsage` still takes its output count from the stream-start `assistant` event, because `readCliUsage` does not read `message_delta`. This only affects the small output side of the context marker.
- A run with several interim `result` events persists the last segment's total. That undercounts rather than double counts, and the behavior predates this change.
- Live `agentMeta.usage` for CLI runs (reply footer, session store counters, cron run records) still reflects the last call.
- Subscription dollar pricing (openclaw#102771).
- Turns whose reply goes out through the message tool, and room-event turns, write no CLI assistant row, so they still add nothing to `usage.cost`.
- Rows whose marker is `unavailable` (for example an aborted Codex turn) keep sizing context and choosing a tier from their counters, as on `main`.

AI-assisted (Claude Code).

## Maintainer simplification

Reviewed the complete diff and the contributing commits at `443a1722ce` before executing the branch. The changes stay within usage accounting, its existing consumers, and regression tests: no new network calls, credential/environment reads, package or lockfile changes, install hooks, or build-configuration changes.

The smallest complete fix is to persist the terminal whole-turn counters, preserve the latest call in `contextUsage`, and keep every context consumer on that marker. The pass preserves mcaldas's commits and implementation:

- Reused the shared `CliTranscriptUsage` contract instead of maintaining an identical local type in the command writer.
- Removed the new Control UI no-marker fallback test: the existing rendered-chat test, “uses the largest prompt for context and aggregates usage, cache, and nested cost,” already exercises that behavior more thoroughly. The distinct whole-turn marker regression remains.
- Kept chat-history forwarding and both web/native consumers: without them, the accounting correction inflates the displayed context size.
- Kept the tiered-pricing guard: a summed prompt cannot reconstruct each request's tier, and applying a higher tier to a sum would introduce incorrect dollar estimates. Flat pricing and sums below the first boundary remain estimated. The same shape-based protection applies to existing Codex rows; no separate backend policy was added.
- Kept rollup version 8 and the adjusted storage-cutover tests: cached versions 6/7 were priced under the old rule and must rebuild. The existing migration still preserves the old cache bytes; the reader correctly declines to treat them as current.
- Kept the small shared `cli-transcript-usage.ts` leaf: both transcript writers need the same projection; importing it from the command writer previously pulled its runtime dependency graph into the runner. There is no competing usage owner to remove.

No additional feature or split-out is needed for these retained pieces; all prevent regressions introduced by persisting totals. The existing “Not in scope” items above remain out of scope.

Line deltas against merge base `05af73b39e6f` (production includes the native and web consumers):

| | Before pass | After pass |
| --- | ---: | ---: |
| Production | +164 / −44 (net +120) | +165 / −51 (net +114) |
| Tests | +375 / −4 (net +371) | +371 / −4 (net +367) |
| Total | +539 / −48 (net +491) | +536 / −55 (net +481) |

The pass removes 6 net production lines and 4 test lines without removing any distinct regression boundary. GitHub reported the branch mergeable, so no extra merge or rebase was performed.

## Maintainer real-CLI verification

Verified the simplified code at `c8a5bb223bb0130863f2159640faa2adf674ecd6` using a full production build (pueue task 7067), real Claude Code **2.1.300**, and an isolated loopback Gateway launched in the GUI session so the CLI could use its existing login keychain. No stand-in binary was used. The setup and prompts match the main-branch reproduction: one Read-tool turn followed by a plain reply on the same fresh session. The test Gateway was stopped afterward.

These are separate live runs, so model token counts vary between main and PR. The invariant is equality between the CLI's own per-turn sum and the canonical persisted counters within each run.

| Revision / turn | Claude transcript output | Persisted output | Claude transcript cache write | Persisted cache write |
| --- | ---: | ---: | ---: | ---: |
| Main `05d13dc7da`, Read (2 calls) | 104 | 1 | 61,090 | 216 |
| Main `05d13dc7da`, plain reply (1 call) | 4 | 1 | 425 | 425 |
| PR simplified head, Read (2 calls) | 106 | **106** | 60,587 | **60,587** |
| PR simplified head, plain reply (1 call) | 4 | **4** | 427 | **427** |

PR-head details (Claude transcript assistant records deduplicated by `message.id`):

| Turn | Source | Input | Output | Cache read | Cache write | Total |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Read | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 4 | 106 | 60,369 | 60,587 | 121,066 |
| Read | Live lastCallUsage | 1 | 1 | 60,369 | 218 | — |
| Plain reply | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 3 | 4 | 60,587 | 427 | 61,021 |
| Plain reply | Live lastCallUsage | 3 | 1 | 60,587 | 427 | — |

- `contextUsage` persisted and returned by **chat.history** is `{state: available, promptTokens: 60588, totalTokens: 60589}` for the Read turn and `{state: available, promptTokens: 61017, totalTokens: 61018}` for the reply. Both prompts equal the native transcript's last-call prompt exactly.
- The Control UI receives the last-call marker, corresponding to **30%** and **31%** of the configured 200,000-token window, rather than sizing the first turn from its 120,960-token aggregate prompt. This was checked through the actual `chat.history` payload; no new browser/native screenshot is claimed.
- Combined `usage.cost` delta: input **7**, output **110**, cache read **120,956**, cache write **61,014**, total **182,087**. All equal the two canonical records and the deduplicated CLI sums.
- The exact reproduction config has no CLI dollar-price entry: dollar totals remain zero and `missingCostEntries` increases by two. This run proves token accounting, not subscription billing or a dollar estimate. The focused tier-pricing tests cover the guard separately.
- The last-call stream-start output count remains 1, as expected for the explicitly out-of-scope `message_delta` issue; it no longer replaces whole-turn output in stored usage.

Validation on the simplified code:
- **208 tests passed across 10 files**, including both transcript writers, real runner wiring, accounting reader, chat projection and rendering, tier pricing, SQLite usage-cache migration, and storage cutover.
- Passed `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`, `pnpm tsgo:ui`, and the matching `test/tsconfig` lanes: agents-root, agents-other, commands, gateway-root, infra, state-logging, ui-chat.
- Passed scoped oxlint and oxfmt, `git diff --check`, `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`.
- The full install/build passed. An initial test invocation before installation found no Vitest; the post-install invocation above passed. The combined validation command reached its overall deadline during the final assertion scan; that scan was rerun alone and passed.
- **Local Swift limitation:** after generating the required Mermaid resources, `swift test --filter ChatContextUsageTests` could not compile because this host's CommandLineTools toolchain lacks the `SwiftUIMacros.StateMacro` plugin. The OpenClawKit package-test CI lane remains responsible for native verification; no local Swift pass is claimed.

Only redacted counters are published here; session identifiers, credentials and raw transcripts are omitted. A fresh ClawSweeper review is requested for this new head; the prior ready review was for `4daf2fecd4`.

Co-authored-by: Ayaan Zaidi <[email protected]>
@RileyJJY
RileyJJY force-pushed the sunlit/fix/issue-148603 branch from adac326 to b3f2e6a Compare October 20, 2026 09:22
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. and removed P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Oct 20, 2026
@RileyJJY

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

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

agents Agent runtime and tooling P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M stale Marked as stale due to inactivity 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