A local-first multi-agent app development platform, built on PenguinHarness
test(core): the prompt cache — assembly invariants, an Anthropic-rule simulator, and the Session lifecycle (#722)
Yaowei Zheng9c3399ad6dea
diff --git a/.agents/skills/penguin-harness-dev/SKILL.md b/.agents/skills/penguin-harness-dev/SKILL.mdindex bb9a03a0..e6c4eb79 100644--- a/.agents/skills/penguin-harness-dev/SKILL.md+++ b/.agents/skills/penguin-harness-dev/SKILL.md@@ -1,6 +1,6 @@---name: penguin-harness-dev-description: Use when developing PenguinHarness itself — changing packages/{core,server,web,cli,desktop,landing,docs,skills}, the built-in model catalog, the installers or the release workflow; writing or auditing changelog entries; writing a blog post or capturing release screenshots; running the test suite here or, when asked, on another machine; deciding what to do about data already on disk; or auditing prose that reads like a leaked authoring session. Covers the two-repo symlink layout, the CI-parity verification chain, the record-and-ship contract, where blog media is hosted, and the seams that are intentional.+description: Use when developing PenguinHarness itself — changing packages/{core,server,web,cli,desktop,landing,docs,skills}, the built-in model catalog, the installers or the release workflow; writing or auditing changelog entries; writing a blog post or capturing release screenshots; running the test suite here or, when asked, on another machine; reading a prompt-cache regression out of the core suites; deciding what to do about data already on disk; or auditing prose that reads like a leaked authoring session. Covers the two-repo symlink layout, the CI-parity verification chain, the record-and-ship contract, where blog media is hosted, and the seams that are intentional.---# Developing PenguinHarness@@ -79,6 +79,7 @@ pnpm --filter @prismshadow/penguin-web test| `packages/docs/content/**`, blog posts under `packages/landing/content/**` | `format:check` + the `docs` and `landing` package tests (search index, blog fixtures) || `plugins/**` (repo root) | the `plugins` package test (loader, README tables, the hook scripts against fake Traces) + `docs`'s `skills-sync.test.ts` || The model catalog | core `model-catalog.test.ts`, web `model-grouping.test.ts` and `protocol-path.test.ts`, server `models.test.ts` |+| Request assembly, history rebuild, compaction, the system prompt, a tool's description or schema | core's three `prompt-cache-*` suites — read the section below before you touch what they report || One package's source | that package's `test`, plus `typecheck` || Exported core types, or anything downstream imports | `pnpm build` + `pnpm typecheck` before any test || `package.json`, the lockfile, `pnpm-workspace.yaml` | `pnpm install --frozen-lockfile` + `pnpm build` |@@ -103,6 +104,30 @@ When a test fails in a way that does not match your diff, when CI reads green tofake or an assertion looks like it proves nothing, read `reference/verification.md` before spendinga second round on it.+## A prompt-cache miss is a cost regression, and it has to be said out loud++A provider serves a cached prefix only while the next request repeats the previous one byte for byte+from the front: the model id, the tools, the fast-mode parameters, the system prompt, the remaining+prompt-affecting parameters, then the messages. Everything from the earliest divergence onward is+re-read at full price, on every request of every running conversation — not only the one in front of+you. A word added to a tool description costs far more than its own tokens.++Three suites in `packages/core/test` hold that line, and a failure means something different in each:++| Failing | What it is telling you |+| --- | --- |+| `prompt-cache-invariants.test.ts` | Your change made a request stop extending its predecessor. This is the regression itself; the diagnostic names the tier that diverged and estimates the input that falls after it. |+| `prompt-cache-lifecycle.test.ts` | The same thing counted in provider tokens. A number that went down is money. |+| `prompt-cache-simulator.test.ts` | You changed the rule engine, not the harness. Only correct when the provider's documented rules changed — go and check the documentation, not the test. |++**Never re-baseline these to green.** Editing an expected number, or adding a case to the list of+misses that are there by design, is a decision about spending the user's money — not a fix. Put the+tier that moved and what it costs in front of them and let them decide.++And say it in the reply, not only in a test log. A cache regression shows up in no other signal this+repo produces: nothing is slower, nothing is wrong on screen, and CI goes green the moment the+numbers are edited. If you do not raise it, it ships.+## Record and shipEvery change ships a changelog entry, in both languages, in `changelog/unreleased/`: adiff --git a/.agents/skills/penguin-harness-dev/reference/verification.md b/.agents/skills/penguin-harness-dev/reference/verification.mdindex 53b508a8..afc41f77 100644--- a/.agents/skills/penguin-harness-dev/reference/verification.md+++ b/.agents/skills/penguin-harness-dev/reference/verification.md@@ -29,6 +29,31 @@ text in a test is house style here (20 web test files do it), which makes it easshape the file already had. Replay each new assertion against `git show <base>:<path>` and keepthe ones that fail there.+## A prompt-cache number that moved++The diagnostic reports the **earliest** divergence between two consecutive requests and nothing+after it, because nothing after it matters: the prefix is matched from the front, so the first tier+that differs is where the cache stops and the whole remainder is re-read. `model_changed` costs+everything and has no escape — no breakpoint can sit in front of the model id. `tools_changed`+costs the system prompt and the messages. `system_changed` costs the messages. `messages_changed`+is the ordinary case and is usually fine, since an extended history is exactly what a cache serves.++So read the tier before you read the token count. A change that moved `messages_changed` later in+the conversation is noise; a change that turned `messages_changed` into `system_changed` moved the+cost of every future request in every conversation, however small the diff looked.++Some misses are there by design and the lifecycle suite names each one with its reason: a+thinking-level move, a compaction reopen and a subagent child's first request each read nothing,+even though the tools and system prompt go out byte-identical, because the harness sends one+automatic breakpoint at the end of the request and no entry ever ended at the system block. Those+are properties of what AgentHub sends, not defects in the change under test. Adding a **new** name+to that list is the thing you must not do quietly.++The simulator is offline: it encodes the documented rules over the same recordings, which makes it+exact about the harness's half and only as good as the documentation about the provider's. It is+evidence that request assembly did not move; it is not evidence that a live deployment behaves this+way. When the two disagree, the endpoint wins and the simulator's rule is the bug.+## Reading CI without fooling yourself**On a conflicting PR, waiting for CI is waiting for nothing.** The workflows run against thediff --git a/changelog/unreleased/2026-09-14-prompt-cache-awareness.md b/changelog/unreleased/2026-09-14-prompt-cache-awareness.mdnew file mode 100644index 00000000..d320cd4a--- /dev/null+++ b/changelog/unreleased/2026-09-14-prompt-cache-awareness.md@@ -0,0 +1,77 @@+# The core suite pins prompt-cache-aware request assembly++- **Date:** 2026-09-14+- **Type:** test+- **Scope:** `core`+- **PR:** [#722](https://github.com/Prism-Shadow/penguin-harness/pull/722)++[中文版](2026-09-14-prompt-cache-awareness.zh.md)++A provider serves a cached prefix only when the next request repeats the previous one byte for+byte from the front — tools, then the system prompt, then the messages — so every turn the engine+assembles has to leave the request an extension of the last one.+`packages/core/test/prompt-cache-invariants.test.ts` now pins that: a real `ContextEngine` drives+a real `GenerativeModel` whose provider stream is scripted, and each consecutive pair of requests+is diagnosed on the wire shape the client would have sent, by a client-side diagnostic modelled+on the cache-miss reasons a provider reports (`model_changed` / `system_changed` /+`tools_changed` / `parameters_changed` / `messages_changed`, earliest divergence first, with an+estimate of the input that falls after it).++## Details++- Pinned as behaviour: every request of a session extends the previous one; a steering message+ delivered mid-task rides the same user turn as the tool result; a thinking-level move costs+ exactly one `parameters_changed` and then holds — the compaction request and the context+ compaction opens both carry the moved level; the compaction request extends the turn it+ follows; and a resumed session's first request opens with the live client's committed history,+ thinking signatures and tool pairing included.+- One reading was worth stating as its own invariant: a reconnect after a partially streamed attempt re-sends the turn with a `[turn_retried]` note carrying what the attempt already produced, so the retried turn's input grows rather than repeating. Everything before that input stays byte-identical (tools, system prompt and history still hit); the suite pins that the divergence never moves earlier and that the original input still leads the retried one.+- `packages/core/test/helpers/prompt-cache/` holds the shared machinery, a file per part:+ `recording.ts` (the scripted provider stream and the per-request wire recording),+ `diagnostics.ts` (the cache-miss diagnostic), `simulator.ts` (the provider half below) and+ `fixtures.ts` (the agent, the fake collaborators and the hit assertion the two Session suites+ share), re-exported from `index.ts`. The recording and the diagnostic measure the harness's half+ only: cache lifetime, breakpoint lookback and minimum cacheable size belong to the provider —+ modelled offline by the simulator, though only a live endpoint proves a real deployment behaves+ this way.+- `packages/core/test/helpers/prompt-cache/simulator.ts` adds that provider half as a rule engine+ over the same recordings: an Anthropic-shaped prompt cache that reads each request as a block+ list (the model id, one block per tool, a virtual block for the fast-mode parameters, the+ system prompt, a virtual block for the remaining prompt-affecting parameters, then every+ message content block), groups it into positions — a run of `tool_use` or `tool_result` blocks+ counting as one — writes **only at a breakpoint**, serves a read by looking back at most twenty+ positions from each breakpoint's own position (the breakpoint itself counting as the first),+ refuses a prefix under 1024 tokens, and expires an entry five minutes after its last use on an+ injected clock. That block order is what reproduces the documented invalidation hierarchy, the+ cache's scoping to one model included: a model switch loses everything and no breakpoint can be+ placed in front of it, a fast-mode toggle keeps the tools and loses the system prompt, and a+ thinking-level move keeps both — on the models that render the thinking configuration after+ them, which the documentation marks as model-specific. By default it models what AgentHub's+ Claude client sends: one+ automatic breakpoint at the last block, so the only entries in the cache end at whole requests+ and content sitting behind a breakpoint is never separately addressable. A+ `breakpoints: "tools-system-automatic"` option models the alternative the API allows —+ explicit breakpoints on the last tool block and on the system block alongside the automatic+ one. It answers in the numbers a provider reports: `cache_read_input_tokens`,+ `cache_creation_input_tokens`, `input_tokens` and the resulting hit ratio.+ `packages/core/test/prompt-cache-simulator.test.ts` pins those rules on hand-built requests.+- `packages/core/test/prompt-cache-lifecycle.test.ts` runs a real `Session` through the Session+ lifecycle against one simulated provider — child sessions and reopened contexts included — and+ asserts on those numbers that every request reads back the whole prefix of its context's+ previous request: an ordinary conversation, an interruption, a `run_in_background` command's+ completion notice, a call the user moves to the background, three parallel tool calls, a+ subagent, a scheduled-task trigger, a resume through a Trace, a thinking-level move and a+ compaction. Every case that cannot hit by design is named with its reason and its loss bounded:+ an interruption falls back to the breakpoint the request before it closed; and a thinking-level+ move, a compaction reopen and a subagent child's first request each read nothing at all, even+ where the tools and the system prompt go out byte-identical, because with one breakpoint at the+ end of the request no entry ever ended at the system block.+- What the extra breakpoints would recover is measured rather than argued, and measured on+ hand-built requests so it costs no scenario run and cannot move when AgentHub changes: under+ `breakpoints: "tools-system-automatic"` a system-prompt change still reads the tools back, a+ fast-mode toggle still reads the tools back, a thinking-level move still reads the tools and+ the system prompt back, and a conversation whose messages have run far past the lookback window+ still reads the fixed prefix back from the breakpoint that sits next to it — where the single+ automatic breakpoint the harness sends today reads nothing in every one of those cases. The+ parameters block behind the system breakpoint stays unreadable either way, so a thinking-level+ move still costs the messages.diff --git a/changelog/unreleased/2026-09-14-prompt-cache-awareness.zh.md b/changelog/unreleased/2026-09-14-prompt-cache-awareness.zh.mdnew file mode 100644index 00000000..2643accc--- /dev/null+++ b/changelog/unreleased/2026-09-14-prompt-cache-awareness.zh.md@@ -0,0 +1,58 @@+# core 测试固定了面向 Prompt 缓存的请求组装++- **Date:** 2026-09-14+- **Type:** test+- **Scope:** `core`+- **PR:** [#722](https://github.com/Prism-Shadow/penguin-harness/pull/722)++[English](2026-09-14-prompt-cache-awareness.md)++只有当下一次请求从头逐字节重复上一次——先 tools,再 system prompt,最后 messages——供应商才会命中+缓存前缀,因此引擎组装的每一轮都必须让请求保持为上一次的延长。+`packages/core/test/prompt-cache-invariants.test.ts` 现在固定了这一点:由真实的 `ContextEngine`+驱动真实的 `GenerativeModel`(其供应商流被脚本替换),对每一对相邻请求按客户端真正会发出的 wire+形态做诊断,诊断口径对齐供应商上报的缓存未命中原因(`model_changed` / `system_changed` /+`tools_changed` / `parameters_changed` / `messages_changed`,取最早的分歧点,并给出分歧之后的+输入量估算)。++## 细节++- 被固定的行为:一个 Session 的每次请求都延长上一次;任务执行中投递的 steering 与工具结果同乘一条+ user 轮次;调整 thinking 级别只产生一次 `parameters_changed` 并就此保持——压缩请求与压缩开出的新+ 上下文都带着调整后的级别;压缩请求延长它紧跟的那一轮;恢复会话的首个请求以活动客户端已提交的+ 历史开头,thinking 签名与工具配对都在。+- 有一条读数值得单独写成不变量:流式输出中途断线后的重连,会把这一轮连同一条带上已产出内容的 `[turn_retried]` 说明一起重发,因此被重试那一轮的输入是「变长」而不是「原样重复」。它之前的所有消息逐字节不变(工具、系统提示词与历史仍然命中);测试固定的是分歧点绝不会提前,且原输入仍位于重试输入的开头。+- `packages/core/test/helpers/prompt-cache/` 按职责分文件收纳共用设施:`recording.ts`(脚本化的+ 供应商流与逐请求的 wire 录制)、`diagnostics.ts`(缓存未命中诊断)、`simulator.ts`(下面那一半+ 供应商规则)与 `fixtures.ts`(两个 Session 测试共用的 Agent、假协作者与命中断言),并由+ `index.ts` 统一再导出。录制与诊断只度量 harness 这一半:缓存有效期、断点回溯范围与最小可缓存+ 长度属于供应商——由模拟器在离线状态下建模,但只有真实 endpoint 才能证明某个实际部署确实如此。+- `packages/core/test/helpers/prompt-cache/simulator.ts` 以规则引擎的形式补上供应商这一半,输入仍是+ 同一批录制请求:一个 Anthropic 形态的 Prompt 缓存,把每次请求读成 block 列表(Model id 一个 block、+ 每个工具一个、承载 fast mode 参数的虚拟 block 一个、system prompt 一个、承载其余影响 Prompt 的参数+ 的虚拟 block 一个,随后是每条消息的每个内容 block),再归并成 position(连续的 `tool_use` 或+ `tool_result` 合并为一个),**只在断点处写入**,读取时每个断点都从自己所在的 position 往前回溯,最多+ 检查二十个 position(断点本身算第一个),拒绝缓存不足 1024 Token 的前缀,并按可注入的时钟在最后一次+ 使用后五分钟过期。这个 block 顺序正是文档所述失效层级的还原,也包括缓存按 Model 隔离这一条:切换+ Model 会丢掉全部前缀,且没有任何断点能排在它前面;切换 fast mode 保住工具、丢掉 system prompt;调整+ thinking 级别两者都保住——这一条只在把 thinking 配置渲染在它们之后的 Model 上成立,文档本身就标注为+ 因 Model 而异。默认建模的就是 AgentHub 的 Claude 客户端当前发出的形态:最后一个+ block 上只有一个自动断点,因此缓存中的条目全都以「整个请求」结尾,断点之后的内容永远不可单独寻址。+ `breakpoints: "tools-system-automatic"` 选项建模 API 允许的另一种布局——在最后一个工具 block 与+ system block 上各加一个显式断点,与自动断点并存。它的输出就是供应商上报的那几个数:+ `cache_read_input_tokens`、`cache_creation_input_tokens`、`input_tokens` 与由此得到的命中率。+ `packages/core/test/prompt-cache-simulator.test.ts` 用手工构造的请求固定这些规则本身。+- `packages/core/test/prompt-cache-lifecycle.test.ts` 让真实 `Session` 跑完整个会话生命周期,所有+ 请求(含子 Session 与压缩后开出的新上下文)都送进同一个模拟供应商,并用这些数值断言:每次请求都能+ 读回本上下文上一次请求的完整前缀——普通对话、中断、`run_in_background` 命令的完成通知、用户把执行+ 中的调用转入后台、一轮三个并行工具调用、子 Agent、定时任务触发、经 Trace 恢复、调整 thinking 级别+ 与上下文压缩。+ 每一种按设计无法命中的情形都写明原因并给出损失上界:中断回退到它前一次请求所封闭的那个断点;调整+ thinking 级别、压缩重开上下文、子 Agent 的首个请求三者都读到 0——哪怕工具与 system prompt 逐字节相同+ 也如此,因为断点只在请求末尾,从来没有条目以 system block 结尾。+- 多加两个断点能挽回多少,是被测出来而不是被论证出来的;而且测在手工构造的请求上,既不占用一次场景+ 驱动,也不会随 AgentHub 的变化而漂移:在 `breakpoints: "tools-system-automatic"` 下,改 system+ prompt 仍能读回 tools,切换 fast mode 仍能读回 tools,调整 thinking 级别仍能读回 tools 加 system+ prompt,消息数远超回溯窗口的对话也仍能从紧邻的那个断点读回固定前缀——而 harness 今天只发一个自动+ 断点,以上每一种情形都读到 0。两种布局下 system 断点之后的参数 block 都读不回来,因此调整 thinking+ 级别依旧要付出全部消息的代价。diff --git a/packages/core/test/helpers/prompt-cache/diagnostics.ts b/packages/core/test/helpers/prompt-cache/diagnostics.tsnew file mode 100644index 00000000..d6ae1cff--- /dev/null+++ b/packages/core/test/helpers/prompt-cache/diagnostics.ts@@ -0,0 +1,203 @@+/**+ * The diagnostic: where two consecutive requests stopped being one growing prefix.+ *+ * A provider serves a cached prefix only when the next request repeats the previous one byte for+ * byte from the front — tools, then the system prompt, then the messages. `diagnoseCacheMiss`+ * takes two requests that `recording.ts` captured and names the earliest level at which that+ * stops holding, in the vocabulary and the precedence order of the `cache_miss_reason` Anthropic+ * reports: model, system, tools, the remaining prompt-affecting parameters, then the messages.+ *+ * This is the harness's half of prompt caching, and it is a statement about bytes only. Whether a+ * prefix that could hit actually did — lifetime, breakpoint lookback, minimum cacheable size — is+ * `simulator.ts`, which calls back into this file to name the divergence behind a modelled miss.+ */+import type { RecordedRequest } from "./recording.js";++/** Rough characters-per-token ratio, only used to size the input a divergence invalidates. */+const CHARS_PER_TOKEN = 4;+/**+ * Request config keys that do not take part in the cached prefix: the window-derived output cap,+ * the transport flag, and the breakpoint marker. A `cache_control` marker says where the provider+ * should write, never what the prompt is, so moving it invalidates nothing — `simulator.ts`+ * leaves it out of the block list for the same reason. Exported so the suites strip exactly this+ * list rather than keeping a third copy of it.+ */+export const NON_PREFIX_CONFIG_KEYS = ["max_tokens", "stream", "cache_control"];++/** The earliest divergence between two consecutive requests, in provider precedence order. */+export type CacheMissReason =+ | { type: "none" }+ | { type: "model_changed" }+ | { type: "system_changed" }+ | { type: "tools_changed"; detail: string }+ /** thinking / output_config / tool_choice / speed / betas — everything prompt-affecting+ * except the keys in NON_PREFIX_CONFIG_KEYS. */+ | { type: "parameters_changed"; keys: string[] }+ | {+ type: "messages_changed";+ index: number;+ detail: string;+ cache_missed_input_estimate: number;+ };++const json = (value: unknown): string => JSON.stringify(value ?? null);++// ---- Diagnosing -----------------------------------------------------------++/**+ * The earliest level at which `next` stops being an extension of `prev`, in the order a+ * provider invalidates them: model, system, tools, the remaining prompt-affecting parameters,+ * then the messages. `max_tokens` is excluded — it does not take part in the cached prefix.+ */+export function diagnoseCacheMiss(prev: RecordedRequest, next: RecordedRequest): CacheMissReason {+ const before = prefixConfig(prev.wireConfig);+ const after = prefixConfig(next.wireConfig);+ if (json(before.model) !== json(after.model)) return { type: "model_changed" };+ if (json(before.system) !== json(after.system)) return { type: "system_changed" };+ if (json(before.tools) !== json(after.tools)) {+ return { type: "tools_changed", detail: describeToolChange(before.tools, after.tools) };+ }+ const keys = changedKeys(before, after, ["model", "system", "tools"]);+ if (keys.length > 0) return { type: "parameters_changed", keys };+ return diagnoseMessages(prev.wire, next.wire);+}++/** `diagnoseCacheMiss` over each consecutive pair: entry i describes request i -> i+1. */+export function diagnoseSeries(requests: RecordedRequest[]): CacheMissReason[] {+ const reasons: CacheMissReason[] = [];+ for (let i = 1; i < requests.length; i += 1) {+ reasons.push(diagnoseCacheMiss(requests[i - 1]!, requests[i]!));+ }+ return reasons;+}++/** The config keys that take part in the cached prefix. */+function prefixConfig(wireConfig: Record<string, unknown>): Record<string, unknown> {+ const copy: Record<string, unknown> = { ...wireConfig };+ for (const key of NON_PREFIX_CONFIG_KEYS) delete copy[key];+ return copy;+}++function changedKeys(+ before: Record<string, unknown>,+ after: Record<string, unknown>,+ skip: string[],+): string[] {+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);+ for (const key of skip) keys.delete(key);+ return [...keys].filter((key) => json(before[key]) !== json(after[key])).sort();+}++function describeToolChange(before: unknown, after: unknown): string {+ const prev = Array.isArray(before) ? before : [];+ const next = Array.isArray(after) ? after : [];+ const names = (list: unknown[]): string[] =>+ list.map((tool) => String((tool as { name?: unknown }).name ?? "?"));+ const prevNames = names(prev);+ const nextNames = names(next);+ if (json(prevNames) !== json(nextNames)) {+ return `names [${prevNames.join(", ")}] -> [${nextNames.join(", ")}]`;+ }+ for (let i = 0; i < prev.length; i += 1) {+ if (json(prev[i]) !== json(next[i])) return `"${prevNames[i]}" definition changed`;+ }+ return "tool list changed";+}++function diagnoseMessages(prev: unknown[], next: unknown[]): CacheMissReason {+ for (let i = 0; i < prev.length; i += 1) {+ if (i >= next.length) {+ return {+ type: "messages_changed",+ index: i,+ detail: `history shrank from ${prev.length} to ${next.length} messages`,+ cache_missed_input_estimate: missedInput(next, i),+ };+ }+ if (json(prev[i]) !== json(next[i])) {+ return {+ type: "messages_changed",+ index: i,+ detail: describeMessageChange(i, prev[i], next[i]),+ cache_missed_input_estimate: missedInput(next, i),+ };+ }+ }+ return { type: "none" };+}++/** Roughly how much input sits after the divergence, and so has to be read again. */+function missedInput(next: unknown[], index: number): number {+ return Math.ceil(JSON.stringify(next.slice(index)).length / CHARS_PER_TOKEN);+}++function describeMessageChange(index: number, prev: unknown, next: unknown): string {+ const prevBlocks = blocksOf(prev);+ const nextBlocks = blocksOf(next);+ const prevRole = roleOf(prev);+ const nextRole = roleOf(next);+ const role = prevRole === nextRole ? prevRole : `${prevRole} -> ${nextRole}`;+ const count = Math.max(prevBlocks.length, nextBlocks.length);+ let at = count;+ for (let i = 0; i < count; i += 1) {+ if (json(prevBlocks[i]) !== json(nextBlocks[i])) {+ at = i;+ break;+ }+ }+ return `${role} message #${index}, block ${at}: ${blockType(prevBlocks[at])} -> ${blockType(+ nextBlocks[at],+ )}`;+}++const roleOf = (message: unknown): string =>+ String((message as { role?: unknown } | undefined)?.role ?? "?");++function blocksOf(message: unknown): unknown[] {+ const content = (message as { content?: unknown } | undefined)?.content;+ if (Array.isArray(content)) return content;+ return content === undefined ? [] : [content];+}++const blockType = (block: unknown): string =>+ block === undefined ? "absent" : String((block as { type?: unknown }).type ?? "?");++// ---- Reporting ------------------------------------------------------------++/** A compact per-request table, for the message of a failing assertion. */+export function formatDiagnostics(requests: RecordedRequest[], reasons: CacheMissReason[]): string {+ const rows = requests.map((request, i) => [+ `#${request.index}`,+ `messages=${request.wire.length}`,+ thinkingLabel(request.wireConfig),+ i === 0 ? "(first request)" : describeMissReason(reasons[i - 1]),+ ]);+ const widths = [0, 1, 2].map((col) => Math.max(...rows.map((row) => row[col]!.length)));+ const lines = rows.map((row) =>+ row.map((cell, col) => (col < 3 ? cell.padEnd(widths[col]!) : cell)).join(" "),+ );+ return ["prompt-cache diagnostics:", ...lines].join("\n");+}++function thinkingLabel(wireConfig: Record<string, unknown>): string {+ const thinking = wireConfig.thinking as { type?: string; display?: string } | undefined;+ const effort = (wireConfig.output_config as { effort?: string } | undefined)?.effort;+ const mode = thinking ? `${thinking.type ?? "?"}/${thinking.display ?? "?"}` : "off";+ return `thinking=${mode} effort=${effort ?? "-"}`;+}++/** One cache-miss reason as a single line, in the vocabulary a provider's diagnostics use. */+export function describeMissReason(reason: CacheMissReason | undefined): string {+ if (!reason) return "?";+ if (reason.type === "tools_changed") return `tools_changed (${reason.detail})`;+ if (reason.type === "parameters_changed") {+ return `parameters_changed [${reason.keys.join(", ")}]`;+ }+ if (reason.type === "messages_changed") {+ return (+ `messages_changed at #${reason.index} (${reason.detail}), ` ++ `~${reason.cache_missed_input_estimate} input tokens after the divergence`+ );+ }+ return reason.type;+}diff --git a/packages/core/test/helpers/prompt-cache/fixtures.ts b/packages/core/test/helpers/prompt-cache/fixtures.tsnew file mode 100644index 00000000..176c7f25--- /dev/null+++ b/packages/core/test/helpers/prompt-cache/fixtures.ts@@ -0,0 +1,323 @@+/**+ * The scenery the Session suites stand on: one agent, fake collaborators, and the assertion the+ * lifecycle scenarios share.+ *+ * `prompt-cache-invariants.test.ts` and `prompt-cache-lifecycle.test.ts` drive the same agent —+ * same tools, same system prompt, same model id — so the fixtures live here and each suite keeps+ * only what is its own. The system prompt is the size a real one is, because a fixed prefix under+ * the provider's minimum would turn every number the lifecycle suite reports into a statement+ * about the minimum instead of about the harness.+ *+ * The requests come from `recording.ts`, the numbers from `simulator.ts`, and the reason behind a+ * miss from `diagnostics.ts`. `expectHits` is where those meet: every request reads back the whole+ * prefix of its context's previous request, unless the scenario names the index and bounds the+ * loss itself.+ */+import { expect } from "vitest";+import { toolCallOutput } from "../../../src/omnimessage/index.js";+import type {+ OmniMessage,+ SessionMetaPayload,+ ToolDefinition,+} from "../../../src/omnimessage/index.js";+import type {+ ApproveFn,+ EnvironmentInterface,+ GenerativeModelConfig,+} from "../../../src/interfaces/index.js";+import type { CompactionSettings } from "../../../src/engine/context-engine.js";+import type { RecordedRequest, ScriptedReply } from "./recording.js";+import {+ DEFAULT_MIN_CACHEABLE_TOKENS,+ PromptCacheSim,+ formatCacheReport,+ prefixTokens,+ previousInContext,+ toolsAndSystemTokens,+} from "./simulator.js";+import type { CacheUsage } from "./simulator.js";++// ---- The agent both suites drive ------------------------------------------++/**+ * A system prompt of the size a real agent carries. It has to clear the provider's minimum+ * cacheable prefix on its own, or every number the lifecycle suite reports would be a statement+ * about the minimum rather than about the harness (`expectHits` asserts that it does).+ */+export const SYSTEM_PROMPT = [+ "You are a coding agent working inside a sandboxed workspace on behalf of one user.",+ "You have a shell, a file reader and a file writer, and nothing else runs on your behalf.",+ "",+ "# Working rules",+ "",+ "Read a file before you change it. A patch written from memory is a guess, and a guess that",+ "compiles is worse than one that does not, because nobody notices it.",+ "Keep every change as small as the task allows. When a task needs three unrelated edits, make",+ "them as three changes, not as one that happens to touch three places.",+ "Never call a tool that is not on the list you were given, and never invent a path you have",+ "not seen in output. If you need to know whether something exists, look.",+ "When a command fails, read the whole error before you react to it. The first line of a stack",+ "trace is rarely the line that matters, and the exit code is never the whole story.",+ "Prefer the workspace's own scripts to hand-rolled equivalents: if there is a build script,",+ "run the build script, because it encodes decisions you cannot see from the file tree.",+ "",+ "# Tool use",+ "",+ "Every tool call names the file or the command it touches, in the words the user would use.",+ "Long output is summarized rather than pasted back in full; keep the part that carries the",+ "decision and drop the part that only proves you ran something.",+ "A command that may run for more than a few seconds goes to the background, and you report",+ "its identifier so the user can follow it. Do not sit on a foreground shell waiting.",+ "When several files must be read to answer one question, ask for them together rather than",+ "one at a time: a round trip costs the user more than a longer answer does.",+ "Do not retry a failing command unchanged. Either change something about it, or say plainly",+ "that it fails and what the failure looks like.",+ "",+ "# Answering",+ "",+ "Say what you changed and why, in that order, and keep it to what the user did not already",+ "know. Repeating the request back to the user is not a summary of the work.",+ "State uncertainty where it exists. 'This should work but I could not run the tests' is a",+ "useful sentence; 'this works' when you did not check is not.",+ "If the task turns out to be a different task than the one described, say so before doing the",+ "different task. The user may have meant what they said.",+ "Never claim a test passed, a build succeeded or a file changed unless the output you were",+ "given says so. An unverified claim costs more to undo than an admitted gap costs to fill.",+ "",+ "# Output",+ "",+ "Write plain sentences. No headings for a two-line answer, no bullet list of three words, no",+ "restatement of these rules back to the user.",+ "Use the user's own vocabulary for files, commands and concepts once they have used it.",+ "When you cannot finish, end with what remains and what you would try next, not with an",+ "apology. The next step is the useful part.",+ "",+ "# Reading a codebase",+ "",+ "Start from the entry point the build declares, not from the file whose name looks closest to",+ "the task. Names drift; build configuration does not.",+ "Follow a symbol to its definition before you reason about it. Two functions with the same",+ "name in one repository is the normal case, not the surprising one.",+ "Read the tests around a behaviour before you change the behaviour. A test is the only place",+ "the previous author wrote down what they meant, and it is usually shorter than the code.",+ "When a file is longer than you can hold, read its top and its exports first, then the one",+ "region the task touches. Reading the middle of a file you have no map of teaches you little.",+ "Configuration counts as code. A value that reaches the running program from a TOML file is",+ "no less part of the behaviour than a value written in a source literal.",+ "",+ "# Editing",+ "",+ "Match the surrounding style rather than the style you prefer. A patch that reads as though",+ "the file's author wrote it costs the reviewer nothing; one that does not costs an argument.",+ "Change one thing per edit and keep the edit adjacent to what it changes. A rename spread",+ "across twenty files and a behaviour change in one of them is a review nobody can do.",+ "Do not delete code you do not understand. Find out what it is for, or leave it and say that",+ "you left it; silently removing a guard is how an incident starts.",+ "Leave the workspace buildable at every point where you stop. If you cannot, say so in the",+ "same breath as the change, and say which command reproduces the breakage.",+ "Comments explain why, not what. If a line needs a comment to say what it does, rewrite the",+ "line instead of annotating it.",+ "",+ "# Safety",+ "",+ "Never run a command that reaches outside the workspace unless the user asked for it in those",+ "words. The workspace boundary is the whole of your permission, not a default you may widen.",+ "Never write a credential, a token or a private key into a file, a log line or an answer, even",+ "one you were given in this conversation.",+ "A destructive command — a recursive delete, a force push, a database drop — is announced",+ "before it runs and named for what it destroys. If you cannot name it, do not run it.",+ "When a command would take longer than the user is likely to wait, say so before starting it",+ "rather than after. An unexplained silence reads as a hang.",+ "",+ "# When you are stuck",+ "",+ "Say what you tried, what you expected and what happened instead. Those three sentences are",+ "worth more than another round of guessing.",+ "Reduce the problem before you widen the search. A failing case you can run in one second",+ "beats a theory you can only test by rebuilding everything.",+ "Ask the user for the one fact that would settle it, rather than for guidance in general. A",+ "question that can be answered in a word gets answered; an open one gets ignored.",+].join("\n");++export const TOOLS: ToolDefinition[] = [+ {+ name: "exec_command",+ description:+ "Run a shell command in the workspace and return its output. Use run_in_background " ++ "for anything that outlives a few seconds; the completion arrives as a user message.",+ parameters: {+ type: "object",+ properties: {+ cmd: { type: "string", description: "The command line to run." },+ run_in_background: { type: "boolean", description: "Detach and report on completion." },+ yield_time_ms: { type: "number", description: "How long to wait before yielding." },+ },+ required: ["cmd"],+ },+ },+ {+ name: "read_file",+ description: "Read a UTF-8 text file from the workspace, optionally a line range of it.",+ parameters: {+ type: "object",+ properties: {+ path: { type: "string", description: "Workspace-relative path." },+ offset: { type: "number", description: "First line to read (1-based)." },+ limit: { type: "number", description: "How many lines to read." },+ },+ required: ["path"],+ },+ },+];++// ---- Session identity and configuration -----------------------------------++export const SESSION_ID = "sess-prompt-cache";+export const CHILD_SESSION_ID = "sess-prompt-cache-child";+/** The one context label a single-context scenario uses. */+export const MAIN = "main";++export const META: SessionMetaPayload = {+ session_id: SESSION_ID,+ provider: "anthropic",+ model_id: "claude-sonnet-4-6",+ model_context_window: 200000,+ system_prompt: SYSTEM_PROMPT,+ agent_state: "/tmp/penguin-prompt-cache/state",+ workspace: "/tmp/penguin-prompt-cache/workspace",+};++export const modelConfig = (over: Partial<GenerativeModelConfig> = {}): GenerativeModelConfig => ({+ modelId: "claude-sonnet-4-6",+ tools: TOOLS,+ systemPrompt: SYSTEM_PROMPT,+ ...over,+});++/** The compaction prompt, named so a suite can assert on the turn it is appended to. */+export const COMPACTION_PROMPT = "Summarize this conversation so the next context can carry on.";++export const compactionSettings = (over: Partial<CompactionSettings> = {}): CompactionSettings => ({+ maxContextLength: 100,+ maxSessionTurns: -1,+ mode: "summarize",+ prompt: COMPACTION_PROMPT,+ ...over,+});++// ---- Fake collaborators ---------------------------------------------------++export const allowAll: ApproveFn = async () => "allow";++/** Fake Environment that never runs a real command: any tool call answers with fixed output. */+export const fakeEnvironmentWith = (tools: ToolDefinition[]): EnvironmentInterface => ({+ async listTools() {+ return tools;+ },+ async *executeTool({ toolCall: call }) {+ yield toolCallOutput({ output: "tool ran", toolCallId: call.payload.tool_call_id });+ },+ toolPermission() {+ return "rw";+ },+});++export const fakeEnvironment = fakeEnvironmentWith(TOOLS);++/** Drains a run to its end and keeps the messages it streamed. */+export async function collect<T>(gen: AsyncGenerator<OmniMessage, T>): Promise<OmniMessage[]> {+ const all: OmniMessage[] = [];+ for (;;) {+ const res = await gen.next();+ if (res.done) return all;+ all.push(res.value);+ }+}++// ---- Scripted replies -----------------------------------------------------++/** A tool-calling first reply, reused by the cases that need a two-turn task. */+export const toolTurn = (over: Partial<ScriptedReply> = {}): ScriptedReply => ({+ thinking: { text: "The entry point is the place to start.", signature: "sig-turn-1" },+ toolCalls: [{ id: "call_1", name: "read_file", args: { path: "src/index.ts" } }],+ ...over,+});++// ---- Reading a recorded request -------------------------------------------++/** One message of a request's wire form, as the suites read it back. */+export interface WireMessage {+ role: string;+ content: { type: string; text?: string; signature?: string }[];+}++export const wireMessage = (request: RecordedRequest, index: number): WireMessage =>+ request.wire.at(index) as WireMessage;++export const blockTypes = (message: WireMessage): string[] =>+ message.content.map((block) => block.type);++// ---- Running a scenario through one simulated provider --------------------++/** Collects the issue order across every model of a scenario (see RecordingOptions.onRequest). */+export function ordering(): { order: RecordedRequest[]; onRequest: (r: RecordedRequest) => void } {+ const order: RecordedRequest[] = [];+ return { order, onRequest: (request) => order.push(request) };+}++/** Runs every recorded request through one provider-side cache, in issue order. */+export function replay(order: RecordedRequest[], sim = new PromptCacheSim()): CacheUsage[] {+ return order.map((request) => sim.request(request));+}++// ---- The assertion every lifecycle scenario shares -------------------------++/**+ * Every request after the first of its context must read back the whole prefix of that+ * context's previous request. An index named in `allowed` is exempted with a stated reason —+ * the scenario then bounds its loss itself — and a context opening anywhere but at the very+ * first request must be named too, so a fresh cache line can never appear unremarked.+ *+ * An exemption has to earn itself: the named request must actually fall short of the prefix it+ * would otherwise be held to, so a reason left behind by a flow that has since started hitting+ * fails here rather than quietly weakening the suite.+ */+export function expectHits(+ requests: RecordedRequest[],+ usages: CacheUsage[],+ allowed: Map<number, string> = new Map(),+): void {+ const report = formatCacheReport(requests, usages);+ expect(usages, report).toHaveLength(requests.length);+ expect(requests.length, report).toBeGreaterThan(0);+ // A fixture whose fixed prefix is under the provider's minimum would make every number the+ // scenarios report a statement about the minimum instead of about the harness.+ expect(toolsAndSystemTokens(requests[0]!), report).toBeGreaterThanOrEqual(+ DEFAULT_MIN_CACHEABLE_TOKENS,+ );+ for (const [index, reason] of allowed) {+ expect(index, `allowed miss #${index} names no request\n${report}`).toBeLessThan(+ requests.length,+ );+ // A request that opens a context is held to its own prefix: it may not arrive fully read.+ const before = previousInContext(requests, index);+ const whole = prefixTokens(requests[before < 0 ? index : before]!);+ expect(+ usages[index]!.cache_read_input_tokens,+ `#${index} is exempted as "${reason}", but it reads that whole prefix back — ` ++ `drop the exemption\n${report}`,+ ).toBeLessThan(whole);+ }+ for (let i = 0; i < requests.length; i += 1) {+ const previous = previousInContext(requests, i);+ if (allowed.has(i)) continue;+ if (previous < 0) {+ expect(i, `#${i} opens a context with no reason given\n${report}`).toBe(0);+ continue;+ }+ expect(+ usages[i]!.cache_read_input_tokens,+ `#${i} should read back all of #${previous}\n${report}`,+ ).toBeGreaterThanOrEqual(prefixTokens(requests[previous]!));+ }+}diff --git a/packages/core/test/helpers/prompt-cache/index.ts b/packages/core/test/helpers/prompt-cache/index.tsnew file mode 100644index 00000000..bd3443d5--- /dev/null+++ b/packages/core/test/helpers/prompt-cache/index.ts@@ -0,0 +1,20 @@+/**+ * The prompt-cache test helpers, in the order a reader meets them.+ *+ * - `recording.ts` drives a real model over a scripted provider stream and captures every+ * request in the shape the client would have put on the wire.+ * - `diagnostics.ts` takes two consecutive recordings and names the earliest point at which+ * the second stopped being an extension of the first.+ * - `simulator.ts` runs the recordings through Anthropic's cache rules and answers what a+ * provider would actually have read back, in the numbers a provider reports.+ * - `fixtures.ts` holds the agent, the fake collaborators and the assertion the Session+ * suites share.+ *+ * Three suites import from here: `prompt-cache-invariants.test.ts` (the harness's assembly+ * invariants), `prompt-cache-simulator.test.ts` (the simulator's own rules) and+ * `prompt-cache-lifecycle.test.ts` (the whole Session lifecycle, measured through the simulator).+ */+export * from "./recording.js";+export * from "./diagnostics.js";+export * from "./simulator.js";+export * from "./fixtures.js";diff --git a/packages/core/test/helpers/prompt-cache/recording.ts b/packages/core/test/helpers/prompt-cache/recording.tsnew file mode 100644index 00000000..21eee0a8--- /dev/null+++ b/packages/core/test/helpers/prompt-cache/recording.ts@@ -0,0 +1,259 @@+/**+ * The recorder: a scripted provider stream, and the wire form of every request it sees.+ *+ * `recordingModel` returns a real `GenerativeModel` with one thing replaced — the provider+ * client's stream, which reads from a script instead of the network. Everything else runs for+ * real: the model builds the UniConfig, AgentHub merges the input into its stateful history, and+ * the recorded request is the output of the provider's own transforms. A `RecordedRequest` is+ * therefore the bytes the client would have put on the wire, not the internal UniMessage form.+ *+ * The other files here read those recordings. `diagnostics.ts` says why two consecutive requests+ * stopped being one growing prefix; `simulator.ts` says what a provider with Anthropic's cache+ * rules would actually have read back; `fixtures.ts` holds the scenery the Session suites share.+ */+import type { UniConfig, UniEvent, UniMessage } from "@prismshadow/agenthub";+import type { GenerativeModelConfig } from "../../../src/interfaces/index.js";+import { GenerativeModel } from "../../../src/llm/index.js";++/** Response tokens reported by every scripted reply (the input side is what the tests steer). */+const SCRIPTED_RESPONSE_TOKENS = 1;+/** Input tokens a scripted reply reports when it names none. */+const DEFAULT_PROMPT_TOKENS = 10;+/**+ * Cache-read input tokens every scripted reply reports. Always zero: what a provider would have+ * served from its cache is modelled offline by `simulator.ts`, never scripted into a reply.+ */+const SCRIPTED_CACHED_TOKENS = 0;++// ---- The script -----------------------------------------------------------++/**+ * One scripted assistant reply. The blocks are emitted in the order a Claude response streams+ * them: thinking (closed by its signature), then text, then the tool calls.+ */+export interface ScriptedReply {+ text?: string;+ thinking?: { text: string; signature: string };+ toolCalls?: { id: string; name: string; args: Record<string, unknown> }[];+ /** Uncached input tokens this request reports (the compaction threshold reads this). */+ promptTokens?: number;+ /**+ * How the request ends: cleanly, with a transport drop after the text (the engine+ * reconnects), or hanging after the text until the caller's signal aborts it.+ */+ outcome?: "completed" | "retryable-after-text" | "abort-after-text";+}++// ---- What a recording holds -----------------------------------------------++/** One request as the provider client would have sent it. */+export interface RecordedRequest {+ index: number;+ /**+ * Which context issued the request (the recording model's `label`). A scenario that runs+ * several models — a compaction rotation, a subagent's child session — tags each one so a+ * report can tell the cache lines apart; a single-model scenario leaves it off.+ */+ label?: string;+ /** The full message list handed to the client (AgentHub's stateful history plus this turn). */+ messages: UniMessage[];+ /** The resolved UniConfig for this request. */+ config: UniConfig;+ /** The messages in the provider's own request shape. */+ wire: unknown[];+ /** The request config in the provider's own shape (tools, system, thinking, cache control). */+ wireConfig: Record<string, unknown>;+}++/** Extras a recording model carries beyond the script. */+export interface RecordingOptions {+ /** Context label stamped on every request this model records (see RecordedRequest.label). */+ label?: string;+ /**+ * Called with each request the moment it is issued. Several models running in one scenario+ * each keep their own `requests` array, so this is what puts their requests in one issue+ * order — the order a provider would have seen them in.+ */+ onRequest?: (request: RecordedRequest) => void;+}++interface StreamOptions {+ messages: UniMessage[];+ config: UniConfig;+ signal?: AbortSignal;+}++/** The AutoLLMClient surface these helpers use (private to GenerativeModel, public at runtime). */+interface AutoClientHandle {+ transformUniMessageToModelInput(messages: UniMessage[], signal?: AbortSignal): Promise<unknown[]>;+ transformUniConfigToModelConfig(config: UniConfig): Record<string, unknown>;+ getHistory(): UniMessage[];+ _client: { _streamingResponseInternal(options: StreamOptions): AsyncGenerator<UniEvent> };+}++const autoClientOf = (model: GenerativeModel): AutoClientHandle =>+ (model as unknown as { client: AutoClientHandle }).client;++const deepCopy = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;++// ---- Recording ------------------------------------------------------------++/**+ * A real `GenerativeModel` with its provider client's stream replaced by a script. Everything+ * else runs for real: the model builds the UniConfig, AgentHub merges the input into its+ * stateful history, and the recorded request is the output of the provider's own transforms.+ */+export function recordingModel(+ config: GenerativeModelConfig,+ script: ScriptedReply[],+ options: RecordingOptions = {},+): { model: GenerativeModel; requests: RecordedRequest[] } {+ const model = new GenerativeModel(config);+ const auto = autoClientOf(model);+ const requests: RecordedRequest[] = [];+ const pending = [...script];++ auto._client._streamingResponseInternal = async function* (+ streamOptions: StreamOptions,+ ): AsyncGenerator<UniEvent> {+ const index = requests.length;+ // Recorded before anything is yielded: AgentHub stamps `created_at` onto the message+ // objects and the harness hands the same objects to the next request.+ const request: RecordedRequest = {+ index,+ ...(options.label !== undefined ? { label: options.label } : {}),+ messages: deepCopy(streamOptions.messages),+ config: deepCopy(streamOptions.config),+ wire: deepCopy(await auto.transformUniMessageToModelInput(streamOptions.messages)),+ wireConfig: deepCopy(auto.transformUniConfigToModelConfig(streamOptions.config)),+ };+ requests.push(request);+ options.onRequest?.(request);+ const reply = pending.shift();+ if (!reply) throw new Error(`prompt-cache script exhausted at request ${index}`);+ yield* replyEvents(reply, streamOptions.signal);+ };++ return { model, requests };+}++/** The live client's committed history, in the provider's request shape. */+export async function wireHistoryOf(model: GenerativeModel): Promise<unknown[]> {+ const auto = autoClientOf(model);+ return deepCopy(await auto.transformUniMessageToModelInput(auto.getHistory()));+}++// ---- The scripted stream --------------------------------------------------++/** Resolves once the signal aborts (a scripted request that hangs until it is cut). */+function untilAborted(signal?: AbortSignal): Promise<void> {+ return new Promise<void>((resolve) => {+ if (!signal) return;+ if (signal.aborted) {+ resolve();+ return;+ }+ signal.addEventListener("abort", () => resolve(), { once: true });+ });+}++/**+ * The UniEvents one scripted reply streams, built the way the Claude client builds them: a+ * start event carrying the input usage, thinking deltas closed by a signature, text deltas,+ * each tool call as partial deltas followed by its complete item, and a stop event carrying+ * the finish reason and the response usage.+ */+async function* replyEvents(reply: ScriptedReply, signal?: AbortSignal): AsyncGenerator<UniEvent> {+ const promptTokens = reply.promptTokens ?? DEFAULT_PROMPT_TOKENS;+ if (signal?.aborted) return;+ yield {+ role: "assistant",+ event_type: "start",+ content_items: [],+ usage_metadata: {+ cached_tokens: SCRIPTED_CACHED_TOKENS,+ prompt_tokens: promptTokens,+ thoughts_tokens: null,+ response_tokens: null,+ },+ finish_reason: null,+ };++ if (reply.thinking) {+ if (signal?.aborted) return;+ yield delta([{ type: "thinking", thinking: reply.thinking.text }]);+ if (signal?.aborted) return;+ // The signature arrives as an empty delta and closes the block, as Claude's+ // signature_delta does.+ yield delta([+ { type: "thinking", thinking: "", fidelity: { signature: reply.thinking.signature } },+ ]);+ }++ if (reply.text) {+ if (signal?.aborted) return;+ yield delta([{ type: "text", text: reply.text }]);+ }++ if (reply.outcome === "retryable-after-text") {+ // A transport drop: no finish reason, nothing committed to AgentHub's history, and the+ // engine's reconnect ladder takes it (an unclassifiable error stays retryable).+ throw new Error("socket hang up");+ }+ if (reply.outcome === "abort-after-text") {+ await untilAborted(signal);+ return;+ }++ for (const call of reply.toolCalls ?? []) {+ if (signal?.aborted) return;+ yield {+ role: "assistant",+ event_type: "start",+ content_items: [+ { type: "partial_tool_call", name: call.name, arguments: "", tool_call_id: call.id },+ ],+ usage_metadata: null,+ finish_reason: null,+ };+ if (signal?.aborted) return;+ // Argument fragments carry no id, exactly as Claude's input_json_delta does; the+ // translator attributes them to the call that opened last.+ yield delta([+ {+ type: "partial_tool_call",+ name: "",+ arguments: JSON.stringify(call.args),+ tool_call_id: "",+ },+ ]);+ if (signal?.aborted) return;+ // The complete item at the block's stop: AgentHub keeps this one in the committed+ // message and drops the partials, while the harness translator emits the tool card from it.+ yield delta([+ { type: "tool_call", name: call.name, arguments: call.args, tool_call_id: call.id },+ ]);+ }++ if (signal?.aborted) return;+ yield {+ role: "assistant",+ event_type: "stop",+ content_items: [],+ usage_metadata: {+ cached_tokens: SCRIPTED_CACHED_TOKENS,+ prompt_tokens: promptTokens,+ thoughts_tokens: null,+ response_tokens: SCRIPTED_RESPONSE_TOKENS,+ },+ finish_reason: (reply.toolCalls?.length ?? 0) > 0 ? "tool_call" : "stop",+ };+}++const delta = (contentItems: UniEvent["content_items"]): UniEvent => ({+ role: "assistant",+ event_type: "delta",+ content_items: contentItems,+ usage_metadata: null,+ finish_reason: null,+});diff --git a/packages/core/test/helpers/prompt-cache/simulator.ts b/packages/core/test/helpers/prompt-cache/simulator.tsnew file mode 100644index 00000000..182514ec--- /dev/null+++ b/packages/core/test/helpers/prompt-cache/simulator.ts@@ -0,0 +1,480 @@+/**+ * The simulator: an Anthropic-shaped prompt cache, run over recorded requests.+ *+ * `diagnostics.ts` measures the harness's half — whether each request is a pure extension of the+ * one before it. This file models the provider's half, the part that decides whether a prefix+ * that *could* hit actually does, so a test can state a scenario's result in the numbers the+ * provider reports: `cache_read_input_tokens`, `cache_creation_input_tokens`, `input_tokens`. Its+ * only input is what `recording.ts` captured, and it calls back into `diagnostics.ts` to name the+ * divergence behind a miss. `fixtures.ts` wraps it in the assertion the Session suites share.+ *+ * The rules modelled, from Anthropic's prompt-caching documentation:+ *+ * - **Blocks.** A request is one ordered block list: the model id, a block per tool+ * definition, one virtual "speed" block holding the fast-mode parameters (`speed`,+ * `betas`), one system block, one virtual "parameters" block holding the remaining+ * prompt-affecting request parameters (`thinking`, `output_config`, `tool_choice`), then+ * every content block of every message in order. `max_tokens`, `stream` and `cache_control`+ * take part in none of it. That order is what reproduces the documented invalidation+ * hierarchy: a model switch invalidates everything — the cache is scoped to one model, and+ * no breakpoint can be placed in front of the model id — a tool change everything behind+ * the tools, a fast-mode toggle the system prompt and the messages but not the tools, a+ * system change the messages, and a thinking/effort or `tool_choice` change the messages+ * alone. That last row is the optimistic case: the documentation marks it model-specific,+ * and a model that renders the thinking configuration ahead of the tools and the system+ * prompt invalidates those tiers too.+ * - **Positions.** A run of consecutive `tool_use` blocks counts as one position, and so does+ * a run of consecutive `tool_result` blocks; every other block is a position of its own.+ * - **Writes happen only at a breakpoint.** A completed request writes one entry per+ * breakpoint it carries: the hash of the prefix ending at that block. Content sitting+ * behind a breakpoint is not separately addressable — a read finds entries prior requests+ * wrote, never a stable prefix nobody ever closed. AgentHub's Claude client sets exactly+ * one breakpoint, the automatic one at the last block (a top-level+ * `cache_control: ephemeral`), which is what `breakpoints: "automatic"` models and the+ * default. `breakpoints: "tools-system-automatic"` models the alternative Anthropic allows+ * (four breakpoints in all): explicit ones on the last tool block and on the system block,+ * plus the automatic one. That second policy is not what the harness sends today; it is+ * here so a test can measure what the extra breakpoints would recover.+ * - **Reads.** Every breakpoint the request carries does its own lookback: it hashes the+ * prefix ending at that breakpoint and, failing an exact match, walks back one position at+ * a time over at most {@link DEFAULT_LOOKBACK_POSITIONS} positions of its own — never from+ * the request's last position. The longest live match across the breakpoints is what the+ * request reads, and reading refreshes that entry.+ * - **TTL.** An entry expires {@link DEFAULT_TTL_MS} after it was last written or read; a+ * read refreshes it. The clock is injected, so a test can advance it and show an expiry.+ *+ * What it is not: a token counter (blocks are estimated at four characters per token, the ratio+ * the harness's own estimator uses for ASCII), a billing model, or a promise about any+ * particular provider deployment. It is a rule engine whose only inputs are the bytes the+ * harness put on the wire.+ */+import { createHash } from "node:crypto";+import { diagnoseCacheMiss, describeMissReason } from "./diagnostics.js";+import type { RecordedRequest } from "./recording.js";++/** Smallest prefix a provider will cache, in tokens. */+export const DEFAULT_MIN_CACHEABLE_TOKENS = 1024;+/** Lifetime of an ephemeral cache entry (five minutes, AgentHub's default). */+export const DEFAULT_TTL_MS = 5 * 60 * 1000;+/**+ * Positions checked per breakpoint. The documented wording is "up to 20 positions before the+ * breakpoint", which leaves the breakpoint's own position ambiguous; what is encoded here is the+ * conservative reading — the breakpoint counts as the first of the twenty, so nineteen appended+ * positions still reach the previous write and twenty do not. Nothing measured in these suites+ * sits near that boundary, so the off-by-one is a statement about the rule's precision rather+ * than about any scenario's result.+ */+const DEFAULT_LOOKBACK_POSITIONS = 20;+/** Characters per token, the ratio the harness's own estimator uses for ASCII. */+const CHARS_PER_TOKEN = 4;++/**+ * Prompt-affecting parameters rendered *ahead* of the system block, so that changing one keeps+ * the tool definitions and loses everything behind them. AgentHub sets exactly this pair for+ * fast mode.+ */+const SPEED_KEYS = ["speed", "betas"] as const;++/**+ * Prompt-affecting parameters rendered *after* the system block, in the order the virtual+ * parameters block renders them, so that changing one keeps the tools and the system prompt.+ * `max_tokens` is deliberately absent: it varies per request (the window-derived clamp) and is+ * not part of the cache key. So are `stream` and `cache_control`, which describe the transport+ * and the breakpoint rather than the prompt.+ */+const PARAMETER_KEYS = ["thinking", "output_config", "tool_choice"] as const;++/** What a block came from — the sections of the prefix, in the order they are sent. */+type CacheBlockKind = "model" | "tool" | "speed" | "system" | "parameters" | "message";++/** The blocks a breakpoint on the last tool block closes. */+const TOOL_TIER: CacheBlockKind[] = ["model", "tool"];+/** The blocks a breakpoint on the system block closes. */+const SYSTEM_TIER: CacheBlockKind[] = ["model", "tool", "speed", "system"];++/** One block of the prefix: the unit a hash, a token count and a position are taken over. */+interface CacheBlock {+ kind: CacheBlockKind;+ /** The block's canonical rendering: what both the hash and the token estimate are taken over. */+ text: string;+ /** Wire block type (`text` / `thinking` / `tool_use` / `tool_result`); message blocks only. */+ blockType?: string;+ /** Index of the wire message this block came from; message blocks only. */+ message?: number;+ tokens: number;+}++/** One request's usage, as Anthropic reports it, plus what it took to get there. */+export interface CacheUsage {+ /** Tokens served from the cache (the matched prefix). */+ cache_read_input_tokens: number;+ /** Tokens written to the cache (from the match point to the breakpoint). */+ cache_creation_input_tokens: number;+ /** Tokens processed without being cached (the remainder when no write happened). */+ input_tokens: number;+ /** `read / (read + creation + input)`; 0 for an empty prefix. */+ hitRatio: number;+ /** How many blocks of this request's prefix the read covered. */+ matchedBlocks: number;+ /** How many blocks this request's prefix holds. */+ totalBlocks: number;+ /** Whether this request's prefix was cached (false below the minimum). */+ wrote: boolean;+}++/**+ * Where a request's cache breakpoints sit. `"automatic"` is what AgentHub's Claude client+ * sends: one breakpoint, at the last block. `"tools-system-automatic"` adds the two explicit+ * breakpoints the API allows alongside it — on the last tool block and on the system block — so+ * a request whose messages moved can still read the fixed prefix back.+ */+type BreakpointPolicy = "automatic" | "tools-system-automatic";++interface PromptCacheSimOptions {+ /** Smallest cacheable prefix, in tokens (default {@link DEFAULT_MIN_CACHEABLE_TOKENS}). */+ minCacheableTokens?: number;+ /** Where the breakpoints sit (default `"automatic"`, what the harness sends today). */+ breakpoints?: BreakpointPolicy;+ /** The clock; injected so a test can advance it (default `Date.now`). */+ now?: () => number;+}++const json = (value: unknown): string => JSON.stringify(value ?? null);++const estimateTokens = (text: string): number => Math.ceil(text.length / CHARS_PER_TOKEN);++const roleOf = (message: unknown): string =>+ String((message as { role?: unknown } | undefined)?.role ?? "?");++function contentBlocksOf(message: unknown): unknown[] {+ const content = (message as { content?: unknown } | undefined)?.content;+ if (Array.isArray(content)) return content;+ return content === undefined ? [] : [content];+}++const blockTypeOf = (block: unknown): string | undefined => {+ const type = (block as { type?: unknown } | undefined)?.type;+ return typeof type === "string" ? type : undefined;+};++// ---- Reading a request as blocks and positions ----------------------------++/** The named request parameters, in a fixed order, absent keys omitted. */+function parameterView(+ wireConfig: Record<string, unknown>,+ keys: readonly string[],+): Record<string, unknown> {+ const view: Record<string, unknown> = {};+ for (const key of keys) {+ if (wireConfig[key] !== undefined) view[key] = wireConfig[key];+ }+ return view;+}++function makeBlock(+ kind: CacheBlockKind,+ text: string,+ extra: Partial<CacheBlock> = {},+): CacheBlock {+ return { kind, text, tokens: estimateTokens(text), ...extra };+}++/**+ * One request as the ordered block list the cache keys on: the model, the tools, the fast-mode+ * parameters, the system prompt, the remaining parameters, then every content block of every+ * message, each rendered with its message's role so an identical block under a different role+ * is a different block.+ */+function prefixBlocks(request: RecordedRequest): CacheBlock[] {+ const wireConfig = request.wireConfig;+ const blocks: CacheBlock[] = [];+ // Ahead of the tools: a prompt cache is scoped to one model, and a model switch is the one+ // invalidator no breakpoint can be placed in front of.+ blocks.push(makeBlock("model", `model:${json(wireConfig.model)}`));+ const tools = Array.isArray(wireConfig.tools) ? wireConfig.tools : [];+ for (const tool of tools) blocks.push(makeBlock("tool", `tool:${json(tool)}`));+ blocks.push(makeBlock("speed", `speed:${json(parameterView(wireConfig, SPEED_KEYS))}`));+ blocks.push(makeBlock("system", `system:${json(wireConfig.system)}`));+ blocks.push(+ makeBlock("parameters", `parameters:${json(parameterView(wireConfig, PARAMETER_KEYS))}`),+ );+ request.wire.forEach((message, index) => {+ const role = roleOf(message);+ for (const block of contentBlocksOf(message)) {+ const type = blockTypeOf(block);+ blocks.push(+ makeBlock("message", `message:${role}:${json(block)}`, {+ message: index,+ ...(type !== undefined ? { blockType: type } : {}),+ }),+ );+ }+ });+ return blocks;+}++/** Blocks that merge into their neighbour when consecutive (tool calls, tool results). */+const runKindOf = (block: CacheBlock): string | null =>+ block.blockType === "tool_use" || block.blockType === "tool_result" ? block.blockType : null;++/**+ * The end offsets (block counts) of every position, ascending; the last one is the automatic+ * breakpoint. A maximal run of consecutive `tool_use` or `tool_result` blocks contributes a+ * single offset, which is why a turn that calls twenty-five tools stays one position away from+ * the last one.+ */+function positionEnds(blocks: CacheBlock[]): number[] {+ const ends: number[] = [];+ for (let i = 0; i < blocks.length; i += 1) {+ const kind = runKindOf(blocks[i]!);+ const next = blocks[i + 1];+ if (kind !== null && next !== undefined && runKindOf(next) === kind) continue;+ ends.push(i + 1);+ }+ return ends;+}++/** How many positions a request's prefix holds. */+export const positionCount = (request: RecordedRequest): number =>+ positionEnds(prefixBlocks(request)).length;++// ---- Token counts a test states its bounds in -----------------------------++const sumTokens = (blocks: CacheBlock[]): number =>+ blocks.reduce((total, block) => total + block.tokens, 0);++const tierTokens = (request: RecordedRequest, kinds: CacheBlockKind[]): number =>+ sumTokens(prefixBlocks(request).filter((block) => kinds.includes(block.kind)));++/** Every token of a request's prefix — what a full hit would read. */+export const prefixTokens = (request: RecordedRequest): number => sumTokens(prefixBlocks(request));++/** The model id and the tool definitions — what a breakpoint on the last tool block closes. */+export const toolsTokens = (request: RecordedRequest): number => tierTokens(request, TOOL_TIER);++/** Everything through the system prompt — what a breakpoint on the system block closes. */+export const toolsAndSystemTokens = (request: RecordedRequest): number =>+ tierTokens(request, SYSTEM_TIER);++/** Every non-message block — the fixed prefix a fresh context reopens on. */+export const fixedPrefixTokens = (request: RecordedRequest): number =>+ sumTokens(prefixBlocks(request).filter((block) => block.kind !== "message"));++/**+ * Everything ahead of the request's last user message: the bound a divergence confined to that+ * message (an interruption's carry-over, a reconnect's retried input) may not cross.+ */+export function tokensBeforeLastUserMessage(request: RecordedRequest): number {+ const last = request.wire.map(roleOf).lastIndexOf("user");+ if (last < 0) return prefixTokens(request);+ return sumTokens(+ prefixBlocks(request).filter((block) => block.message === undefined || block.message < last),+ );+}++// ---- The cache ------------------------------------------------------------++interface PendingWrite {+ /** Cumulative prefix hashes, index `k` covering the first `k` blocks. */+ hashes: string[];+ /** Cumulative token sums, index `k` covering the first `k` blocks. */+ sums: number[];+ /** Prefix lengths this request's breakpoints close, in blocks. */+ offsets: number[];+}++/**+ * The provider's cache, as a rule engine over recorded requests. One instance is one provider+ * for one test: every request of the scenario — a subagent's child session included — goes+ * through the same one, because a provider does not keep a cache per Session.+ */+export class PromptCacheSim {+ private readonly minCacheableTokens: number;+ private readonly breakpoints: BreakpointPolicy;+ private readonly now: () => number;+ /** Live entries: cumulative prefix hash -> expiry timestamp. */+ private readonly entries = new Map<string, number>();+ /** Writes staged by `begin`, readable only once `complete` lands them. */+ private readonly pending = new Map<RecordedRequest, PendingWrite>();++ constructor(options: PromptCacheSimOptions = {}) {+ this.minCacheableTokens = options.minCacheableTokens ?? DEFAULT_MIN_CACHEABLE_TOKENS;+ this.breakpoints = options.breakpoints ?? "automatic";+ this.now = options.now ?? (() => Date.now());+ }++ /**+ * The read side of one request: what it serves from the cache, and what it will write. The+ * write is staged, not landed — an entry becomes readable only when the request completes,+ * so a second request issued while this one is still streaming cannot read it.+ */+ begin(request: RecordedRequest): CacheUsage {+ const blocks = prefixBlocks(request);+ const ends = positionEnds(blocks);+ const hashes = cumulativeHashes(blocks);+ const sums = cumulativeTokens(blocks);+ const total = sums[blocks.length]!;+ const offsets = this.breakpointOffsets(blocks);++ const matchedBlocks = this.lookup(hashes, ends, offsets);+ const read = sums[matchedBlocks]!;+ const wrote = total >= this.minCacheableTokens;+ this.pending.set(request, { hashes, sums, offsets });++ const remainder = total - read;+ const creation = wrote ? remainder : 0;+ const input = wrote ? 0 : remainder;+ const accounted = read + creation + input;+ return {+ cache_read_input_tokens: read,+ cache_creation_input_tokens: creation,+ input_tokens: input,+ hitRatio: accounted === 0 ? 0 : read / accounted,+ matchedBlocks,+ totalBlocks: blocks.length,+ wrote,+ };+ }++ /** Lands the writes `begin` staged: from here on this request's breakpoints are readable. */+ complete(request: RecordedRequest): void {+ const staged = this.pending.get(request);+ if (!staged) throw new Error("PromptCacheSim.complete: the request was never begun");+ this.pending.delete(request);+ const expiry = this.now() + DEFAULT_TTL_MS;+ for (const offset of staged.offsets) {+ if (staged.sums[offset]! < this.minCacheableTokens) continue;+ this.entries.set(staged.hashes[offset]!, expiry);+ }+ }++ /** `begin` then `complete`: one request that ran to its end before the next one started. */+ request(request: RecordedRequest): CacheUsage {+ const usage = this.begin(request);+ this.complete(request);+ return usage;+ }++ /**+ * Prefix lengths this request's breakpoints close: the automatic one at the last block+ * always, and under the wider policy the last tool block and the system block as well (both+ * are positions of their own, so both are addressable boundaries).+ */+ private breakpointOffsets(blocks: CacheBlock[]): number[] {+ const offsets = [blocks.length];+ if (this.breakpoints !== "tools-system-automatic") return offsets;+ const lastTool = blocks.findLastIndex((block) => block.kind === "tool");+ const system = blocks.findIndex((block) => block.kind === "system");+ if (lastTool >= 0) offsets.push(lastTool + 1);+ if (system >= 0) offsets.push(system + 1);+ return offsets;+ }++ /**+ * The longest live prefix this request can read, as a block count. Every breakpoint gets its+ * own lookback window, anchored at its own position rather than at the request's last one, so+ * an explicit breakpoint on the system block still reads at distance zero however many message+ * positions follow it. Reading refreshes the entry that won.+ */+ private lookup(hashes: string[], ends: number[], offsets: number[]): number {+ const now = this.now();+ let best = 0;+ for (const offset of offsets) {+ const anchor = ends.indexOf(offset);+ if (anchor < 0) continue;+ const first = Math.max(0, anchor + 1 - DEFAULT_LOOKBACK_POSITIONS);+ for (let i = anchor; i >= first; i -= 1) {+ const end = ends[i]!;+ // Positions descend, so nothing left in this window can beat what another already won.+ if (end <= best) break;+ const expiry = this.entries.get(hashes[end]!);+ if (expiry === undefined) continue;+ if (expiry <= now) {+ this.entries.delete(hashes[end]!);+ continue;+ }+ best = end;+ break;+ }+ }+ if (best > 0) this.entries.set(hashes[best]!, now + DEFAULT_TTL_MS);+ return best;+ }+}++/** Cumulative prefix hashes: index `k` covers the first `k` blocks (index 0 the empty prefix). */+function cumulativeHashes(blocks: CacheBlock[]): string[] {+ const hashes: string[] = [createHash("sha256").update("").digest("hex")];+ for (const block of blocks) {+ const previous = hashes[hashes.length - 1]!;+ hashes.push(createHash("sha256").update(`${previous} ${block.text}`).digest("hex"));+ }+ return hashes;+}++/** Cumulative token sums: index `k` covers the first `k` blocks. */+function cumulativeTokens(blocks: CacheBlock[]): number[] {+ const sums = [0];+ for (const block of blocks) sums.push(sums[sums.length - 1]! + block.tokens);+ return sums;+}++// ---- Reporting ------------------------------------------------------------++/**+ * Why the prefix moved between two requests, in the vocabulary a provider's cache diagnostics+ * use. Reuses the request-assembly diagnosis: a miss the simulator reports is either a+ * divergence this names, or none at all — an expiry, a lookback overrun, a reopened context.+ */+export function explainMiss(prev: RecordedRequest, next: RecordedRequest): string {+ const reason = diagnoseCacheMiss(prev, next);+ return reason.type === "none" ? "no divergence" : describeMissReason(reason);+}++/** The request before `index` issued by the same context, or -1 when there is none. */+export function previousInContext(requests: RecordedRequest[], index: number): number {+ for (let i = index - 1; i >= 0; i -= 1) {+ if (requests[i]!.label === requests[index]!.label) return i;+ }+ return -1;+}++/**+ * A per-request table for a failing assertion's message: what each request read, created and+ * paid for in full, and — when the read fell short of the previous request's whole prefix —+ * why. Requests are in issue order; "previous" means the previous request of the same context.+ */+export function formatCacheReport(requests: RecordedRequest[], usages: CacheUsage[]): string {+ const rows = requests.map((request, i) => {+ const usage = usages[i];+ if (!usage) return [`#${i}`, request.label ?? "-", "(no usage recorded)", "", ""];+ const previous = previousInContext(requests, i);+ const percent = `${(usage.hitRatio * 100).toFixed(1)}%`;+ let note: string;+ if (previous < 0) {+ note = "first request of this context";+ } else {+ const expected = prefixTokens(requests[previous]!);+ note =+ usage.cache_read_input_tokens >= expected+ ? `full hit on #${previous}`+ : `short of #${previous} by ${expected - usage.cache_read_input_tokens} tokens: ` ++ explainMiss(requests[previous]!, request);+ }+ return [+ `#${i}`,+ request.label ?? "-",+ `read=${usage.cache_read_input_tokens}`,+ `creation=${usage.cache_creation_input_tokens} input=${usage.input_tokens} hit=${percent}`,+ note,+ ];+ });+ const widths = [0, 1, 2, 3].map((column) =>+ Math.max(...rows.map((row) => (row[column] ?? "").length)),+ );+ const lines = rows.map((row) =>+ row.map((cell, column) => (column < 4 ? cell.padEnd(widths[column]!) : cell)).join(" "),+ );+ const heading = "prompt-cache report (tokens; previous = the same context's previous request):";+ return [heading, ...lines].join("\n");+}diff --git a/packages/core/test/prompt-cache-invariants.test.ts b/packages/core/test/prompt-cache-invariants.test.tsnew file mode 100644index 00000000..99b72e0e--- /dev/null+++ b/packages/core/test/prompt-cache-invariants.test.ts@@ -0,0 +1,281 @@+/**+ * The harness's half of the prompt cache: every request is assembled as an extension of the last.+ *+ * A provider serves a cached prefix only when the request repeats the previous one byte for byte+ * from the front — tools, then the system prompt, then the messages. Everything the harness does+ * between two requests — running a turn, delivering a steering message, moving the thinking+ * level, compacting, reconnecting, resuming from a Trace — therefore has to leave the request an+ * extension of the one before it. Each case here drives a real `ContextEngine` over a real+ * `GenerativeModel` whose provider stream is scripted, and diagnoses each consecutive pair of+ * requests on the wire shape the client would have sent.+ *+ * These are assertions about bytes. Whether a prefix that could hit actually did — cache+ * lifetime, breakpoint lookback, minimum cacheable size — is `prompt-cache-lifecycle.test.ts`,+ * which puts the same kind of recording through the simulator.+ */+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { sessionMeta, userText } from "../src/omnimessage/index.js";+import type { ApproveFn } from "../src/interfaces/index.js";+import { ContextEngine } from "../src/engine/context-engine.js";+import { Writer, readTrace, resumeTrace } from "../src/trace/index.js";+import {+ COMPACTION_PROMPT,+ META,+ NON_PREFIX_CONFIG_KEYS,+ SESSION_ID,+ allowAll,+ blockTypes,+ collect,+ compactionSettings,+ diagnoseCacheMiss,+ diagnoseSeries,+ fakeEnvironment,+ formatDiagnostics,+ modelConfig,+ recordingModel,+ toolTurn,+ wireHistoryOf,+ wireMessage,+} from "./helpers/prompt-cache/index.js";+import type {+ CacheMissReason,+ RecordedRequest,+ ScriptedReply,+} from "./helpers/prompt-cache/index.js";++// ---------------------------------------------------------------------------+// Fixtures of this suite's own+// ---------------------------------------------------------------------------++const metaMessage = sessionMeta(META);++/** Everything in a request's config that takes part in the cached prefix. */+function configFingerprint(request: RecordedRequest): string {+ const copy: Record<string, unknown> = { ...request.wireConfig };+ for (const key of NON_PREFIX_CONFIG_KEYS) delete copy[key];+ return JSON.stringify(copy);+}++const effortOf = (request: RecordedRequest): string | undefined =>+ (request.wireConfig.output_config as { effort?: string } | undefined)?.effort;++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("prompt-cache invariants of request assembly", () => {+ let traces: string;++ beforeEach(async () => {+ traces = await mkdtemp(join(tmpdir(), "penguin-prompt-cache-"));+ });++ afterEach(async () => {+ await rm(traces, { recursive: true, force: true });+ });++ it("every request of a session extends the previous one on the wire", async () => {+ const { model, requests } = recordingModel(modelConfig(), [+ toolTurn(),+ { text: "The entry point re-exports the public API." },+ { text: "Nothing else changed since." },+ ]);+ const engine = new ContextEngine({ llm: model, environment: fakeEnvironment });++ await collect(engine.run([userText("what does the entry point do?")], { approve: allowAll }));+ await collect(engine.run([userText("anything else worth knowing?")], { approve: allowAll }));++ expect(requests).toHaveLength(3);+ const reasons = diagnoseSeries(requests);+ expect(reasons, formatDiagnostics(requests, reasons)).toEqual([+ { type: "none" },+ { type: "none" },+ ]);+ // The prefix grows, it never rewrites: each request carries the previous one plus a turn.+ expect(requests.map((r) => r.wire.length)).toEqual([1, 3, 5]);+ // Tools, system prompt and every other prompt-affecting parameter are one fixed prefix.+ expect(new Set(requests.map(configFingerprint)).size).toBe(1);+ });++ it("steering delivered mid-task rides the same user turn as the tool result", async () => {+ let engine: ContextEngine | null = null;+ const { model, requests } = recordingModel(modelConfig(), [+ toolTurn(),+ { text: "Read both, here is the summary." },+ ]);+ // Steering from the approval callback lands deterministically: the tool_call has streamed,+ // the tool has not run yet, so the steer is queued before the next request is assembled.+ const approve: ApproveFn = async () => {+ expect(engine!.steer([userText("also check the tests directory")])).toBe(true);+ return "allow";+ };+ engine = new ContextEngine({ llm: model, environment: fakeEnvironment });++ await collect(engine.run([userText("read the entry point")], { approve }));++ expect(requests).toHaveLength(2);+ const reasons = diagnoseSeries(requests);+ expect(reasons, formatDiagnostics(requests, reasons)).toEqual([{ type: "none" }]);+ // One appended user turn holding the tool result and the steering text, not two.+ const appended = wireMessage(requests[1]!, -1);+ expect(appended.role).toBe("user");+ expect(blockTypes(appended)).toEqual(["tool_result", "text"]);+ expect(appended.content[1]!.text).toContain("[user_steering]");+ });++ it("moving the thinking level invalidates the prompt cache once and then holds", async () => {+ const first = recordingModel(modelConfig(), [+ { text: "First answer.", promptTokens: 20 },+ // Over the compaction threshold at the task's wrap-up round.+ { text: "Second answer.", promptTokens: 150 },+ { text: "[summary]the distilled summary[/summary]", promptTokens: 160 },+ ]);+ const second = recordingModel(modelConfig(), [{ text: "Third answer.", promptTokens: 20 }]);+ const engine = new ContextEngine({+ llm: first.model,+ environment: fakeEnvironment,+ compaction: compactionSettings(),+ openNextContext: () => ({ llm: second.model }),+ });++ await collect(engine.run([userText("task one")], { approve: allowAll }));+ engine.setThinkingLevel("high");+ await collect(engine.run([userText("task two")], { approve: allowAll }));+ await collect(engine.run([userText("task three")], { approve: allowAll }));++ expect(first.requests).toHaveLength(3);+ expect(second.requests).toHaveLength(1);+ const reasons = diagnoseSeries(first.requests);+ const report = formatDiagnostics(first.requests, reasons);+ // Exactly one invalidation, at the first request after the move, and nothing after it.+ expect(+ reasons.map((reason) => reason.type),+ report,+ ).toEqual(["parameters_changed", "none"]);+ const moved = reasons[0] as Extract<CacheMissReason, { type: "parameters_changed" }>;+ const offLevel = moved.keys.filter((key) => key !== "thinking" && key !== "output_config");+ expect(offLevel, report).toEqual([]);+ // The compaction request runs on the moved level too, not the level the context opened at.+ expect(configFingerprint(first.requests[2]!)).toBe(configFingerprint(first.requests[1]!));+ // The pin is a per-request parameter, so the context compaction opens carries it as well.+ const efforts = [...first.requests, ...second.requests].map(effortOf);+ expect(efforts, report).toEqual([undefined, "high", "high", "high"]);+ });++ // A dropped attempt is never committed to history, and the reconnect ladder re-sends the+ // turn with a `[turn_retried]` user text carrying what the attempt already produced, so the+ // model continues from it instead of re-running tools. Seen from the provider, every message+ // before that turn's input is byte-identical — tools, system prompt and the whole history+ // still hit — and only the retried turn's own input is read afresh, which is the same tail a+ // normal turn re-reads anyway (a cache entry is written at each request's end; the next+ // request's new blocks are never cached yet). The invariant is therefore not "identical+ // resend" but "the divergence never moves earlier than the retried turn's input".+ it("a reconnect changes nothing before the retried turn's input, and that input only grows", async () => {+ const { model, requests } = recordingModel(modelConfig(), [+ { text: "Starting on it", outcome: "retryable-after-text" },+ { text: "Recovered and finished." },+ ]);+ const engine = new ContextEngine({+ llm: model,+ environment: fakeEnvironment,+ reconnectBackoffMs: 1,+ });++ await collect(engine.run([userText("answer the question")], { approve: allowAll }));++ expect(requests).toHaveLength(2);+ const [first, retry] = requests as [RecordedRequest, RecordedRequest];+ const reason = diagnoseCacheMiss(first, retry);+ const report = formatDiagnostics(requests, [reason]);+ expect(reason.type, report).toBe("messages_changed");+ if (reason.type !== "messages_changed") return;+ // The divergence is the retried turn's input itself — the last message of the first+ // request — never anything before it.+ expect(reason.index, report).toBe(first.wire.length - 1);+ expect(retry.wire.slice(0, reason.index)).toEqual(first.wire.slice(0, reason.index));+ // And that input only grows: the original user text still leads it, the retry note follows.+ const before = first.wire[reason.index] as { content: unknown[] };+ const after = retry.wire[reason.index] as { content: unknown[] };+ expect(after.content.length).toBeGreaterThan(before.content.length);+ expect(after.content.slice(0, before.content.length)).toEqual(before.content);+ });++ it("a resumed session replays the live history byte for byte", async () => {+ const script: ScriptedReply[] = [+ toolTurn({+ thinking: { text: "Read the README first.", signature: "sig-resume-1" },+ toolCalls: [{ id: "call_1", name: "read_file", args: { path: "README.md" } }],+ }),+ { text: "The README explains the layout." },+ ];+ const live = recordingModel(modelConfig(), script);+ const trace = new Writer({ tracesDir: traces, sessionId: SESSION_ID });+ const engine = new ContextEngine({+ llm: live.model,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ });+ await collect(engine.run([userText("read the README")], { approve: allowAll }));++ const resumed = resumeTrace(await readTrace(trace.currentPath()));+ const next = recordingModel(modelConfig(), [{ text: "Here are the packages." }]);+ next.model.setHistory(resumed.history);+ const resumedEngine = new ContextEngine({ llm: next.model, environment: fakeEnvironment });+ await collect(resumedEngine.run([userText("now list the packages")], { approve: allowAll }));++ const liveHistory = await wireHistoryOf(live.model);+ expect(liveHistory).toHaveLength(4);+ const first = next.requests[0]!;+ expect(first.wire).toHaveLength(liveHistory.length + 1);+ expect(first.wire.slice(0, liveHistory.length)).toEqual(liveHistory);+ // Stated as the diagnosis: the replayed history is a cache-clean prefix of the first+ // request the resumed session sends, under the same tools, system prompt and parameters.+ const replayed: RecordedRequest = {+ index: -1,+ messages: [],+ config: live.requests[1]!.config,+ wire: liveHistory,+ wireConfig: live.requests[1]!.wireConfig,+ };+ expect(diagnoseCacheMiss(replayed, first)).toEqual({ type: "none" });+ // The blocks a replay is most likely to lose: the thinking signature and the tool pairing.+ const assistant = wireMessage(first, 1);+ expect(blockTypes(assistant)).toEqual(["thinking", "tool_use"]);+ expect(assistant.content[0]!.signature).toBe("sig-resume-1");+ expect(blockTypes(wireMessage(first, 2))).toEqual(["tool_result"]);+ });++ it("the compaction request extends the turn it follows", async () => {+ const first = recordingModel(modelConfig(), [+ // Mid-task: the tool round's usage is already over the threshold.+ toolTurn({+ toolCalls: [{ id: "call_1", name: "exec_command", args: { cmd: "pnpm -r build" } }],+ promptTokens: 150,+ }),+ { text: "[summary]the distilled summary[/summary]", promptTokens: 160 },+ ]);+ const second = recordingModel(modelConfig(), [{ text: "Carried on from the summary." }]);+ const engine = new ContextEngine({+ llm: first.model,+ environment: fakeEnvironment,+ compaction: compactionSettings(),+ openNextContext: () => ({ llm: second.model }),+ });++ await collect(engine.run([userText("build everything")], { approve: allowAll }));++ expect(first.requests).toHaveLength(2);+ const reasons = diagnoseSeries(first.requests);+ expect(reasons, formatDiagnostics(first.requests, reasons)).toEqual([{ type: "none" }]);+ // One appended user turn: the pending tool outputs, then the compaction prompt.+ const appended = wireMessage(first.requests[1]!, -1);+ expect(appended.role).toBe("user");+ expect(blockTypes(appended)).toEqual(["tool_result", "text"]);+ expect(appended.content[1]!.text).toBe(COMPACTION_PROMPT);+ expect(configFingerprint(first.requests[1]!)).toBe(configFingerprint(first.requests[0]!));+ });+});diff --git a/packages/core/test/prompt-cache-lifecycle.test.ts b/packages/core/test/prompt-cache-lifecycle.test.tsnew file mode 100644index 00000000..16c61fcf--- /dev/null+++ b/packages/core/test/prompt-cache-lifecycle.test.ts@@ -0,0 +1,613 @@+/**+ * The prompt cache across a Session's lifecycle, measured through the simulator.+ *+ * `prompt-cache-invariants.test.ts` asks whether the harness assembles each request as an+ * extension of the one before it. This suite asks the question a bill answers: with the+ * provider's own rules applied — the automatic breakpoint, the minimum cacheable prefix, the+ * position lookback, the five-minute TTL — does the conversation keep hitting the cache while it+ * is interrupted, backgrounded, delegated, scheduled, resumed, retuned and compacted?+ *+ * Each scenario drives a real `Session` over a real `GenerativeModel` whose provider stream is+ * scripted, feeds every recorded request to one `PromptCacheSim` in the order it was issued (the+ * simulator IS the provider for the scenario, child sessions and reopened contexts included), and+ * asserts through `expectHits` that each request reads back the whole prefix of the previous+ * request of its context. Where that cannot hold by design, the index is named in `allowed` with+ * the reason and the loss is bounded explicitly.+ *+ * The agent, the fake collaborators and `expectHits` itself live in `helpers/prompt-cache`; what+ * stays here is the scaffolding each scenario needs and the scenarios themselves.+ */+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { Environment } from "../src/environment/index.js";+import { Session } from "../src/index.js";+import { buildScheduledMessage, userText } from "../src/omnimessage/index.js";+import type { OmniMessage } from "../src/omnimessage/index.js";+import { Writer, readTrace, resumeTrace } from "../src/trace/index.js";+import type { CompactionSettings, TraceSink } from "../src/engine/context-engine.js";+import { DETACHED_TOOL_NOTE_PREFIX } from "../src/interfaces/index.js";+import type {+ EnvironmentInterface,+ LLMInterface,+ RunCutoff,+ SubagentHandle,+ SubagentRunner,+ ToolConfig,+ ToolDefinitionConfig,+ ToolDetachResult,+} from "../src/interfaces/index.js";+import {+ CHILD_SESSION_ID,+ MAIN,+ META,+ SESSION_ID,+ allowAll,+ blockTypes,+ collect,+ compactionSettings,+ expectHits,+ explainMiss,+ fakeEnvironment,+ fakeEnvironmentWith,+ formatCacheReport,+ modelConfig,+ ordering,+ positionCount,+ prefixTokens,+ recordingModel,+ replay,+ tokensBeforeLastUserMessage,+ toolTurn,+ wireMessage,+} from "./helpers/prompt-cache/index.js";+import type { RecordedRequest } from "./helpers/prompt-cache/index.js";++// ---------------------------------------------------------------------------+// Scaffolding each scenario needs+// ---------------------------------------------------------------------------++interface SessionSpec {+ llm: LLMInterface;+ environment: EnvironmentInterface;+ sessionId?: string;+ trace?: TraceSink;+ compaction?: CompactionSettings;+ openNextContext?: ConstructorParameters<typeof Session>[0]["openNextContext"];+ initialEngineState?: ConstructorParameters<typeof Session>[0]["initialEngineState"];+ metaAlreadyWritten?: boolean;+}++function makeSession(spec: SessionSpec): Session {+ const session = new Session({+ meta: { ...META, ...(spec.sessionId ? { session_id: spec.sessionId } : {}) },+ bootstrap: async () => ({ llm: spec.llm }),+ environment: spec.environment,+ imagesDir: "/tmp/penguin-prompt-cache/scratchpad",+ modelHasVision: true,+ ...(spec.trace ? { trace: spec.trace } : {}),+ ...(spec.compaction ? { compaction: spec.compaction } : {}),+ ...(spec.openNextContext ? { openNextContext: spec.openNextContext } : {}),+ ...(spec.initialEngineState ? { initialEngineState: spec.initialEngineState } : {}),+ ...(spec.metaAlreadyWritten ? { metaAlreadyWritten: true } : {}),+ });+ cleanups.push(() => session.dispose());+ return session;+}++const cleanups: Array<() => Promise<void> | void> = [];+afterEach(async () => {+ while (cleanups.length) await cleanups.pop()!();+});++function toolDef(name: string): ToolDefinitionConfig {+ return { name, description: `${name} for the prompt-cache scenarios`, permission: "rw" };+}++const commandToolConfig = (names: string[]): ToolConfig => ({+ customTools: names.map(toolDef),+ mcpServers: [],+});++/** A real Environment over a scratch workspace, disposed after the test. */+async function makeEnvironment(names: string[], services?: { subagentRunner: SubagentRunner }) {+ const dir = await mkdtemp(path.join(tmpdir(), "penguin-prompt-cache-"));+ const environment = new Environment({+ workspaceDir: dir,+ toolConfig: commandToolConfig(names),+ ...(services ? { services } : {}),+ });+ cleanups.push(async () => {+ environment.dispose();+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ });+ return { environment, dir };+}++/**+ * Waits until the predicate holds (real process exits, real background reports). The deadline+ * sits under this package's 5s test timeout, so a predicate that never holds fails here with its+ * own message rather than as an anonymous test timeout.+ */+async function waitFor(predicate: () => boolean): Promise<void> {+ await vi.waitFor(+ () => {+ if (!predicate()) throw new Error("condition not met yet");+ },+ { timeout: 4000, interval: 20 },+ );+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("the prompt cache across a Session's lifecycle", () => {+ it("an ordinary conversation hits the prompt cache on every request after the first", async () => {+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig(),+ [+ toolTurn(),+ { text: "The entry point re-exports the public API." },+ { text: "Nothing else has changed since." },+ ],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment: fakeEnvironment });++ await collect(session.run([userText("what does the entry point do?")], { approve: allowAll }));+ await collect(session.run([userText("anything else worth knowing?")], { approve: allowAll }));++ expect(order).toHaveLength(3);+ expectHits(order, replay(order));+ });++ it("an interrupted turn still hits the prompt cache up to its last user message", async () => {+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig(),+ [+ toolTurn(),+ { text: "The entry point re-exports the public API." },+ { text: "Starting on the refactor", outcome: "abort-after-text" },+ { text: "Picking up from where that stopped." },+ ],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment: fakeEnvironment });++ await collect(session.run([userText("what does the entry point do?")], { approve: allowAll }));++ // Interrupt once the model's text is on the stream, so the aborted turn has output to fold.+ const controller = new AbortController();+ for await (const msg of session.run([userText("now refactor it")], {+ approve: allowAll,+ signal: controller.signal,+ })) {+ const payload = msg.payload as { type?: string; event_type?: string };+ if (payload.type === "partial_text" && payload.event_type === "delta") controller.abort();+ }+ await collect(session.run([userText("never mind, summarize instead")], { approve: allowAll }));++ expect(order).toHaveLength(4);+ const usages = replay(order);+ const reason =+ "the interrupted turn is folded into a [turn_aborted] carry-over, so the last user " ++ "message is rewritten and the interrupted request's own entry is unreachable";+ expectHits(order, usages, new Map([[3, reason]]));+ const report = formatCacheReport(order, usages);++ // The harness's half: the flattened carry-over and the new prompt ride one user message,+ // and the divergence never reaches earlier than that message.+ const folded = wireMessage(order[3]!, -1);+ expect(folded.role, report).toBe("user");+ expect(blockTypes(folded), report).toEqual(["text", "text"]);+ expect(folded.content[0]!.text, report).toContain("[turn_aborted]");+ expect(tokensBeforeLastUserMessage(order[3]!), report).toBe(+ tokensBeforeLastUserMessage(order[2]!),+ );+ // The provider's half: the only entry the interrupted request wrote ends at its own last+ // block, which is the block that was rewritten — so the read falls back to the breakpoint+ // the request before it closed. Nothing earlier than that is lost.+ expect(usages[3]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));+ expect(usages[3]!.cache_read_input_tokens, report).toBeLessThan(+ tokensBeforeLastUserMessage(order[3]!),+ );+ });++ it("a background command's completion notice still hits the prompt cache", async () => {+ const { environment } = await makeEnvironment(["exec_command", "input_command"]);+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig({ tools: await environment.listTools() }),+ [+ {+ toolCalls: [+ {+ id: "call_bg",+ name: "exec_command",+ args: { cmd: "sleep 0.4; printf 'build ok'", run_in_background: true },+ },+ ],+ },+ { text: "Started it; I will report when it settles." },+ { text: "The build finished cleanly." },+ ],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment });++ await collect(session.run([userText("build it in the background")], { approve: allowAll }));+ await waitFor(() => session.hasPendingBackgroundNotices());+ const notices = session.takeBackgroundNotices();+ expect(notices).toHaveLength(1);+ await collect(session.run(notices, { approve: allowAll }));++ expect(order).toHaveLength(3);+ const usages = replay(order);+ expectHits(order, usages);+ const report = formatCacheReport(order, usages);+ const carried = wireMessage(order[2]!, -1);+ expect(carried.content[0]!.text, report).toContain("[background_task_done]");+ expect(usages[2]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));+ });++ it("a call the user moves to the background still hits the prompt cache", async () => {+ const { environment } = await makeEnvironment(["exec_command", "input_command"]);+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig({ tools: await environment.listTools() }),+ [+ {+ toolCalls: [+ {+ id: "call_detach",+ name: "exec_command",+ // A yield window far longer than the test: the promotion can only be the detach.+ args: { cmd: "printf 'listening\\n'; sleep 30", yield_time_ms: 60000 },+ },+ ],+ },+ { text: "It is still running; I left it in the background." },+ ],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment });++ let detach: ToolDetachResult | null = null;+ let seen = "";+ for await (const msg of session.run([userText("start the dev server")], {+ approve: allowAll,+ })) {+ const payload = msg.payload as { type?: string; output?: string };+ if (payload.type === "partial_tool_call_output") seen += payload.output ?? "";+ if (detach === null && seen.includes("listening")) {+ detach = session.detachToolCall("call_detach");+ }+ }+ expect(detach).toBe("detached");++ expect(order).toHaveLength(2);+ const usages = replay(order);+ expectHits(order, usages);+ const report = formatCacheReport(order, usages);+ const result = wireMessage(order[1]!, -1);+ expect(blockTypes(result), report).toEqual(["tool_result"]);+ expect(JSON.stringify(result.content), report).toContain(DETACHED_TOOL_NOTE_PREFIX);+ expect(usages[1]!.cache_read_input_tokens, report).toBe(prefixTokens(order[0]!));+ });++ it("a turn that calls three tools at once still hits the prompt cache", async () => {+ const { environment } = await makeEnvironment(["exec_command", "input_command"]);+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig({ tools: await environment.listTools() }),+ [+ {+ toolCalls: [+ { id: "call_a", name: "exec_command", args: { cmd: "printf alpha" } },+ { id: "call_b", name: "exec_command", args: { cmd: "printf beta" } },+ { id: "call_c", name: "exec_command", args: { cmd: "printf gamma" } },+ ],+ },+ { text: "All three came back." },+ ],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment });++ await collect(session.run([userText("check all three")], { approve: allowAll }));++ expect(order).toHaveLength(2);+ const usages = replay(order);+ expectHits(order, usages);+ const report = formatCacheReport(order, usages);+ // Three tool_use blocks are one position and three tool_result blocks another, so a wide+ // parallel round costs two of the twenty positions the lookback has, not six.+ expect(blockTypes(wireMessage(order[1]!, 1)), report).toEqual([+ "tool_use",+ "tool_use",+ "tool_use",+ ]);+ expect(blockTypes(wireMessage(order[1]!, 2)), report).toEqual([+ "tool_result",+ "tool_result",+ "tool_result",+ ]);+ expect(positionCount(order[1]!) - positionCount(order[0]!), report).toBe(2);+ });++ it("a subagent leaves its parent's prompt cache intact, and reads 0 because it opens its own line", async () => {+ const { order, onRequest } = ordering();+ // The child Session is built from the parent Environment's own toolset, so the runner+ // reads it at spawn time rather than at construction.+ let childSession: Session | null = null;+ const { environment } = await makeEnvironment(["exec_command", "read_file", "run_subagent"], {+ subagentRunner: childRunnerFor(() => childSession),+ });+ const tools = await environment.listTools();+ const child = recordingModel(+ modelConfig({ tools }),+ [+ toolTurn({+ thinking: { text: "Start from the test directory.", signature: "sig-child-1" },+ toolCalls: [{ id: "call_child", name: "read_file", args: { path: "test/README.md" } }],+ }),+ { text: "The tests are grouped by package." },+ ],+ { label: "child", onRequest },+ );+ childSession = makeSession({+ llm: child.model,+ environment: fakeEnvironmentWith(tools),+ sessionId: CHILD_SESSION_ID,+ });+ const parent = recordingModel(+ modelConfig({ tools }),+ [+ {+ toolCalls: [+ {+ id: "call_sub",+ name: "run_subagent",+ args: { prompt: "describe how the tests are laid out" },+ },+ ],+ },+ { text: "The child reports the tests are grouped by package." },+ ],+ { label: "parent", onRequest },+ );+ const session = makeSession({ llm: parent.model, environment });++ await collect(session.run([userText("how are the tests laid out?")], { approve: allowAll }));++ // Parent request, the child's two requests inside its tool call, then the parent again.+ expect(order.map((request) => request.label)).toEqual(["parent", "child", "child", "parent"]);+ const usages = replay(order);+ const reason =+ "the child context opens: it shares the parent's toolset and system prompt, but no " ++ "breakpoint sits after either, so none of that fixed prefix is addressable";+ expectHits(order, usages, new Map([[1, reason]]));+ const report = formatCacheReport(order, usages);+ // A self-spawned child sends the very same tools and system prompt as its parent and still+ // pays for them in full: the only entries in the cache end at whole requests.+ expect(usages[1]!.cache_read_input_tokens, report).toBe(0);+ expect(usages[1]!.cache_creation_input_tokens, report).toBe(prefixTokens(order[1]!));+ // And the parent's own line is untouched by the child having run in between.+ expect(usages[3]!.cache_read_input_tokens, report).toBe(prefixTokens(order[0]!));+ });++ it("a scheduled task's trigger still hits the prompt cache", async () => {+ const { order, onRequest } = ordering();+ const { model } = recordingModel(+ modelConfig(),+ [{ text: "Yesterday's run was clean." }, { text: "Ran the nightly checks; all green." }],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment: fakeEnvironment });++ await collect(session.run([userText("how did yesterday go?")], { approve: allowAll }));+ const trigger = buildScheduledMessage(+ "nightly-checks",+ "2026-09-14T03:00:00Z",+ "run the nightly checks and report anything red",+ );+ await collect(session.run([userText(trigger, "server")], { approve: allowAll }));++ expect(order).toHaveLength(2);+ const usages = replay(order);+ expectHits(order, usages);+ const report = formatCacheReport(order, usages);+ expect(wireMessage(order[1]!, -1).content[0]!.text, report).toContain("[scheduled_task]");+ expect(usages[1]!.cache_read_input_tokens, report).toBe(prefixTokens(order[0]!));+ });++ it("a session resumed from a Trace still hits the prompt cache, replayed history and all", async () => {+ const { order, onRequest } = ordering();+ await driveResume(onRequest);++ expect(order).toHaveLength(3);+ const usages = replay(order);+ // The resumed Session is the same context to the provider: its cache outlived the process.+ expectHits(order, usages);+ const report = formatCacheReport(order, usages);+ expect(usages[2]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));+ expect(explainMiss(order[1]!, order[2]!), report).toBe("no divergence");+ });++ it("a thinking-level move reads 0 because nothing closed an entry at the system prompt, then hits again", async () => {+ const { order, onRequest } = ordering();+ await driveThinkingMove(onRequest);++ expect(order).toHaveLength(3);+ const usages = replay(order);+ const reason =+ "the thinking level moved and no breakpoint sits after the system prompt, so nothing " ++ "behind the moved parameter is addressable";+ expectHits(order, usages, new Map([[1, reason]]));+ const report = formatCacheReport(order, usages);+ // The effort parameter sits after the system prompt, so the documented hierarchy says the+ // tools and the system prompt survive — but with one breakpoint at the end of the request+ // nothing ever closed an entry there, so the whole prefix is paid for again.+ expect(usages[1]!.cache_read_input_tokens, report).toBe(0);+ expect(usages[1]!.cache_creation_input_tokens, report).toBe(prefixTokens(order[1]!));+ // Once: the request after the move reads the moved level's prefix back in full.+ expect(usages[2]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));+ });++ it("a reopened context reads 0 because it is a new cache line, then hits the prompt cache from there", async () => {+ const { order, onRequest } = ordering();+ await driveCompaction(onRequest);++ expect(order.map((request) => request.label)).toEqual([+ "context 1",+ "context 1",+ "context 1",+ "context 2",+ "context 2",+ ]);+ const usages = replay(order);+ const reason =+ "the context reopened and no breakpoint sits after the system prompt, so the fixed " ++ "prefix the new context resends is not addressable either";+ expectHits(order, usages, new Map([[3, reason]]));+ const report = formatCacheReport(order, usages);+ // The compaction request runs on the same object with the same config: it reads the turn+ // it follows in full, which is the request where the context is largest.+ expect(usages[2]!.cache_read_input_tokens, report).toBe(prefixTokens(order[1]!));+ // What the rotation costs: the whole request, tools and system prompt included, even+ // though the reopened context sends byte-identical ones.+ expect(usages[3]!.cache_read_input_tokens, report).toBe(0);+ expect(usages[3]!.cache_creation_input_tokens, report).toBe(prefixTokens(order[3]!));+ // And the new context hits from its second request onwards.+ expect(usages[4]!.cache_read_input_tokens, report).toBe(prefixTokens(order[3]!));+ });+});++// ---------------------------------------------------------------------------+// Scenario helpers+// ---------------------------------------------------------------------------++/** One Session, a thinking-level move between its first and second task. */+async function driveThinkingMove(onRequest: (request: RecordedRequest) => void): Promise<void> {+ const { model } = recordingModel(+ modelConfig(),+ [{ text: "First answer." }, { text: "Second answer." }, { text: "Third answer." }],+ { label: MAIN, onRequest },+ );+ const session = makeSession({ llm: model, environment: fakeEnvironment });+ await collect(session.run([userText("task one")], { approve: allowAll }));+ session.thinkingLevel = "high";+ await collect(session.run([userText("task two")], { approve: allowAll }));+ await collect(session.run([userText("task three")], { approve: allowAll }));+}++/** One Session whose second task crosses the compaction threshold and opens a new context. */+async function driveCompaction(onRequest: (request: RecordedRequest) => void): Promise<void> {+ const first = recordingModel(+ modelConfig(),+ [+ { text: "First answer.", promptTokens: 20 },+ // Over the compaction threshold at the task's wrap-up round.+ { text: "Second answer.", promptTokens: 150 },+ { text: "[summary]the distilled summary[/summary]", promptTokens: 160 },+ ],+ { label: "context 1", onRequest },+ );+ const second = recordingModel(+ modelConfig(),+ [{ text: "Carried on from the summary." }, { text: "And on from there." }],+ { label: "context 2", onRequest },+ );+ const session = makeSession({+ llm: first.model,+ environment: fakeEnvironment,+ compaction: compactionSettings(),+ openNextContext: () => ({ llm: second.model }),+ });+ await collect(session.run([userText("task one")], { approve: allowAll }));+ await collect(session.run([userText("task two")], { approve: allowAll }));+ await collect(session.run([userText("task three")], { approve: allowAll }));+ await collect(session.run([userText("task four")], { approve: allowAll }));+}++/**+ * A runner whose every spawn hands back the one prepared child Session, origin-tagged as the+ * contract requires. Enough of the composition layer to put a real child Session's requests on+ * the same provider as its parent's.+ */+function childRunnerFor(get: () => Session | null): SubagentRunner {+ return {+ async spawn(): Promise<SubagentHandle> {+ const childSession = get();+ if (!childSession) throw new Error("the child session was not prepared");+ return {+ sessionId: CHILD_SESSION_ID,+ run: ({ messages, signal, approve }) =>+ tagged(+ childSession.run(messages, {+ ...(signal ? { signal } : {}),+ ...(approve ? { approve } : {}),+ }),+ ),+ dispose() {},+ };+ },+ };+}++async function* tagged(+ gen: AsyncGenerator<OmniMessage, RunCutoff | null>,+): AsyncGenerator<OmniMessage, RunCutoff | null> {+ for (;;) {+ const res = await gen.next();+ if (res.done) return res.value;+ yield { ...res.value, origin: [CHILD_SESSION_ID] };+ }+}++/**+ * One Session writing a Trace, then a fresh Session resuming from that Trace into a new model+ * object — the process restart, with the provider's cache untouched on the other side.+ */+async function driveResume(onRequest: (request: RecordedRequest) => void): Promise<void> {+ const traces = await mkdtemp(path.join(tmpdir(), "penguin-prompt-cache-trace-"));+ cleanups.push(() => rm(traces, { recursive: true, force: true }));++ const live = recordingModel(+ modelConfig(),+ [+ toolTurn({+ thinking: { text: "Read the README first.", signature: "sig-resume-1" },+ toolCalls: [{ id: "call_1", name: "read_file", args: { path: "README.md" } }],+ }),+ { text: "The README explains the layout." },+ ],+ { label: MAIN, onRequest },+ );+ const trace = new Writer({ tracesDir: traces, sessionId: SESSION_ID });+ const session = makeSession({ llm: live.model, environment: fakeEnvironment, trace });+ await collect(session.run([userText("read the README")], { approve: allowAll }));++ const resumed = resumeTrace(await readTrace(trace.currentPath()));+ const next = recordingModel(modelConfig(), [{ text: "Here are the packages." }], {+ label: MAIN,+ onRequest,+ });+ next.model.setHistory(resumed.history);+ const resumedSession = makeSession({+ llm: next.model,+ environment: fakeEnvironment,+ metaAlreadyWritten: true,+ initialEngineState: {+ carryOver: resumed.carryOver,+ sessionTurns: resumed.sessionTurns,+ sessionTokens: resumed.sessionTokens,+ lastRequestTotal: resumed.lastRequestTotal,+ },+ });+ await collect(resumedSession.run([userText("now list the packages")], { approve: allowAll }));+}diff --git a/packages/core/test/prompt-cache-simulator.test.ts b/packages/core/test/prompt-cache-simulator.test.tsnew file mode 100644index 00000000..4e8b660b--- /dev/null+++ b/packages/core/test/prompt-cache-simulator.test.ts@@ -0,0 +1,352 @@+/**+ * The simulator's own rules, on hand-built requests.+ *+ * `prompt-cache-lifecycle.test.ts` reads every scenario's result off this simulator, so the rules+ * it applies are pinned here first: what counts as a block, what counts as a position, which+ * change loses what, and the three limits a provider imposes on top of the hashes — the minimum+ * cacheable prefix, the entry lifetime, and the lookback window.+ *+ * The requests below are written by hand rather than recorded (`helpers/prompt-cache/recording.ts`+ * is what records them elsewhere), so each case is a statement about one rule and nothing else.+ */+import { describe, expect, it } from "vitest";+import type { UniConfig } from "@prismshadow/agenthub";+import {+ DEFAULT_TTL_MS,+ PromptCacheSim,+ fixedPrefixTokens,+ positionCount,+ prefixTokens,+ toolsAndSystemTokens,+ toolsTokens,+} from "./helpers/prompt-cache/index.js";+import type { RecordedRequest } from "./helpers/prompt-cache/index.js";++// ---------------------------------------------------------------------------+// A tiny RecordedRequest factory: the wire shape only, nothing the engine produces+// ---------------------------------------------------------------------------++interface WireBlock {+ type: string;+ [key: string]: unknown;+}+interface WireMessage {+ role: string;+ content: WireBlock[];+}++const TOOLS = [+ {+ name: "read_file",+ description: "Read a UTF-8 text file from the workspace.",+ input_schema: { type: "object", properties: { path: { type: "string" } } },+ },+ {+ name: "exec_command",+ description: "Run a shell command in the workspace.",+ input_schema: { type: "object", properties: { cmd: { type: "string" } } },+ },+];++const SYSTEM = "You are a coding agent. Read before you write, and say what you changed.";++/** The parameters a request carries when no thinking level is pinned. */+const PLAIN_PARAMETERS = { thinking: { type: "adaptive", display: "summarized" } };++interface RequestSpec {+ model?: string;+ tools?: Record<string, unknown>[];+ system?: string;+ parameters?: Record<string, unknown>;+ messages?: WireMessage[];+}++function request(spec: RequestSpec = {}): RecordedRequest {+ return {+ index: 0,+ messages: [],+ config: {} as UniConfig,+ wire: spec.messages ?? [],+ wireConfig: {+ model: spec.model ?? "claude-sonnet-4-6",+ stream: true,+ // Present on every request and part of none of them: the transport flag above, the+ // window-derived output cap here, and the breakpoint below.+ max_tokens: 32000,+ cache_control: { type: "ephemeral" },+ tools: spec.tools ?? TOOLS,+ system: spec.system ?? SYSTEM,+ ...(spec.parameters ?? PLAIN_PARAMETERS),+ },+ };+}++const text = (role: string, body: string): WireMessage => ({+ role,+ content: [{ type: "text", text: body }],+});++const counted = (n: number): number[] => Array.from({ length: n }, (_, i) => i);++const toolUses = (n: number): WireMessage => ({+ role: "assistant",+ content: counted(n).map((i) => ({+ type: "tool_use",+ id: `call_${i}`,+ name: "read_file",+ input: { path: `src/file-${i}.ts` },+ })),+});++const toolResults = (n: number): WireMessage => ({+ role: "user",+ content: counted(n).map((i) => ({+ type: "tool_result",+ tool_use_id: `call_${i}`,+ content: [{ type: "text", text: `contents of src/file-${i}.ts` }],+ })),+});++/** One opening turn, reused as the prefix every case below extends or diverges from. */+const OPENING: WireMessage[] = [text("user", "what does the entry point do?")];++/** `count` plain alternating turns, one position each. */+const turns = (count: number): WireMessage[] =>+ counted(count).map((i) => text(i % 2 === 0 ? "assistant" : "user", `turn ${i}`));++/** A simulator with no minimum, so these small fixtures exercise the hash rules alone. */+const openSim = (over: Partial<ConstructorParameters<typeof PromptCacheSim>[0]> = {}) =>+ new PromptCacheSim({ minCacheableTokens: 0, ...over });++/** The same, with the two extra breakpoints Anthropic allows alongside the automatic one. */+const widerSim = () => openSim({ breakpoints: "tools-system-automatic" });++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("prompt-cache simulator", () => {+ it("serves the whole prefix when a request repeats the previous one exactly", () => {+ const sim = openSim();+ const first = request({ messages: OPENING });+ const opening = sim.request(first);+ expect(opening.cache_read_input_tokens).toBe(0);+ expect(opening.cache_creation_input_tokens).toBe(prefixTokens(first));+ expect(opening.input_tokens).toBe(0);++ const repeat = sim.request(request({ messages: OPENING }));+ expect(repeat.cache_read_input_tokens).toBe(prefixTokens(first));+ expect(repeat.cache_creation_input_tokens).toBe(0);+ expect(repeat.hitRatio).toBe(1);+ });++ it("serves the whole previous prefix to a request that only appends", () => {+ const sim = openSim();+ const first = request({ messages: OPENING });+ sim.request(first);+ const next = request({+ messages: [...OPENING, text("assistant", "it re-exports the public API"), text("user", "ok")],+ });+ const usage = sim.request(next);+ expect(usage.cache_read_input_tokens).toBe(prefixTokens(first));+ expect(usage.cache_creation_input_tokens).toBe(prefixTokens(next) - prefixTokens(first));+ });++ it("serves nothing at all across a model switch, whatever the breakpoints", () => {+ const switched = request({ model: "claude-opus-4-6", messages: OPENING });++ // The model id sits ahead of the tools, so every breakpoint's prefix moves with it: a model+ // switch is the one invalidator no breakpoint can be placed in front of.+ const wider = widerSim();+ wider.request(request({ messages: OPENING }));+ const covered = wider.request(switched);+ expect(covered.cache_read_input_tokens).toBe(0);+ expect(covered.cache_creation_input_tokens).toBe(prefixTokens(switched));++ const automatic = openSim();+ automatic.request(request({ messages: OPENING }));+ expect(automatic.request(switched).cache_read_input_tokens).toBe(0);+ });++ it("loses the system prompt on a fast-mode toggle but keeps the tools", () => {+ // `speed` and `betas` are what AgentHub sets for fast mode, and they are rendered ahead of+ // the system block: the tools survive the toggle and the system prompt does not.+ const fast = request({+ parameters: { ...PLAIN_PARAMETERS, speed: "fast", betas: ["fast-mode-2026-01-01"] },+ messages: OPENING,+ });++ const wider = widerSim();+ wider.request(request({ messages: OPENING }));+ const covered = wider.request(fast);+ expect(covered.cache_read_input_tokens).toBe(toolsTokens(fast));+ expect(covered.cache_read_input_tokens).toBeLessThan(toolsAndSystemTokens(fast));++ const automatic = openSim();+ automatic.request(request({ messages: OPENING }));+ expect(automatic.request(fast).cache_read_input_tokens).toBe(0);+ });++ it("keeps the tools past a system-prompt change only with a breakpoint on them", () => {+ const moved = request({ system: `${SYSTEM} Prefer the smallest change.`, messages: OPENING });++ const wider = widerSim();+ wider.request(request({ messages: OPENING }));+ const covered = wider.request(moved);+ expect(covered.cache_read_input_tokens).toBe(toolsTokens(moved));+ expect(covered.cache_read_input_tokens).toBeLessThan(toolsAndSystemTokens(moved));++ // With the single automatic breakpoint the harness sends, no request ever closed an entry+ // at the tools boundary, so there is nothing behind the divergence to read.+ const automatic = openSim();+ automatic.request(request({ messages: OPENING }));+ expect(automatic.request(moved).cache_read_input_tokens).toBe(0);+ });++ it("keeps the tools and system prompt past a parameter change only with a breakpoint", () => {+ const thinking = request({+ parameters: { ...PLAIN_PARAMETERS, output_config: { effort: "high" } },+ messages: OPENING,+ });++ const wider = widerSim();+ wider.request(request({ messages: OPENING }));+ const covered = wider.request(thinking);+ expect(covered.cache_read_input_tokens).toBe(toolsAndSystemTokens(thinking));+ // The parameters block sits after the system block and no breakpoint closes it, so the+ // parameters themselves are never part of what a diverged request reads back.+ expect(covered.cache_read_input_tokens).toBeLessThan(fixedPrefixTokens(thinking));++ const automatic = openSim();+ automatic.request(request({ messages: OPENING }));+ expect(automatic.request(thinking).cache_read_input_tokens).toBe(0);+ });++ it("ignores the parameters that take no part in the prefix", () => {+ const sim = openSim();+ const first = request({ messages: OPENING });+ sim.request(first);+ // A different output cap and a different breakpoint spelling: same cached prefix.+ const relaxed = request({ messages: OPENING });+ relaxed.wireConfig.max_tokens = 8000;+ relaxed.wireConfig.cache_control = { type: "ephemeral", ttl: "1h" };+ expect(sim.request(relaxed).cache_read_input_tokens).toBe(prefixTokens(first));+ });++ it("falls back to the last breakpoint ahead of an edited message", () => {+ const sim = openSim();+ const history = [+ text("user", "read the README"),+ text("assistant", "it describes the layout"),+ text("user", "and the packages?"),+ ];+ const opening = request({ messages: history.slice(0, 1) });+ sim.request(opening);+ sim.request(request({ messages: history }));+ // The third message is rewritten: the write that covered it is gone, and the read falls+ // back to the one breakpoint still ahead of the divergence — the opening request's.+ const edited = request({+ messages: [...history.slice(0, 2), text("user", "and the plugins?")],+ });+ expect(sim.request(edited).cache_read_input_tokens).toBe(prefixTokens(opening));+ });++ it("never caches a prefix below the provider's minimum", () => {+ const tiny: RequestSpec = { tools: [], system: "be brief", messages: OPENING };+ const strict = new PromptCacheSim();+ const first = strict.request(request(tiny));+ expect(first.wrote).toBe(false);+ expect(first.cache_creation_input_tokens).toBe(0);+ expect(first.input_tokens).toBe(prefixTokens(request(tiny)));+ expect(strict.request(request(tiny)).cache_read_input_tokens).toBe(0);+ // The same prefix under a simulator with no minimum does cache — it is the size that+ // refuses it, nothing about the bytes.+ const relaxed = openSim();+ const opening = request(tiny);+ relaxed.request(opening);+ expect(relaxed.request(request(tiny)).cache_read_input_tokens).toBe(prefixTokens(opening));+ });++ it("expires an entry once the TTL passes since its last use, and a read refreshes it", () => {+ let clock = 1_000_000;+ const sim = openSim({ now: () => clock });+ const opening = request({ messages: OPENING });+ sim.request(opening);++ // The middle request extends the prefix instead of repeating it, so the entry it writes is+ // a different one: nothing but the read itself can keep the opening prefix alive.+ clock += DEFAULT_TTL_MS - 1;+ const extended = request({+ messages: [...OPENING, text("assistant", "it re-exports the public API"), text("user", "ok")],+ });+ expect(sim.request(extended).cache_read_input_tokens).toBe(prefixTokens(opening));++ // Just short of a second lifetime after that read, and well past the first one.+ clock += DEFAULT_TTL_MS - 1;+ expect(sim.request(request({ messages: OPENING })).cache_read_input_tokens).toBe(+ prefixTokens(opening),+ );++ clock += DEFAULT_TTL_MS + 1;+ const cold = sim.request(request({ messages: OPENING }));+ expect(cold.cache_read_input_tokens).toBe(0);+ expect(cold.cache_creation_input_tokens).toBe(prefixTokens(opening));+ });++ it("checks twenty positions per breakpoint, the breakpoint counting as the first", () => {+ const within = openSim();+ const opening = request({ messages: OPENING });+ within.request(opening);+ const nineteen = request({ messages: [...OPENING, ...turns(19)] });+ expect(positionCount(nineteen) - positionCount(opening)).toBe(19);+ expect(within.request(nineteen).cache_read_input_tokens).toBe(prefixTokens(opening));++ // One position further and the previous write is out of reach: the request pays in full.+ const beyond = openSim();+ beyond.request(request({ messages: OPENING }));+ const twenty = request({ messages: [...OPENING, ...turns(20)] });+ expect(beyond.request(twenty).cache_read_input_tokens).toBe(0);+ });++ it("gives every breakpoint its own lookback window, anchored at its own position", () => {+ const opening = request({ messages: OPENING });+ // Far past the twenty positions any one window reaches back, so a read can only come from a+ // breakpoint that sits next to what it is looking for.+ const far = request({ messages: [...OPENING, ...turns(40)] });+ expect(positionCount(far) - positionCount(opening)).toBeGreaterThan(20);++ const wider = widerSim();+ wider.request(opening);+ // The system breakpoint looks back from the system block, where the entry it wants sits at+ // distance zero; only the automatic breakpoint is out of reach of the earlier write.+ expect(wider.request(far).cache_read_input_tokens).toBe(toolsAndSystemTokens(far));++ const automatic = openSim();+ automatic.request(request({ messages: OPENING }));+ expect(automatic.request(far).cache_read_input_tokens).toBe(0);+ });++ it("collapses a run of tool calls or tool results into one position", () => {+ const sim = openSim();+ const opening = request({ messages: OPENING });+ sim.request(opening);+ const round = request({ messages: [...OPENING, toolUses(25), toolResults(25)] });+ // Fifty blocks, two positions: a wide parallel round stays within reach of the lookback.+ expect(positionCount(round) - positionCount(opening)).toBe(2);+ expect(sim.request(round).cache_read_input_tokens).toBe(prefixTokens(opening));+ });++ it("keeps a write invisible until its request completes", () => {+ const sim = openSim();+ const parent = request({ messages: OPENING });+ sim.begin(parent);+ // A second request issued while the first is still streaming: nothing to read yet.+ const sibling = request({ messages: OPENING });+ expect(sim.begin(sibling).cache_read_input_tokens).toBe(0);+ sim.complete(parent);+ sim.complete(sibling);+ expect(sim.request(request({ messages: OPENING })).cache_read_input_tokens).toBe(+ prefixTokens(parent),+ );+ });+});