leanprompt 0.0.1 → 0.1.0-dev.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-DOCS +396 -0
  3. package/NOTICE +11 -0
  4. package/README.md +86 -3
  5. package/cli/dist/detect.d.ts +23 -0
  6. package/cli/dist/detect.js +219 -0
  7. package/cli/dist/evalAudit.d.ts +32 -0
  8. package/cli/dist/evalAudit.js +161 -0
  9. package/cli/dist/facts.d.ts +14 -0
  10. package/cli/dist/facts.js +43 -0
  11. package/cli/dist/forms.d.ts +23 -0
  12. package/cli/dist/forms.js +199 -0
  13. package/cli/dist/frontmatter.d.ts +10 -0
  14. package/cli/dist/frontmatter.js +32 -0
  15. package/cli/dist/help.d.ts +27 -0
  16. package/cli/dist/help.js +118 -0
  17. package/cli/dist/init.d.ts +78 -0
  18. package/cli/dist/init.js +358 -0
  19. package/cli/dist/install.d.ts +20 -0
  20. package/cli/dist/install.js +225 -0
  21. package/cli/dist/isMain.d.ts +6 -0
  22. package/cli/dist/isMain.js +18 -0
  23. package/cli/dist/lesson.d.ts +16 -0
  24. package/cli/dist/lesson.js +205 -0
  25. package/cli/dist/lint/facts.d.ts +7 -0
  26. package/cli/dist/lint/facts.js +163 -0
  27. package/cli/dist/lint/numbers.d.ts +26 -0
  28. package/cli/dist/lint/numbers.js +163 -0
  29. package/cli/dist/lint/rules.d.ts +20 -0
  30. package/cli/dist/lint/rules.js +170 -0
  31. package/cli/dist/log/logger.d.ts +49 -0
  32. package/cli/dist/log/logger.js +148 -0
  33. package/cli/dist/log/record.d.ts +56 -0
  34. package/cli/dist/log/record.js +117 -0
  35. package/cli/dist/main.d.ts +6 -0
  36. package/cli/dist/main.js +67 -0
  37. package/cli/dist/profile.d.ts +93 -0
  38. package/cli/dist/profile.js +372 -0
  39. package/cli/dist/report/cost.d.ts +55 -0
  40. package/cli/dist/report/cost.js +151 -0
  41. package/cli/dist/report/html.d.ts +81 -0
  42. package/cli/dist/report/html.js +555 -0
  43. package/cli/dist/report/template.html +269 -0
  44. package/cli/dist/score/calibrate.d.ts +65 -0
  45. package/cli/dist/score/calibrate.js +213 -0
  46. package/cli/dist/score/measured.d.ts +66 -0
  47. package/cli/dist/score/measured.js +191 -0
  48. package/cli/dist/score/static.d.ts +112 -0
  49. package/cli/dist/score/static.js +172 -0
  50. package/cli/dist/score/write.d.ts +29 -0
  51. package/cli/dist/score/write.js +247 -0
  52. package/forms/AGENTS.block.md +25 -0
  53. package/forms/opencode/commands/leanprompt-audit.md +10 -0
  54. package/forms/opencode/commands/leanprompt.md +8 -0
  55. package/forms/skills/generation-economy/SKILL.md +89 -0
  56. package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
  57. package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
  58. package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
  59. package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
  60. package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
  61. package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
  62. package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
  63. package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
  64. package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
  65. package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
  66. package/forms/skills/leanprompt/SKILL.md +48 -0
  67. package/forms/skills/leanprompt/fix.md +15 -0
  68. package/forms/skills/leanprompt/init.md +30 -0
  69. package/forms/skills/llm-call-audit/SKILL.md +169 -0
  70. package/forms/skills/llm-call-audit/call-shapes.md +99 -0
  71. package/forms/skills/llm-call-audit/presenting.md +72 -0
  72. package/forms/skills/llm-call-audit/report-template.md +113 -0
  73. package/forms/skills/lmwarden/SKILL.md +97 -0
  74. package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
  75. package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
  76. package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
  77. package/forms/skills/measure-loop/SKILL.md +155 -0
  78. package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
  79. package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
  80. package/forms/skills/prefill-cache/SKILL.md +66 -0
  81. package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
  82. package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
  83. package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
  84. package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
  85. package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
  86. package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
  87. package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
  88. package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
  89. package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
  90. package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
  91. package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
  92. package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
  93. package/forms/skills/prompt-diet/SKILL.md +69 -0
  94. package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
  95. package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
  96. package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
  97. package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
  98. package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
  99. package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
  100. package/models/anthropic-thinking.md +38 -0
  101. package/models/openai-reasoning.md +35 -0
  102. package/models/qwen.md +34 -0
  103. package/package.json +31 -8
  104. package/providers/anthropic.md +83 -0
  105. package/providers/deepinfra.md +46 -0
  106. package/providers/gemini.md +61 -0
  107. package/providers/openai.md +73 -0
  108. package/providers/openrouter.md +66 -0
  109. package/providers/sglang.md +41 -0
  110. package/providers/vllm.md +52 -0
  111. package/runtimes/http-clients.md +20 -0
  112. package/skills/_template/RULE.md +31 -0
  113. package/skills/generation-economy/SKILL.md +88 -0
  114. package/skills/generation-economy/rules/LP-GE-01.md +92 -0
  115. package/skills/generation-economy/rules/LP-GE-02.md +81 -0
  116. package/skills/generation-economy/rules/LP-GE-03.md +86 -0
  117. package/skills/generation-economy/rules/LP-GE-04.md +117 -0
  118. package/skills/generation-economy/rules/LP-GE-05.md +83 -0
  119. package/skills/generation-economy/rules/LP-GE-06.md +75 -0
  120. package/skills/generation-economy/rules/LP-GE-07.md +83 -0
  121. package/skills/generation-economy/rules/LP-GE-08.md +70 -0
  122. package/skills/generation-economy/rules/LP-GE-09.md +78 -0
  123. package/skills/generation-economy/rules/LP-GE-10.md +103 -0
  124. package/skills/leanprompt/SKILL.md +47 -0
  125. package/skills/leanprompt/fix.md +14 -0
  126. package/skills/leanprompt/init.md +29 -0
  127. package/skills/llm-call-audit/SKILL.md +168 -0
  128. package/skills/llm-call-audit/call-shapes.md +98 -0
  129. package/skills/llm-call-audit/presenting.md +71 -0
  130. package/skills/llm-call-audit/report-template.md +112 -0
  131. package/skills/lmwarden/SKILL.md +96 -0
  132. package/skills/lmwarden/rules/LP-LW-01.md +72 -0
  133. package/skills/lmwarden/rules/LP-LW-02.md +77 -0
  134. package/skills/lmwarden/rules/LP-LW-03.md +72 -0
  135. package/skills/measure-loop/SKILL.md +154 -0
  136. package/skills/measure-loop/templates/stable-head.template.ts +38 -0
  137. package/skills/measure-loop/templates/stable_head_template.py +40 -0
  138. package/skills/prefill-cache/SKILL.md +65 -0
  139. package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
  140. package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
  141. package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
  142. package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
  143. package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
  144. package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
  145. package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
  146. package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
  147. package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
  148. package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
  149. package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
  150. package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
  151. package/skills/prompt-diet/SKILL.md +68 -0
  152. package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
  153. package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
  154. package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
  155. package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
  156. package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
  157. package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
