From 18c5086edb5f6c37eaf78c4f729bdeb7373831a5 Mon Sep 17 00:00:00 2001 From: maxsol Date: Sat, 21 Nov 2026 14:50:12 +0100 Subject: [PATCH] Name the reason when the mod says the cache broke The toast said "cache expired after N min idle" for every cache loss after a 5 min gap. After a /clear-tools or /compact it blamed the clock, and in sessions with a 1-hour cache it said "expired" for gaps the cache outlives. A loss with no pause gave no toast at all, though a change at the start of the request is the case worth a look. The mod now checks the reasons in the engine's order: compaction, model switch, idle past the lifetime, else a prefix change. It cannot ask the engine: the engine runs only while the viewer is open. Claude Code's TurnUsage has no 5 min / 1 h split, so the mod learns the 1-hour lifetime when the cache holds over a pause longer than 5 min; until then a 5-60 min gap names both causes. --- README.md | 5 +- packages/mod/src/live.ts | 11 ++- packages/mod/src/nudges.ts | 45 ++++++++++--- packages/mod/src/register.ts | 11 ++- packages/mod/test/nudges.test.ts | 111 ++++++++++++++++++++++++++----- packages/mod/types/index.d.ts | 4 ++ 6 files changed, 153 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 54497f5..d3f7437 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ agents through SQL and a CLI. Nothing leaves the machine. ## What you get - **A status line in Claude Code:** `qx $3.42 · ctx 182k · cache 96%`, from the harness's own numbers. -- **Nudges** (toasts, never added to the model's context): the prompt cache expired after idle time and the next - call re-wrote it; the context passed 200k. +- **Nudges** (toasts, never added to the model's context): a call re-wrote the prompt cache, with the reason + (a compaction, a model switch, idle past the cache's lifetime, or a change at the start of the request, which + is worth a look); the context passed 200k. - **`/clear-tools [outputs] [keep N]`:** compacts by replacing old tool calls (their inputs) and old tool outputs with short stubs instead of a summary, in one pass, so the prompt cache is written once. `outputs` clears only the outputs; `keep N` leaves the last N whole. Also as `/compact tools [outputs] [keep N]`. The next call diff --git a/packages/mod/src/live.ts b/packages/mod/src/live.ts index b2dc0df..eec1757 100644 --- a/packages/mod/src/live.ts +++ b/packages/mod/src/live.ts @@ -4,7 +4,16 @@ import { atom, read, update } from "claude-code"; import type { Live } from "../types/index.js"; import { tokens, usd } from "./format.ts"; -export const EMPTY: Live = { ctx: 0, read: 0, input: 0, lastEndAt: 0, lastCtx: 0, bigCtxNudged: false }; +export const EMPTY: Live = { + ctx: 0, + read: 0, + input: 0, + lastEndAt: 0, + lastCtx: 0, + bigCtxNudged: false, + compacted: false, + hourCache: false, +}; export const live = atom({ plugin: "quantext", key: "live" } as const, EMPTY); // Function declarations: the mod's loader follows `$` across files only into those. diff --git a/packages/mod/src/nudges.ts b/packages/mod/src/nudges.ts index f59a518..a8521f5 100644 --- a/packages/mod/src/nudges.ts +++ b/packages/mod/src/nudges.ts @@ -2,10 +2,11 @@ import type { TurnUsage } from "claude-code"; import type { Live } from "../types/index.js"; import { tokens, usd } from "./format.ts"; -import { cacheWriteUsd } from "./prices.ts"; +import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteUsd } from "./prices.ts"; -/** The prompt cache's default time to live: a longer idle gap may have let it expire. */ +/** The prompt cache's two lifetimes: 5 minutes by default, 1 hour when the harness asks for it. */ export const CACHE_TTL_MS = 5 * 60_000; +export const CACHE_TTL_1H_MS = 60 * 60_000; /** A re-write smaller than this is not worth a nudge. */ export const CACHE_REWRITE_NUDGE_TOKENS = 20_000; /** Below this share of the last call's input read from the cache, the cache was lost rather than extended. */ @@ -13,16 +14,40 @@ export const CACHE_LOST_READ_SHARE = 0.5; /** Context size at which every call gets expensive; nudged once until a compaction or /clear. */ export const CONTEXT_NUDGE_TOKENS = 200_000; -/** The expiry nudge for a main-loop call that started `startedAt`, or undefined when the cache held. */ -export function cacheExpiryNudge(l: Live, u: TurnUsage, startedAt: number): string | undefined { +const CHANGED = "the start of the request changed (tools, MCP servers, CLAUDE.md?)"; +const SEE = " /quantext view shows the first change."; + +/** Whether a main-loop call read most of the last call's input from the cache. */ +export const cacheHeld = (l: Live, u: TurnUsage): boolean => + u.cache_read_input_tokens >= CACHE_LOST_READ_SHARE * l.lastCtx; + +/** + * Why a main-loop call that started `startedAt` lost the cache, or undefined when it held. The reason, first that + * fits (as the engine's cache breaks): a compaction, a model switch, a pause past the cache's lifetime, else a + * change early in the request. The lifetime is known to be 1 hour once the cache held over a longer pause. + */ +export function cacheBreakNudge(l: Live, u: TurnUsage, startedAt: number): string | undefined { if (l.lastEndAt === 0) return undefined; - const idle = startedAt - l.lastEndAt; const rewrote = u.cache_creation_input_tokens; - if (idle <= CACHE_TTL_MS || rewrote <= CACHE_REWRITE_NUDGE_TOKENS) return undefined; - if (u.cache_read_input_tokens >= CACHE_LOST_READ_SHARE * l.lastCtx) return undefined; - const cost = cacheWriteUsd(u.model, rewrote); - const price = cost === undefined ? "" : ` (~${usd(cost)})`; - return `quantext: cache expired after ${Math.round(idle / 60_000)} min idle; this call re-wrote ${tokens(rewrote)} tokens${price}.`; + if (rewrote <= CACHE_REWRITE_NUDGE_TOKENS || cacheHeld(l, u)) return undefined; + const cost = cacheWriteUsd(u.model, rewrote, l.hourCache ? CACHE_WRITE_1H : CACHE_WRITE_5M); + const w = `${tokens(rewrote)} tokens${cost === undefined ? "" : ` (~${usd(cost)})`}`; + const idle = startedAt - l.lastEndAt; + const min = Math.round(idle / 60_000); + if (l.compacted) return `quantext: cache re-written after a compaction, as expected; this call wrote ${w}.`; + if (l.model !== undefined && l.model !== u.model) { + const from = `a switch from ${l.model} to ${u.model} (each model has its own cache)`; + return `quantext: cache re-written after ${from}; this call wrote ${w}.`; + } + if (idle > CACHE_TTL_1H_MS) return `quantext: cache expired after ${min} min idle; this call re-wrote ${w}.`; + if (idle <= CACHE_TTL_MS) { + return `quantext: cache lost after ${min} min, with no compaction or model switch: ${CHANGED}; this call re-wrote ${w}.${SEE}`; + } + if (l.hourCache) { + return `quantext: cache lost after ${min} min idle, within its 1-hour lifetime: ${CHANGED}; this call re-wrote ${w}.${SEE}`; + } + const both = "it expired if it lives 5 min, else the start of the request changed"; + return `quantext: cache lost after ${min} min idle: ${both}; this call re-wrote ${w}.`; } /** The large-context nudge when `ctx` has reached the threshold and it was not shown since it was re-armed. */ diff --git a/packages/mod/src/register.ts b/packages/mod/src/register.ts index 229319b..b780c08 100644 --- a/packages/mod/src/register.ts +++ b/packages/mod/src/register.ts @@ -3,7 +3,7 @@ import type { EngineInterface, Register } from "claude-code"; import type { ClearArgs } from "./clear-tools.ts"; import { clearRequest, clearTools, clearWhat, compactArgs, parseClearArgs, USAGE } from "./clear-tools.ts"; import { EMPTY, inputOf, readLive, statusLabel, updateLive } from "./live.ts"; -import { cacheExpiryNudge, contextNudge } from "./nudges.ts"; +import { CACHE_TTL_MS, cacheBreakNudge, cacheHeld, contextNudge } from "./nudges.ts"; import { openViewer } from "./viewer.ts"; /** @@ -91,10 +91,15 @@ export const register: Register = (on) => { const r = yield* next(e); const u = r.usage; if (u === null || e.agentId !== undefined) return r; // subagents have their own caches: count the main loop - const nudge = cacheExpiryNudge(await readLive($), u, startedAt); + const before = await readLive($); + const nudge = cacheBreakNudge(before, u, startedAt); + // A cache read after more than 5 minutes idle shows that this session's cache lives an hour. + const heldOverPause = before.lastEndAt > 0 && startedAt - before.lastEndAt > CACHE_TTL_MS && cacheHeld(before, u); const endedAt = await $.clock.now(); await updateLive($, (l) => ({ ...l, + compacted: false, + hourCache: l.hourCache || heldOverPause, read: l.read + u.cache_read_input_tokens, input: l.input + u.input_tokens + u.cache_creation_input_tokens, lastEndAt: endedAt, @@ -129,7 +134,7 @@ export const register: Register = (on) => { r = { messages: cleared.messages }; } if (e.agentId === undefined && e.trigger !== "precompute" && r.messages !== undefined) { - await updateLive($, (l) => ({ ...l, bigCtxNudged: false })); + await updateLive($, (l) => ({ ...l, bigCtxNudged: false, compacted: true })); remeasureSoon($); } if (note !== undefined) $.ui.toast(note); // after the update, so a failed clear shows no "Cleared" diff --git a/packages/mod/test/nudges.test.ts b/packages/mod/test/nudges.test.ts index 64cb773..5cc80ff 100644 --- a/packages/mod/test/nudges.test.ts +++ b/packages/mod/test/nudges.test.ts @@ -4,53 +4,128 @@ import { measurer, stepper, toasts, usage } from "./kit.ts"; const MINUTE = 60_000; -test("a cache expiry after an idle gap raises one nudge with its cost", async ($, on) => { +const SUMMARY = [{ role: "user" as const, text: "summary", toolUses: [] }]; +/** The kit hands the call's argument to the hooks as the event: give it the event's own fields. */ +const compact = ($: Engine, trigger = "manual") => $.session.compact({ trigger, messages: SUMMARY } as never); + +test("a cache lost after more than an hour idle is an expiry, with its cost", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + await step($, usage(300_000, 1_000)); + await clock.advance(70 * MINUTE); + await step($, usage(0, 301_000)); + expect(seen).toEqual(["quantext: cache expired after 70 min idle; this call re-wrote 301k tokens (~$1.50)."]); +}); + +test("a cache lost after 5 to 60 minutes idle names both causes while the cache's lifetime is not known", async ($, on) => { const seen = toasts(on); const { step, clock } = stepper(on); await step($, usage(300_000, 1_000)); await clock.advance(12 * MINUTE); await step($, usage(0, 301_000)); - expect(seen).toEqual(["quantext: cache expired after 12 min idle; this call re-wrote 301k tokens (~$1.50)."]); + expect(seen).toEqual([ + "quantext: cache lost after 12 min idle: it expired if it lives 5 min, else the start of the request changed; " + + "this call re-wrote 301k tokens (~$1.50).", + ]); +}); + +test("once the cache held over a pause, a loss within the hour is a prefix change, priced as a 1-hour write", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + await step($, usage(300_000, 1_000)); + await clock.advance(20 * MINUTE); + await step($, usage(301_000, 1_000)); // read after 20 min: this session's cache lives an hour + await clock.advance(40 * MINUTE); + await step($, usage(0, 302_000)); + expect(seen).toEqual([ + "quantext: cache lost after 40 min idle, within its 1-hour lifetime: the start of the request changed " + + "(tools, MCP servers, CLAUDE.md?); this call re-wrote 302k tokens (~$2.42). /quantext view shows the first change.", + ]); +}); + +test("a cache lost with no pause is a prefix change", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + await step($, usage(300_000, 1_000)); + await clock.advance(1 * MINUTE); + await step($, usage(0, 301_000)); + expect(seen).toEqual([ + "quantext: cache lost after 1 min, with no compaction or model switch: the start of the request changed " + + "(tools, MCP servers, CLAUDE.md?); this call re-wrote 301k tokens (~$1.50). /quantext view shows the first change.", + ]); +}); + +test("a re-write after a compaction is named as such, even after a long pause", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + on("session.compact", () => ({ messages: SUMMARY })); + await step($, usage(300_000, 1_000)); + await clock.advance(40 * MINUTE); + await compact($); + await step($, usage(0, 100_000)); + await clock.advance(1 * MINUTE); + await step($, usage(0, 101_000)); // the compaction counts for one call only + expect(seen).toEqual([ + "quantext: cache re-written after a compaction, as expected; this call wrote 100k tokens (~$0.50).", + "quantext: cache lost after 1 min, with no compaction or model switch: the start of the request changed " + + "(tools, MCP servers, CLAUDE.md?); this call re-wrote 101k tokens (~$0.51). /quantext view shows the first change.", + ]); +}); + +test("a precompute compaction does not count as a compaction", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + on("session.compact", () => ({ messages: SUMMARY })); + await step($, usage(300_000, 1_000)); + await compact($, "precompute"); + await clock.advance(1 * MINUTE); + await step($, usage(0, 301_000)); + expect(seen[0]).toContain("the start of the request changed"); }); -test("no expiry nudge within 5 minutes, for a small re-write, or when the cache was still read", async ($, on) => { +test("a re-write after a model switch is named as such", async ($, on) => { const seen = toasts(on); const { step, clock } = stepper(on); await step($, usage(300_000, 1_000)); - await clock.advance(4 * MINUTE); - await step($, usage(0, 301_000)); // within the time to live: not an expiry - await clock.advance(6 * MINUTE); + await clock.advance(1 * MINUTE); + await step($, { ...usage(0, 301_000), model: "claude-sonnet-5-5" }); + expect(seen).toEqual([ + "quantext: cache re-written after a switch from claude-opus-5-5 to claude-sonnet-5-5 (each model has its own " + + "cache); this call wrote 301k tokens (~$0.75).", + ]); +}); + +test("no cache nudge for a small re-write, or when the cache was still read", async ($, on) => { + const seen = toasts(on); + const { step, clock } = stepper(on); + await step($, usage(10_000, 1_000)); + await clock.advance(70 * MINUTE); await step($, usage(0, 15_000)); // 15k re-written: below the threshold - await step($, usage(0, 300_000)); - await clock.advance(6 * MINUTE); - await step($, usage(290_000, 40_000)); // the cache was read: new content, not an expiry + await clock.advance(1 * MINUTE); + await step($, usage(10_000, 40_000)); // the cache was read: new content, not a loss expect(seen).toEqual([]); }); -test("a subagent's calls raise no expiry nudge and do not move the main loop's idle clock", async ($, on) => { +test("a subagent's calls raise no cache nudge and do not move the main loop's idle clock", async ($, on) => { const seen = toasts(on); const { step, clock } = stepper(on); await step($, usage(300_000, 1_000)); - await clock.advance(6 * MINUTE); + await clock.advance(66 * MINUTE); await step($, usage(0, 300_000), "agent-1"); await clock.advance(1 * MINUTE); await step($, usage(0, 301_000)); - expect(seen).toEqual(["quantext: cache expired after 7 min idle; this call re-wrote 301k tokens (~$1.50)."]); + expect(seen).toEqual(["quantext: cache expired after 67 min idle; this call re-wrote 301k tokens (~$1.50)."]); }); test("a model with no known price gets the nudge without a cost", async ($, on) => { const seen = toasts(on); const { step, clock } = stepper(on); await step($, { ...usage(300_000, 1_000), model: "some-model" }); - await clock.advance(6 * MINUTE); + await clock.advance(61 * MINUTE); await step($, { ...usage(0, 301_000), model: "some-model" }); - expect(seen).toEqual(["quantext: cache expired after 6 min idle; this call re-wrote 301k tokens."]); + expect(seen).toEqual(["quantext: cache expired after 61 min idle; this call re-wrote 301k tokens."]); }); -const SUMMARY = [{ role: "user" as const, text: "summary", toolUses: [] }]; -/** The kit hands the call's argument to the hooks as the event: give it the event's own fields. */ -const compact = ($: Engine) => $.session.compact({ trigger: "manual", messages: SUMMARY } as never); - test("crossing 200k context raises one nudge, re-armed after a compaction", async ($, on) => { const seen = toasts(on); const measure = measurer(on); diff --git a/packages/mod/types/index.d.ts b/packages/mod/types/index.d.ts index 3baecec..b826739 100644 --- a/packages/mod/types/index.d.ts +++ b/packages/mod/types/index.d.ts @@ -14,6 +14,10 @@ export type Live = { model?: string; /** Whether the large-context nudge was shown since the last compaction or /clear. */ bigCtxNudged: boolean; + /** Whether the main loop compacted since its last call: the next cache re-write is expected. */ + compacted: boolean; + /** Whether the cache held over a pause longer than 5 minutes: this session's cache lives an hour. */ + hourCache: boolean; }; declare module "claude-code" {