@@ -0,0 +1,72 @@
1
+ ---
2
+ id: LP-LW-03
3
+ title: One key per app or tenant; cache scope is a privacy boundary
4
+ skill: lmwarden
5
+ applies_to: [vllm, sglang, lm-warden]
6
+ saves: prefill
7
+ severity: medium
8
+ evidence:
9
+ - doc: https://docs.vllm.ai/en/latest/features/automatic_prefix_caching.html
10
+ checked: 2026-11-26
11
+ ---
12
+ ## Rule
13
+ Give each app or tenant of a shared self-hosted server its own API key, and treat the prefix cache as shared by everyone who reaches the same model unless you have confirmed that it is partitioned.
14
+
15
+ ## Why
16
+ Two separate things share this rule.
17
+
18
+ **Accounting.** One key for several apps makes usage unattributable: you cannot see which app generates the long prompts, the repeats and the misses, so none of the other rules can be targeted. LM Warden issues a key per consumer with its own usage figures; other servers vary, and a reverse proxy can add keys in front of any of them.
19
+
20
+ **Isolation.** A prefix cache matches on tokens: each block's hash covers every token before it, so any request that starts with the same tokens finds the same block ([providers/vllm.md](../../../providers/vllm.md)). The cache does not know who sent the earlier request unless the engine partitions it. A request that reuses a prefix is answered faster than one that does not, so a tenant who can time responses can learn whether another tenant sent a given prefix recently. That follows from how prefix caches work and is untested here. For an internal app sharing a system prompt with its siblings the cost is nothing; for tenants whose prompts are confidential from one another it is a privacy question. The vLLM page read does not mention `cache_salt` and the SGLang pages read do not either (checked 2026-11-26); whether your engine version supports a per-request cache salt is a question for its documentation. This skill has not verified whether LM Warden partitions the cache by key, so do not assume it does.
21
+
22
+ The trade is real: a partitioned cache cannot share one long system prompt across tenants, so it prefills that prompt once per partition. Share a cache across consumers you trust, separate it across consumers you do not.
23
+
24
+ ## Detect in code
25
+ Look for one credential used by several apps or tenants, and for per-tenant content going through a shared server.
26
+
27
+ Python:
28
+ ```
29
+ rg -n 'api_key=os\.environ|OPENAI_API_KEY|LLM_API_KEY|api_key=.*(SHARED|COMMON|TEAM)' -g '*.py'
30
+ rg -n 'tenant|org_id|customer_id' -g '*.py'
31
+ ```
32
+ Shapes: one `api_key` read from a shared environment variable by several services; a function that serves many tenants with a single client object and builds each tenant's prompt with its private data in the system prompt.
33
+
34
+ TS/JS:
35
+ ```
36
+ rg -n 'apiKey: process\.env|new OpenAI\(\{' -g '*.{ts,tsx,js,mjs}'
37
+ rg -n 'tenantId|orgId|customerId' -g '*.{ts,tsx,js,mjs}'
38
+ ```
39
+ Shapes: a module-level `new OpenAI({ baseURL, apiKey })` used for every tenant's request.
40
+
41
+ Go:
42
+ ```
43
+ rg -n 'openai\.NewClient|option\.WithAPIKey|os\.Getenv\("(LLM|OPENAI)_' -g '*.go'
44
+ rg -n 'TenantID|OrgID|CustomerID' -g '*.go'
45
+ ```
46
+ Shapes: one package-level client with one key serving requests for many tenants.
47
+
48
+ Also in deployment files: the same key value or secret reference mounted into several services.
49
+
50
+ ## Fix
51
+ One key per app, and for tenants who must not share a cache, a separate key and, where your engine supports it, a separate cache partition; otherwise a separate model instance.
52
+
53
+ ```python
54
+ # before: every app and tenant shares one key
55
+ client = OpenAI(base_url=SERVER_URL, api_key=os.environ["LLM_API_KEY"])
56
+
57
+ # after: one key per app, named after it, from that app's own secret
58
+ client = OpenAI(base_url=SERVER_URL, api_key=os.environ["BILLING_APP_LLM_KEY"])
59
+ ```
60
+
61
+ For several tenants in one app, keep tenant-specific text after the shared prefix, never in the shared head (`prefill-cache` LP-PC-07), and do not put one tenant's confidential data in text that other tenants' prompts share a prefix with. If tenants must be isolated from each other's timing, give each its own key and a partitioned cache or its own instance, and accept the lower reuse.
62
+
63
+ ## Don't break meaning
64
+ Splitting keys does not change answers. Do not split a prefix that belongs to one consumer across keys that do not share a cache: that lowers reuse for nothing (`prefill-cache` LP-PC-12). Do not paste a key into a prompt or a log. When rotating keys, use the server's grace window if it has one, so a running app is not cut off.
65
+
66
+ ## Verify
67
+ (a) The server's per-key usage shows each app's own requests and tokens, and no app's usage appears under another's key.
68
+
69
+ (b) For isolation, send the same long prefix from two keys: if the second request reports cached tokens (`cached_tokens`, where the server reports it) for the first's prefix, the cache is shared across those keys. That is the answer to whether your setup partitions it, for that engine version.
70
+
71
+ ## Waste signal
72
+ Measured: none directly; attribution by key is what lets the other rules' signals be read per app, and the usage log carries no key. Static: severity medium where one credential is read by several services or one client serves several tenants through a shared server; low for a single app with a single consumer. A shared cache is not waste, and it is only a finding where the tenants' prompts are confidential from each other.
@@ -0,0 +1,154 @@
1
+ ---
2
+ name: measure-loop
3
+ description: Use when you need to prove that a change to an LLM-calling app made it cheaper or faster, or to keep it from regressing — logging cache usage per call (cached_tokens, cache_read_input_tokens, cache_creation_input_tokens), replaying a recorded session before and after a change, writing a CI test that fails when the system prompt or tool list stops being stable, running npx leanprompt score or leanprompt calibrate, or when someone asks "did that fix work?" for Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra or a self-hosted vLLM or SGLang server. Turns each fix from a claim into a before and after number.
4
+ license: CC-BY-4.0
5
+ ---
6
+
7
+ # measure-loop
8
+
9
+ Makes every change to an LLM-calling app answer to numbers: measure, change one thing, measure again, then prove it with a score anyone can rerun. The other skills say what to change (`prefill-cache`, `generation-economy`, `prompt-diet`); this one says how to know it worked and how to keep it working.
10
+
11
+ ## When to use
12
+
13
+ - You changed a prompt builder, a tool registry, a history store, a retry or a token budget, and want to know what it did to cache reuse and output tokens.
14
+ - You want a test in CI that fails when the stable head of a request changes (a timestamp added to a system prompt, a tool reordered, old messages re-serialised).
15
+ - You want a score for the badge or the report: `npx leanprompt score`, optionally `leanprompt calibrate`.
16
+ - The `prefill-cache`, `generation-economy` or `prompt-diet` skill sent you here for a rule's "Verify" step.
17
+
18
+ ## Ask first
19
+
20
+ Before you edit the app's code, install a package, add a file outside `.leanprompt/`, or run anything that sends requests to a provider (they are billed), show the change or the command and ask. The user may prefer to run it themselves. No ask is needed for `npx leanprompt score` and `npx leanprompt calibrate`, which only read and write files under `.leanprompt/` and make no network calls; `calibrate` still writes `.leanprompt/weights.json` only after `y` or `--yes`. Offering to share a lesson (below) needs no ask, but `npx leanprompt lesson` writes `.leanprompt/lesson.md`, so run it only after the user says yes.
21
+
22
+ ## Workflow
23
+
24
+ 1. **Measure.** Propose adding the usage logger (below) as a small diff, and add it only if the user says yes. Then ask the user to run a fixed scenario through the app, or ask whether you may run it (it sends real, billed requests): several sessions, with follow-up turns, not one request repeated. Keep the scenario so the next run is comparable.
25
+ 2. **Change one rule at a time.** Propose a single rule's fix from `prefill-cache`, `generation-economy` or `prompt-diet` as a diff, with its "Don't break meaning" check, and apply it only after the user says yes. If two things change together, the result cannot be credited to either.
26
+ 3. **Measure again.** Replay the same scenario against the same model, or collect real traffic. A replay sends real requests to the provider, which are billed: ask the user to run it, or ask before you run it yourself. Compare the same fields: cached tokens against prompt tokens, output tokens, number of calls, `finish: "length"`, retries.
27
+ 4. **Prove.** `npx leanprompt score` writes `.leanprompt/score.json` (the badge source) from the usage log. With no log yet, `npx leanprompt score --static` scores the audit's findings instead and labels it "static". To fit the static score to your app, run `leanprompt calibrate` ([docs/calibration.md](../../docs/calibration.md)).
28
+ 5. **Keep it.** Offer the stable-head test (below) as its own small diff, and add it only after the user says yes, so the change cannot quietly come undone.
29
+
30
+ ## Read the provider's own usage fields first
31
+
32
+ Every provider reports what it cached. Read these before any other tool; they are what you are billed on. Where each lives, and what the provider says about it, is in the dated tables.
33
+
34
+ | Provider | Cache read | Cache write |
35
+ |---|---|---|
36
+ | OpenAI-compatible APIs, vLLM, DeepInfra, OpenRouter | `usage.prompt_tokens_details.cached_tokens` | OpenRouter: `cache_write_tokens` beside it |
37
+ | Anthropic | `usage.cache_read_input_tokens` | `usage.cache_creation_input_tokens` |
38
+ | Gemini | the cached-content token count, `usageMetadata.cachedContentTokenCount` in the leanprompt logger | none reported |
39
+
40
+ Details and sources: [providers/openai.md](../../providers/openai.md), [providers/anthropic.md](../../providers/anthropic.md), [providers/gemini.md](../../providers/gemini.md) (its SDK examples name a different field, so check the response you get), [providers/openrouter.md](../../providers/openrouter.md), [providers/deepinfra.md](../../providers/deepinfra.md), [providers/vllm.md](../../providers/vllm.md). A hit that reports 0 with no error usually means the prompt was under the model's minimum or the prefix changed; the tables list the minimums and the rules say what changes a prefix.
41
+
42
+ ## Log every call
43
+
44
+ Adding the logger is a change to the app's code: show the lines below as a diff for the user's call site, and add them only if the user says yes. The leanprompt usage logger writes one JSON line per call to `.leanprompt/usage.jsonl`: kvsig ids, character counts, token counts from the usage fields above, the finish reason and flags. It never writes prompt or completion text, and it never raises into your request path.
45
+
46
+ Install it first, and propose the install command to the user instead of running it (it adds a dependency). Until the npm release, the `leanprompt` package on npm is a placeholder with no logger, so install from GitHub, where it is built on install:
47
+
48
+ - TypeScript or JavaScript, propose: `npm i github:Podwarden/leanprompt#v0.1.0-dev.1`. After the npm release: `npm i leanprompt`.
49
+ - Python, propose: `pip install "git+https://github.com/Podwarden/leanprompt#subdirectory=python"` (`uv pip install` takes the same argument). The `leanprompt-cli` package on PyPI is a placeholder too until the release; then `pip install leanprompt-cli`.
50
+
51
+ TypeScript or JavaScript:
52
+
53
+ ```ts
54
+ import { createLogger } from "leanprompt/log";
55
+ const logger = createLogger({ path: ".leanprompt/usage.jsonl", key: keyBytes, provider: "openai", model: "gpt-x" });
56
+ // after each call:
57
+ logger.log({ dialect: "openai.chat", body: requestBody, params: { temperature } }, { usage: response.usage, finish: choice.finish_reason });
58
+ // log() returns at once and appends in the background. Before a script or test exits, await logger.flush().
59
+ ```
60
+
61
+ Python (package `leanprompt-cli`):
62
+
63
+ ```python
64
+ from leanprompt_cli import Logger
65
+ logger = Logger(".leanprompt/usage.jsonl", key_bytes, "openai", "gpt-x")
66
+ # after each call:
67
+ logger.log("openai.chat", request_body, response.usage, params={"temperature": t}, finish=choice.finish_reason)
68
+ ```
69
+
70
+ The `provider` you pass decides which cache facts score the call, so name where the request is served, not the SDK that sends it:
71
+
72
+ - A hosted API with its own table: `anthropic`, `openai`, `gemini`, `openrouter` or `deepinfra`.
73
+ - A self-hosted server: the engine name, `vllm`, `sglang` or `lm-warden` (LM Warden uses the vLLM table), even when you call it through the OpenAI SDK. Logged as `openai`, its calls get OpenAI's cache facts and the `engine:` values in `leanprompt.yaml` are not applied.
74
+ - Another OpenAI-compatible host (Groq, Together, Azure, DeepSeek and others with no table here): its own name. With no table, the target in `leanprompt.yaml` (`target.provider` or `target.engine`) decides the cache facts; with no target set, those calls are unmeasured (`unknown_provider`) and `score` says so. With several `targets`, a host name that matches no entry is unmeasured as `ambiguous_target` rather than guessed, so log each backend under its own name.
75
+
76
+ `key_bytes` is a 32-byte secret you generate once and keep out of the repo; the ids are keyed and mean nothing without it. When you retry, pass the index the previous `log` returned as `retry_of`; when your parser rejects an answer, set `parse_failed`. The generation rules read those flags.
77
+
78
+ ## Replay: send a recorded session twice
79
+
80
+ For a before and after you need the same traffic twice. Record the requests of a session (ids and token counts are enough to compare; keep the bodies only if your own policy allows it), then send the same session through the old and the new code, or through the same code twice a few seconds apart. The second pass shows what the provider could reuse. Every pass sends real requests to the provider, which are billed, so ask the user before you start one, or let them run it. Gaps longer than the provider's cache lifetime ([providers/anthropic.md](../../providers/anthropic.md), [providers/openai.md](../../providers/openai.md)) make the second pass cold, which is expected and not a bug. The leanprompt repo's replay harness (`npm run eval`, `eval/run.ts`) replays the example apps in `examples/` this way; with a `sim:` target it uses a local simulator and costs nothing, and pointed at a provider it sends real requests, which are billed, so ask the user before you run it that way.
81
+
82
+ ## The stable-head test (kvsig ids in CI)
83
+
84
+ kvsig gives every request keyed ids for its system prompt (`sys`), its tool list (`tools`), the two together (`head`) and each prefix (`nodes[i]`). Two requests with equal exact `nodes[i]` have the same prompt up to message `i`. A test can build the request your app would send for two fixed inputs (two users, two days, two working directories) and fail when the stable head differs. It runs offline, in milliseconds, with no provider call, and it catches a tool reordered by a refactor, a timestamp added to a system prompt, or a history store that re-serialises old messages.
85
+
86
+ The test needs kvsig 0.1.0 as a dev dependency, `npm i -D @kvsig/core@0.1.0` (npm) or `pip install kvsig==0.1.0` (PyPI), the helper template copied into the project's tests, and a test file that points it at the app's request builder. The templates are helpers, not tests, and their names keep test runners from collecting them where they are installed. Propose the install command, the copied helper and the new test file as one small diff, and run or add them only after the user says yes:
87
+
88
+ - TypeScript, once the user says yes: copy [templates/stable-head.template.ts](templates/stable-head.template.ts) to the project's tests as `stable-head.ts` and write the test in `stable-head.test.ts` (vitest, jest or any runner)
89
+ - Python, once the user says yes: copy [templates/stable_head_template.py](templates/stable_head_template.py) to the project's tests as `stable_head.py` and write the test in `test_stable_head.py` (pytest)
90
+
91
+ Leave the trailing `leanprompt:generated` line out of the proposed copy: it marks the installed template, which `leanprompt update` keeps up to date, not the user's file.
92
+
93
+ ```ts
94
+ import { assertStableHead } from "./stable-head";
95
+ it("the head does not change from one day to the next", () =>
96
+ assertStableHead(
97
+ (now) => app.buildRequest("Where is my order?", { session: 0, turn: 0, now }),
98
+ [new Date("2026-11-03T08:15:42Z"), new Date("2026-11-04T17:02:09Z")],
99
+ { sys: true, tools: true },
100
+ ));
101
+ ```
102
+
103
+ Use `nodesUpTo` only when the inputs leave the first messages equal: a request that carries the date in its newest user message (the fix for LP-PC-03) has equal `head` but a different `nodes[0]` for two days, so leave `nodesUpTo` out there.
104
+
105
+ Assert only on `kvsig/1` exact ids and `loose/1` ids; never on `loose/2`, which is experimental. The test uses exact ids for what the provider caches and the loose ids only to explain a failure.
106
+
107
+ ### Which id to assert for each rule
108
+
109
+ | Rule | Assert equal across the two inputs | Inputs to vary |
110
+ |---|---|---|
111
+ | [LP-PC-02](../prefill-cache/rules/LP-PC-02.md), [LP-PC-03](../prefill-cache/rules/LP-PC-03.md) | `sys`, then `head` | the date, a user id, a working directory, a version |
112
+ | [LP-PC-04](../prefill-cache/rules/LP-PC-04.md) | `tools` | process restarts or seeds (registration order) |
113
+ | [LP-PC-05](../prefill-cache/rules/LP-PC-05.md) | `sys` every turn; `tools` only on turns that add a tool | a session that loads a tool mid-way |
114
+ | [LP-PC-06](../prefill-cache/rules/LP-PC-06.md), [LP-PC-09](../prefill-cache/rules/LP-PC-09.md) | `nodes[0..i]` between consecutive turns | a two-turn session; the later request starts with all earlier `nodes` |
115
+ | [LP-PC-07](../prefill-cache/rules/LP-PC-07.md) | `head` | two users |
116
+ | [LP-PC-08](../prefill-cache/rules/LP-PC-08.md) | `head` before and after a compaction (`conv` is expected to change) | a session long enough to compact |
117
+
118
+ ### Reading a failure
119
+
120
+ The messages follow kvsig's [reading-the-ids](https://github.com/Podwarden/kvsig/blob/main/docs/reading-the-ids.md) table:
121
+
122
+ | Failure | Meaning | Look at |
123
+ |---|---|---|
124
+ | `sys` differs, `loose_sys` equal | the system prompt changed only in noise: a bare date line, a reminder, whitespace | LP-PC-03 |
125
+ | `sys` differs, `loose_sys` differs | the system prompt changed beyond noise: a labelled date or time ("Current time: ..."), an id, a path, or wording | LP-PC-03, and what the input is allowed to change |
126
+ | `tools` differs, `loose_tools` equal | only the member order inside a schema or arguments changed | LP-PC-04, key order |
127
+ | `tools` differs, `loose_tools` differs | a tool was added, removed, edited or reordered | LP-PC-04, LP-PC-05 |
128
+ | `nodes[i]` differs, `sys` and `tools` equal | part of the history was rewritten: an edit, a fork, or old messages re-serialised | LP-PC-06 |
129
+
130
+ Ids tell you the prompt was reusable; they do not tell you the provider reused it. Pair a passing test with the usage fields in a real run, and see the limits of kvsig in its reading-the-ids page ("What the ids do not tell you").
131
+
132
+ ## Where the measured score stops
133
+
134
+ The score comes from the usage log, so it inherits the log's limits. Say so when you quote it.
135
+
136
+ - **It needs at least 50 measured calls** (calls minus unmeasured), and states how many it used. With fewer, `score` refuses a measured number, prints how many measured calls it found, and suggests `--static`.
137
+ - **Reusable tokens are an estimate by character share**, not a token count from the provider's tokenizer ([docs/calibration.md](../../docs/calibration.md) explains how the static weights are fitted against it).
138
+ - **A cache has a lifetime.** A prefix that returns after the provider's lifetime was not reusable; the lifetimes are in the provider tables. The lifetime changes the cache-reuse figure (E) only; the stability figure (S) ignores it, because a user's pause is not the app rewriting its prefix.
139
+ - **Requests kvsig cannot identify** (a dialect it does not read, a body over 2 MiB, malformed JSON) are counted as "unmeasured" and left out of the reuse figures; they are not counted as zero reuse.
140
+ - **Failed calls are unmeasured too.** A call that failed (finish `error`) never reached the cache, or its state is unknown, so it is left out of the reuse figures, not counted as zero.
141
+ - **The heads diagnostic is information only.** It reports how many distinct heads and conversations the log holds. A head that differs per session shows up there, not in the score; read it beside the score.
142
+ - **Money is not in the score.** It covers tokens only, because prices change.
143
+
144
+ The target profile ([docs/profile.md](../../docs/profile.md)) sets the provider and the priority the report is read against.
145
+
146
+ ## Sharing a lesson
147
+
148
+ After a fix has a measured before and after, or when a rule misled the user (it did not fit their app, or the fix changed answers), offer once to share what happened as a "lesson learned". It is an offer, not a step: say what it is, and never run it unasked. Only after the user says yes, run `npx leanprompt lesson --rule <id>` (add `--before <an older score.json>` when they kept one). It writes a draft to `.leanprompt/lesson.md` on their machine from the rule id, the target and the current score; it contains no code, paths, prompts or model output, and nothing is sent anywhere.
149
+
150
+ The user reads the exact text, edits it, and opens the issue themselves: the command prints a link to the "Lesson learned" form on GitHub, which carries no text from the draft, and the user pastes the draft into the form. A maintainer reads every submission before it informs a rule, and credit is optional ([THANKYOU.md](../../docs/THANKYOU.md)). If `lesson` reports something to remove (a key, an email, a path, a host name), help the user remove it and run it again; do not paste the removed text anywhere. Do not offer after a static score alone: there is no before and after to share.
151
+
152
+ ## What this skill does not do
153
+
154
+ It does not decide what to change (that is `prefill-cache`, `generation-economy` and `prompt-diet`), it does not make answers right (any change that can alter answers needs its own answer check), and it does not turn a small log into a trustworthy score.
@@ -0,0 +1,38 @@
1
+ // The helper for a CI test that fails when the stable head of your requests changes.
2
+ // Install: npm i -D @kvsig/core@0.1.0 (kvsig/1 and loose/1 ids; never assert on loose/2).
3
+ // Copy this file into your tests under a name of your own (for example test/stable-head.ts) and
4
+ // write the test beside it (for example test/stable-head.test.ts, any runner):
5
+ //
6
+ // import { assertStableHead } from "./stable-head";
7
+ // it("the head does not change from one day to the next", () =>
8
+ // assertStableHead(build, ["2026-11-01", "2026-11-02"], { sys: true, tools: true }));
9
+ //
10
+ // `build` is the function your app uses to build a request, returning { dialect, body }, and the
11
+ // inputs are two values that must NOT change the head (two dates, two users, two working directories).
12
+ import { canonicalize, ids, TEST_KEY, type Dialect } from "@kvsig/core";
13
+
14
+ export type Built = { dialect: Dialect; body: unknown };
15
+ export type Expect = { sys?: true; tools?: true; nodesUpTo?: number };
16
+
17
+ const idsOf = (b: Built) => {
18
+ const canon = canonicalize(b.body as never, b.dialect);
19
+ if (canon === null) throw new Error(`kvsig could not identify the request (dialect ${b.dialect}); is it a supported dialect, under 2 MiB, valid JSON?`);
20
+ return ids(canon, TEST_KEY);
21
+ };
22
+
23
+ export function assertStableHead<T>(build: (input: T) => Built, inputs: [T, T], expect: Expect): void {
24
+ const [a, b] = [idsOf(build(inputs[0])), idsOf(build(inputs[1]))];
25
+ const bad: string[] = [];
26
+ if (expect.sys && a.sys !== b.sys)
27
+ bad.push(a.loose_sys === b.loose_sys
28
+ ? "`sys` differs, `loose_sys` equal: the system prompt changed only in noise (a date line, a reminder, whitespace)"
29
+ : "`sys` differs, `loose_sys` differs: the system prompt changed in content the loose form does not treat as noise (a labelled date or time, an id, a path, wording)");
30
+ if (expect.tools && a.tools !== b.tools)
31
+ bad.push(a.loose_tools === b.loose_tools
32
+ ? "`tools` differs, `loose_tools` equal: the tool list changed only in the member order inside a schema or arguments"
33
+ : "`tools` differs, `loose_tools` differs: a tool was added, removed, edited or reordered");
34
+ for (let i = 0; i < (expect.nodesUpTo ?? 0); i++)
35
+ if (a.nodes[i] !== b.nodes[i]) { bad.push(`\`nodes[${i}]\` differs: the prompt up to message ${i} changed (a history message was rewritten, or the head above changed)`); break; }
36
+ if (bad.length) throw new Error(`The stable head changed between the two inputs:\n- ${bad.join("\n- ")}`);
37
+ }
38
+
@@ -0,0 +1,40 @@
1
+ """The helper for a CI test that fails when the stable head of your requests changes.
2
+
3
+ Install: pip install kvsig==0.1.0 pytest (kvsig/1 and loose/1 ids; never assert on loose/2).
4
+ Copy this file into your tests under a name of your own (for example tests/stable_head.py) and
5
+ write the test beside it (for example tests/test_stable_head.py):
6
+
7
+ from stable_head import assert_stable_head
8
+
9
+ def test_head_does_not_change_from_one_day_to_the_next():
10
+ assert_stable_head(build, ["2026-11-01", "2026-11-02"], {"sys": True, "tools": True})
11
+
12
+ `build` is the function your app uses to build a request, returning (dialect, body), and the
13
+ inputs are two values that must NOT change the head (two dates, two users, two working directories).
14
+ """
15
+ from kvsig import SUPPORTED, TEST_KEY, canonicalize, ids
16
+
17
+
18
+ def _ids_of(dialect, body):
19
+ canon = canonicalize(body, dialect) if dialect in SUPPORTED else None
20
+ if canon is None:
21
+ raise AssertionError(f"kvsig could not identify the request (dialect {dialect}); is it a supported dialect, under 2 MiB, valid JSON?")
22
+ return ids(canon, TEST_KEY)
23
+
24
+
25
+ def assert_stable_head(build, inputs, expect):
26
+ a, b = (_ids_of(*build(x)) for x in inputs)
27
+ bad = []
28
+ if expect.get("sys") and a.sys != b.sys:
29
+ bad.append("`sys` differs, `loose_sys` equal: the system prompt changed only in noise (a date line, a reminder, whitespace)"
30
+ if a.loose_sys == b.loose_sys else "`sys` differs, `loose_sys` differs: the system prompt changed in content the loose form does not treat as noise (a labelled date or time, an id, a path, wording)")
31
+ if expect.get("tools") and a.tools != b.tools:
32
+ bad.append("`tools` differs, `loose_tools` equal: the tool list changed only in the member order inside a schema or arguments"
33
+ if a.loose_tools == b.loose_tools else "`tools` differs, `loose_tools` differs: a tool was added, removed, edited or reordered")
34
+ for i in range(expect.get("nodes_up_to", 0)):
35
+ if a.nodes[i] != b.nodes[i]:
36
+ bad.append(f"`nodes[{i}]` differs: the prompt up to message {i} changed (a history message was rewritten, or the head above changed)")
37
+ break
38
+ if bad:
39
+ raise AssertionError("The stable head changed between the two inputs:\n- " + "\n- ".join(bad))
40
+
@@ -0,0 +1,65 @@
1
+ ---
2
+ name: prefill-cache
3
+ description: Use when writing, reviewing or debugging code that builds LLM requests (system prompt, tool list, message history, compaction, cache marks, thinking settings) for Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra or a self-hosted vLLM or SGLang server, or when a provider reports few or no cached prompt tokens (cached_tokens, cache_read_input_tokens). Makes the prompt reusable by the provider's prefix cache without changing what it means.
4
+ license: CC-BY-4.0
5
+ ---
6
+
7
+ # prefill-cache
8
+
9
+ Makes prompts that the provider's cache can reuse, so the app stops paying full price to prefill the same tokens on every call. Twelve rules, `LP-PC-01` to `LP-PC-12`, each in its own file under `rules/`, each with a way to detect it in code, the smallest fix, what the fix must not break, and how to verify it.
10
+
11
+ Every prefix cache works the same way: it matches the rendered prompt from the first token and stops at the first byte that differs. Everything after that byte is recomputed and billed at the full input price. The rules below are all ways of keeping the early bytes identical from one request to the next, plus the marks and routing some providers need on top.
12
+
13
+ ## When to use
14
+
15
+ - You are writing or changing the code that builds a request: the system prompt, the tool list, the history store, compaction, cache marks, thinking or effort settings, model or provider routing.
16
+ - A provider reports few or no cached tokens on a chat, an agent loop, or a batch that repeats a long prompt.
17
+ - The `llm-call-audit` skill sends you here for an `LP-PC-*` finding.
18
+
19
+ Caching never changes answers, so it applies whatever the project's priority is (cost, speed or quality). Rules that move or reword content (LP-PC-02, LP-PC-03, LP-PC-07) do need an answer check; each says so under "Don't break meaning".
20
+
21
+ ## Workflow
22
+
23
+ 1. **Know the target.** Read `leanprompt.yaml` if the project has one (`target`, `priority`). Otherwise infer the provider and model from the SDK, `base_url` and model names, and ask if it is unclear. Open that provider's table from the list below.
24
+ 2. **Find where the prompt is built.** From each LLM call, follow `system`, `tools` and `messages` back to the code that builds them: system-prompt builders, tool registries and MCP clients, the history store, compaction, request options (`thinking`, `reasoning_effort`, `tool_choice`, `prompt_cache_key`), cache marks, and model or provider selection.
25
+ 3. **Check each rule,** in the order of the index below (highest typical impact first). Each rule's "Detect in code" gives `rg` patterns and code shapes for Python, TS/JS and Go. Open a rule file when its pattern matches.
26
+ 4. **Propose the fix.** Give the rule id, file and line, and the smallest change from the rule's "Fix", with its "Don't break meaning" check. When you are reviewing existing code, propose and ask before editing. When you are writing the prompt builder now, apply the rules directly.
27
+ 5. **Verify.** Use the rule's "Verify": (a) the provider's usage field across two requests, and (b) the kvsig id that must stay equal. The `measure-loop` skill turns (b) into a CI test that fails when the stable head changes.
28
+
29
+ ## Provider facts, in brief
30
+
31
+ The numbers (minimums, step and block sizes, lifetimes, prices, limits) live only in the dated tables; read them there, not from memory.
32
+
33
+ - **Anthropic.** Caches only at `cache_control` breakpoints, or with top-level automatic caching that places one breakpoint for you; without marks nothing is cached (E1). Tools render first, then system, then messages. A prompt shorter than the model's minimum is silently not cached. Two lifetimes; writes cost a premium and reads a fraction of input, so marks follow the break-even rule in LP-PC-01. Thinking settings are part of the prompt. [providers/anthropic.md](../../providers/anthropic.md), [models/anthropic-thinking.md](../../models/anthropic-thinking.md)
34
+ - **OpenAI.** Automatic above a minimum, reported in fixed steps (E2). System before tools is observed, not documented: in the replay test behind E3 the system-prompt part stayed cached when only the tool list changed (render-order row in the table). `prompt_cache_key` groups requests that share a prefix. Recent models add optional explicit breakpoints and lifetime options. `tool_choice: "none"` drops the tools from the rendered prompt. [providers/openai.md](../../providers/openai.md), [models/openai-reasoning.md](../../models/openai-reasoning.md)
35
+ - **Gemini.** Implicit caching on current models, plus explicit cache objects with a lifetime and storage billing for large shared context. Documented, not yet measured here. [providers/gemini.md](../../providers/gemini.md)
36
+ - **OpenRouter.** A router, not a cache: hits depend on the upstream provider, so keep a conversation on one provider. Cache marks are passed through and translated between dialects; send them for Anthropic and Gemini models (E1). [providers/openrouter.md](../../providers/openrouter.md)
37
+ - **DeepInfra.** Automatic, with an optional `prompt_cache_key` and, on some models, explicit retention (E2, E3). [providers/deepinfra.md](../../providers/deepinfra.md)
38
+ - **vLLM and SGLang (self-hosted).** Automatic prefix caching in whole blocks or pages, so the tail of every prompt is recomputed. Hybrid models can have very large blocks, and speculative decoding drops one more (E9). With several replicas, reuse needs the request to reach the replica that holds the prefix (the `lmwarden` skill). [providers/vllm.md](../../providers/vllm.md), [providers/sglang.md](../../providers/sglang.md), [models/qwen.md](../../models/qwen.md)
39
+
40
+ Evidence rows (E1 to E12) are in [docs/evidence.md](../../docs/evidence.md). A rule whose only source is provider documentation says "documented, not yet measured here".
41
+
42
+ ## Rules
43
+
44
+ | Id | Rule | Severity | Evidence |
45
+ |---|---|---|---|
46
+ | [LP-PC-01](rules/LP-PC-01.md) | Put cache marks where the provider needs them | high | E1 |
47
+ | [LP-PC-02](rules/LP-PC-02.md) | Stable content first, without hurting meaning | high | E6 |
48
+ | [LP-PC-03](rules/LP-PC-03.md) | No ids, timestamps, versions or paths at the top of the prompt | high | E4, E5 |
49
+ | [LP-PC-04](rules/LP-PC-04.md) | Fixed tool order and JSON key order | high | provider docs |
50
+ | [LP-PC-05](rules/LP-PC-05.md) | Tool lists grow only at the end | medium | E3 |
51
+ | [LP-PC-06](rules/LP-PC-06.md) | Append-only history | high | provider docs |
52
+ | [LP-PC-07](rules/LP-PC-07.md) | Shared context before per-user context | medium | provider docs |
53
+ | [LP-PC-08](rules/LP-PC-08.md) | Cache-aware compaction | medium | provider docs |
54
+ | [LP-PC-09](rules/LP-PC-09.md) | Consistent reasoning handling; thinking fixed per session | high | E7, E11 |
55
+ | [LP-PC-10](rules/LP-PC-10.md) | Stable image and attachment placement | medium | provider docs |
56
+ | [LP-PC-11](rules/LP-PC-11.md) | Keep pauses inside the cache lifetime | low | provider docs |
57
+ | [LP-PC-12](rules/LP-PC-12.md) | Do not split one prefix across models or keys that do not share a cache | medium | provider docs |
58
+
59
+ ## Reading kvsig ids
60
+
61
+ kvsig gives each request keyed ids: `sys` (system prompt), `tools` (tool list), `head` (both), `msgs[i]` (one message), `nodes[i]` (the whole prompt up to message `i`) and `conv` (the conversation). Use exact ids for caching questions. Two requests with equal exact `nodes[i]` have the same prompt up to message `i`. The loose forms ignore noise such as date lines, reminders, whitespace, reasoning and key order inside tool schemas, so "loose equal, exact different" tells you the change was only noise. Assert only on `kvsig/1` exact ids and `loose/1` ids. The table of what changed between two requests is in kvsig's `docs/reading-the-ids.md`.
62
+
63
+ ## What this skill does not do
64
+
65
+ It does not change how much the model generates (that is `generation-economy`), it does not cut dead weight from what each call sends (that is `prompt-diet`), it does not tune engine settings or replica routing on a self-hosted server (that is `lmwarden`), and it does not promise a saving for an app it has not measured.
@@ -0,0 +1,102 @@
1
+ ---
2
+ id: LP-PC-01
3
+ title: Put cache marks where the provider needs them
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openrouter, openai, deepinfra, gemini]
6
+ saves: prefill
7
+ severity: high
8
+ evidence: [E1]
9
+ ---
10
+ ## Rule
11
+ On a provider that caches only at marks, put a cache mark at the end of each stable part of the prompt, and only on parts that will be read again within the cache lifetime.
12
+
13
+ ## Why
14
+ Anthropic caches a prefix only at a `cache_control` breakpoint, or with top-level automatic caching, which places one breakpoint for you. Without marks nothing is cached and every turn pays the full input price. Coding-agent sessions that sent no `cache_control` to an Anthropic model through a router cached 0 tokens on 29 turns, while sessions that set 3 breakpoints cached almost all of their reusable prefix (E1).
15
+
16
+ Anthropic renders tools, then system, then messages. A read looks back from a mark for the longest prefix already written, so three marks cover a conversation: the last tool, the end of the system prompt, and the newest message. The breakpoint limit and the lookback limit are in [providers/anthropic.md](../../../providers/anthropic.md).
17
+
18
+ A router does not add marks for you. OpenRouter forwards marks and translates them between dialects, so an OpenAI-shaped client that talks to an Anthropic or Gemini model through it still has to send them ([providers/openrouter.md](../../../providers/openrouter.md)). Automatic caches (OpenAI, DeepInfra, vLLM, SGLang) need no marks; recent OpenAI models and some DeepInfra models also accept optional explicit breakpoints with their own write price ([providers/openai.md](../../../providers/openai.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). Gemini's explicit cache objects are a separate mechanism with storage billing ([providers/gemini.md](../../../providers/gemini.md)).
19
+
20
+ **Break-even rule.** A mark is not free. Where cache writes cost a premium, a prefix that is written and not read again within the lifetime costs more marked than unmarked. Take the write multiplier `w` and the read multiplier `r` from the provider's table (both relative to the base input price). A marked prefix pays back when it is read, on average, more than `(w − 1) / (1 − r)` times per write within the lifetime. Mark the head of a chat or agent loop. Do not mark a one-shot prompt that never repeats. For prefixes reused at long intervals, compare a longer lifetime (a higher `w`) with rewriting at the default one (LP-PC-11).
21
+
22
+ ## Detect in code
23
+ Find every Anthropic call, direct or routed, and check whether `tools`, `system` and the newest message carry a mark.
24
+
25
+ Python:
26
+ ```
27
+ rg -n 'anthropic\.(Anthropic|AsyncAnthropic|AnthropicBedrock|AnthropicVertex)\(|messages\.(create|stream)\(' -g '*.py'
28
+ rg -n 'cache_control' -g '*.py'
29
+ rg -n 'openrouter\.ai|"anthropic/|"google/' -g '*.py'
30
+ ```
31
+ Shapes: `client.messages.create(system=SYSTEM_PROMPT, ...)` with `system` as a plain string and no `cache_control` anywhere in the call; the OpenAI SDK with `base_url` on a router and an `anthropic/...` or `google/...` model, with string `content` (a string cannot carry a mark).
32
+
33
+ TS/JS:
34
+ ```
35
+ rg -n '@anthropic-ai/sdk|messages\.(create|stream)\(|cache_control|cacheControl' -g '*.{ts,tsx,js,mjs}'
36
+ ```
37
+ Shapes: `system: "..."` as a string; Vercel AI SDK calls to an Anthropic model with no `providerOptions: { anthropic: { cacheControl: ... } }` on any message; `fetch(".../v1/messages", ...)` bodies without `"cache_control"`.
38
+
39
+ Go:
40
+ ```
41
+ rg -n 'anthropic-sdk-go|Messages\.New\(|CacheControl|/v1/messages' -g '*.go'
42
+ ```
43
+ Shapes: `anthropic.MessageNewParams{System: ...}` with no `CacheControl` on any `TextBlockParam` or `ToolParam`; raw `http.NewRequest` to `/v1/messages` whose JSON has no `cache_control`.
44
+
45
+ Over-marking, the opposite finding: a mark on a block that holds per-request content (a timestamp, the user's question), or marks on a one-shot call whose prompt never repeats. Apply the break-even rule.
46
+
47
+ ## Fix
48
+ Python, Anthropic SDK. The marks are added to copies at send time, so the stored history stays byte-identical (LP-PC-06).
49
+
50
+ ```python
51
+ # before
52
+ resp = client.messages.create(
53
+ model=MODEL, max_tokens=MAX_TOKENS,
54
+ system=SYSTEM_PROMPT, tools=TOOLS, messages=history,
55
+ )
56
+
57
+ # after
58
+ EPHEMERAL = {"type": "ephemeral"}
59
+
60
+ def mark_last(items):
61
+ *rest, last = items
62
+ return [*rest, {**last, "cache_control": EPHEMERAL}]
63
+
64
+ def mark_last_message(messages):
65
+ *rest, last = messages
66
+ content = last["content"]
67
+ if isinstance(content, str):
68
+ content = [{"type": "text", "text": content}]
69
+ return [*rest, {**last, "content": mark_last(content)}]
70
+
71
+ resp = client.messages.create(
72
+ model=MODEL, max_tokens=MAX_TOKENS,
73
+ tools=mark_last(TOOLS), # 1: end of tools
74
+ system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": EPHEMERAL}], # 2: end of system
75
+ messages=mark_last_message(history), # 3: newest message
76
+ )
77
+ ```
78
+
79
+ TS/JS through a router with the OpenAI SDK: send `content` as parts so a part can carry the mark.
80
+
81
+ ```ts
82
+ // before
83
+ messages: [{ role: "system", content: SYSTEM_PROMPT }, ...history]
84
+ // after
85
+ messages: [
86
+ { role: "system", content: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }] },
87
+ ...history,
88
+ ]
89
+ ```
90
+
91
+ To choose a longer lifetime, add the `ttl` field documented in [providers/anthropic.md](../../../providers/anthropic.md), and only where the break-even rule favours it.
92
+
93
+ ## Don't break meaning
94
+ A mark does not change the text the model sees, so adding marks cannot change answers. Do not reorder or reword content to make a mark fit: that is LP-PC-02, and it needs an answer check. Do not convert content between string and parts in the stored history; convert at send time.
95
+
96
+ ## Verify
97
+ (a) Send two requests with the same marked prefix within the lifetime. On Anthropic the first reports `cache_creation_input_tokens` > 0 and the second `cache_read_input_tokens` close to the marked prefix. Through OpenRouter read `prompt_tokens_details.cached_tokens` and `cache_write_tokens`. If both stay 0 with no error, check the prompt against the model's minimum cacheable length in [providers/anthropic.md](../../../providers/anthropic.md); below it nothing is cached, marks or not.
98
+
99
+ (b) kvsig: the two requests have equal exact `head` (tools and system) and equal exact `nodes[i]` up to the marked message. Equal ids with `cache_read_input_tokens` of 0 is the E1 shape: the prefix was reusable and the marks were missing or misplaced.
100
+
101
+ ## Waste signal
102
+ Measured: lowers E (provider-cached tokens over reusable tokens). kvsig says the prefix was equal, the provider reports no read. Missing marks count against the app: leanprompt scores what the provider could have reused, and a mark is the app's to add. Static: a finding of severity high on each Anthropic call site, direct or routed, that sends no marks. Over-marking is reported with the break-even advice (mark, don't mark, longer lifetime, restructure).
@@ -0,0 +1,79 @@
1
+ ---
2
+ id: LP-PC-02
3
+ title: Stable content first, without hurting meaning
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: high
8
+ evidence: [E6]
9
+ ---
10
+ ## Rule
11
+ Put the content that is the same across requests first; make a dynamic value stable (a date instead of a timestamp) or move it into the newest user message together with the text that refers to it, and re-check answers after any reordering.
12
+
13
+ ## Why
14
+ Every prefix cache matches from the first token and stops at the first difference; everything after a changed byte is recomputed. Render order decides what "first" means: Anthropic renders tools, then system, then messages; on OpenAI and DeepInfra the system prompt appears to render before the tools (observed, not documented: the render-order rows in [providers/openai.md](../../../providers/openai.md) and [providers/deepinfra.md](../../../providers/deepinfra.md)); self-hosted engines follow the model's chat template, which you can read. A value that changes per request near the top (a timestamp, a user's name, the retrieved chunks for this query) makes the long stable text after it unreusable.
15
+
16
+ The obvious fix, "move everything dynamic to the end", is not always safe. Text that tells the model what a value means can end up far from the value, and answers that depend on it get worse. The general rule is therefore stable first without hurting meaning, not dynamic last (E6).
17
+
18
+ ## Detect in code
19
+ Look at every function that builds a system prompt or the first messages, and ask of each interpolated value: is it the same on the next request?
20
+
21
+ Python:
22
+ ```
23
+ rg -n 'datetime\.(now|utcnow)\(|time\.time\(|date\.today\(' -g '*.py'
24
+ rg -n -i '(system|instructions)\w*\s*=\s*f"' -g '*.py'
25
+ ```
26
+ Shapes: `system = f"Current time: {datetime.now().isoformat()}\n{INSTRUCTIONS}"`; `prompt = context + "\n\n" + INSTRUCTIONS` with retrieved chunks before the instructions; few-shot examples chosen per query and placed before fixed instructions.
27
+
28
+ TS/JS:
29
+ ```
30
+ rg -n 'new Date\(|Date\.now\(|toISOString\(' -g '*.{ts,tsx,js,mjs}'
31
+ rg -n 'system:\s*`|role:\s*"system"' -g '*.{ts,tsx,js,mjs}'
32
+ ```
33
+ Shapes: `` system: `Now: ${new Date().toISOString()}\n${INSTRUCTIONS}` ``; `[chunks.join("\n"), INSTRUCTIONS].join("\n\n")`.
34
+
35
+ Go:
36
+ ```
37
+ rg -n 'time\.Now\(\)|fmt\.Sprintf\(.*(system|System|prompt|Prompt)' -g '*.go'
38
+ ```
39
+ Shapes: `fmt.Sprintf(systemTmpl, time.Now().Format(time.RFC3339), instructions)`; `strings.Join([]string{retrieved, instructions}, "\n\n")`; a `text/template` whose first lines print request data.
40
+
41
+ ## Fix
42
+ Stabilise before you move.
43
+
44
+ 1. Coarsen the value: a date changes once a day, a timestamp on every call.
45
+ 2. If the value is truly per request (the question, the chunks retrieved for it), put it in the newest user message, together with the sentence that says what it is.
46
+ 3. Put long stable text (instructions, reference documents, examples) before short dynamic text.
47
+
48
+ ```python
49
+ # before
50
+ system = f"Current time: {datetime.now().isoformat()}\n{INSTRUCTIONS}\n\nContext:\n{chunks}"
51
+ messages = [{"role": "user", "content": question}]
52
+
53
+ # after
54
+ system = f"{INSTRUCTIONS}\n\nToday's date is {date.today().isoformat()}. Use it to resolve relative dates."
55
+ messages = [{"role": "user", "content": f"Context for this question:\n{chunks}\n\nQuestion: {question}"}]
56
+ ```
57
+
58
+ ```ts
59
+ // before
60
+ const system = `Now: ${new Date().toISOString()}\n${INSTRUCTIONS}`;
61
+ // after
62
+ const today = new Date().toISOString().slice(0, 10);
63
+ const system = `${INSTRUCTIONS}\n\nToday's date is ${today}. Use it to resolve relative dates.`;
64
+ ```
65
+
66
+ ## Don't break meaning
67
+ In the reorder experiment, moving date lines to the end of the prompt cut correct date answers from 10/12 to 1/12, lowered the control question too, and did not help caching (E6). A value must stay next to the text that tells the model how to use it: "Today's date is 2026-11-26. Use it to resolve relative dates." moves as one unit or not at all.
68
+
69
+ - After any reorder, run the app's answer check on a fixed input set before and after. A change that saves tokens and fails the check is not a fix.
70
+ - Coarsening a timestamp to a date changes meaning only if the app needs the time of day; then pass the time in the newest user message.
71
+ - Retrieved chunks moved into the user message must keep their label, and instructions that said "the context above" must still be true.
72
+
73
+ ## Verify
74
+ (a) Send two requests built for two different moments (or two users) that share the stable part. The second reports `cached_tokens` (OpenAI-compatible APIs, vLLM) or `cache_read_input_tokens` (Anthropic) covering the stable part.
75
+
76
+ (b) kvsig: build the request for two fixed `now` values (or two users) and compare. Exact `sys` must be equal when the date is unchanged; with the per-request part in the newest user message, `head` and every `nodes[i]` before that message are equal too. `loose_sys` equal with exact `sys` different means a date line or similar noise is still in the system prompt.
77
+
78
+ ## Waste signal
79
+ Measured: a value that changes on every turn lowers S, because each request shares little with the turn before; a value that changes per user or per day shows as more distinct `sys` and `head` ids than the app has prompts. Static: severity high when a per-call value (timestamp, id, query, retrieved chunks) comes before long stable text.