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,113 @@
1
+ # Report template: `leanprompt-report.md`
2
+
3
+ Write the report at the project root with the sections below, in this order. It follows the same order as the page `npx leanprompt report --html` writes: what is wrong and what it costs first, in plain English, then the hand-off for a coding agent, then the score and the detail. Replace every `<...>`; leave no placeholder in the written report. Keep the rule text out of it: link the rule file instead. The same content is what you present in the conversation ([presenting.md](presenting.md)); the file is the record.
4
+
5
+ The plain-English lines come from each finding's fields in `.leanprompt/findings.json` (`problem`, `change`, `why`, `estimate`, `assumptions`, `verify`), so the report, the page and the hand-off block say the same thing. Write them for a person who has not read the rule: no rule ids in the sentences, no jargon.
6
+
7
+ ````markdown
8
+ # leanprompt report: <project name>
9
+
10
+ <date> · leanprompt <version> · target: <provider or engine, model family> · priority: <cost | speed | quality | weights>
11
+
12
+ **<n> places where this app pays for tokens it doesn't need.** The biggest: <rule title, plain> at <file>:<line>, about <tokens> tokens per 1,000 calls. Together about <total tokens> tokens per 1,000 calls (<"estimate from the code, not a measurement" | "measured over N calls">).<If there are open questions:> Plus <n> open questions to confirm.
13
+
14
+ ## What this costs you
15
+
16
+ <With `volume:` and a dated price in leanprompt.yaml:>
17
+ About <$X> a month at <N> calls a month. Fixing these saves about <$X> a month (about <Y> of an estimated <$B> monthly bill). <Self-hosted, with `prefill_tokens_per_second`: about <H> hours of GPU prefill time a month, and <+s> on the first-token time of the calls the prefill findings affect.>
18
+
19
+ Inputs: volume <N> calls a month (<source>); <model> input <$>, cached input <$>, output <$> per 1M tokens, from <pricing page URL or the user's source>, checked <date>; average call <prompt> prompt and <output> output tokens. Every figure is an estimate from the code, not a measurement (or: measured over N calls).
20
+
21
+ <Without them:> Tokens per 1,000 calls only. To see this in money, add `volume: {calls_per_month: N}` and `prices:` for <model> (input, cached_input, output per 1M tokens, with source and checked date) to `leanprompt.yaml`. leanprompt never invents a volume or a price.
22
+
23
+ | Finding | Where | Tokens per 1,000 calls | A month |
24
+ |---|---|---|---|
25
+ | <rule id> | <file>:<line> | <n prompt, n not cached, n output> | <$, or blank without volume and price> |
26
+
27
+ ## What's wrong and what to change
28
+
29
+ Largest first, by estimated tokens lost per 1,000 calls. Findings that change price or latency but not tokens follow, in the order the priority gives them.
30
+
31
+ ### 1. <problem, in a few words> · <file>:<line>
32
+
33
+ - **Problem:** <`problem`: what is wrong, one or two plain sentences>
34
+ - **What to change:** <`change`; a short diff if it fits>
35
+ - **Why it matters:** <`why`: why it costs tokens or time>
36
+ - **Estimate:** <`estimate`>, tokens lost per 1,000 calls (<estimate | measured, N calls>)
37
+ - **Assumes:** <`assumptions`: call mix, tokens per call, how often this path runs>
38
+ - **Share:** <0.000> of <prompt | output> tokens = <tokens lost per 1,000 calls> ÷ <that side's tokens for the same 1,000 calls>. <Or: "severity default share: no estimate possible, because <reason>">
39
+ - **Don't break meaning:** <the rule's check for this fix, or "caching only: answers cannot change">
40
+ - **How to check the fix:** <`verify`: the usage field that must change and the kvsig id that must stay equal>; proved with `measure-loop`
41
+ - **Rule:** [<rule id> <rule title>](<link to the rule file>)
42
+ - **Status:** <open | fixed, with the before and after line | skipped | ignored in leanprompt.yaml>
43
+
44
+ ### Open questions
45
+
46
+ Findings outside this repository (`"<external>"`) or waiting on a fact (`needs-facts`), ranked the same way. They count in the score. Confirm or dismiss each one with its fact. Leave this heading out when there are none.
47
+
48
+ #### <n>. <problem, in a few words> · <where, for example "engine launch flags">
49
+
50
+ - **Problem:** <`problem`: why it may apply>
51
+ - **To confirm:** <the `confirm` text: the fact that would confirm or dismiss it, and where the user can read it>
52
+ - **Change, if confirmed:** <`change`>
53
+ - **Estimate:** <`estimate`> (estimate); <what it assumes about the missing fact>
54
+ - **Rule:** [<rule id> <rule title>](<link to the rule file>)
55
+ - **Status:** <open question | confirmed | dismissed>
56
+
57
+ ## Fix it with your coding agent
58
+
59
+ Paste this into Claude Code, Codex, Cursor or any coding assistant. It checks each finding against the code and proposes fixes one at a time, asking before it changes anything.
60
+
61
+ ```text
62
+ Please check and fix the LLM-call findings from a leanprompt audit of this repository.
63
+
64
+ 1. If the leanprompt skills are not installed for you here, install them: npx github:Podwarden/leanprompt install
65
+ 2. Read .leanprompt/findings.json and leanprompt-report.md. If they are missing, use the list below.
66
+ 3. Check each finding against the code before you change anything. The audit can be wrong: if a finding does not hold, tell me why and leave that code alone.
67
+ 4. Fix one finding at a time. Show me the change as a small diff and apply it only after I say yes.
68
+ 5. Prove each fix with the measure-loop skill: a before and after on the same scenario. Ask me before running anything that sends real, billed requests.
69
+ 6. When a fix is proved, set "fixed": true on its finding in .leanprompt/findings.json and run npx github:Podwarden/leanprompt score.
70
+
71
+ Findings, largest first:
72
+ 1. <rule id> at <file>:<line>: <problem>
73
+
74
+ Open questions (confirm before fixing):
75
+ - <rule id> (<where>): <problem> To confirm: <confirm>
76
+ ```
77
+
78
+ ## Score
79
+
80
+ <score> <kind>, from <".leanprompt/findings.json" | ".leanprompt/usage.jsonl, N calls (M unmeasured)">, <default | calibrated> weights. One number from 0 to 100 for how well the app avoids paying for the same tokens twice; higher is better.
81
+
82
+ <Static only:> <N> of <M> findings use a default share (`default_shares` in `.leanprompt/score.json`), the rest an estimated one.
83
+
84
+ | Input | Value | Meaning |
85
+ |---|---|---|
86
+ | E | <0.00> | prefill reuse (measured), or the prefill term from the findings (static) |
87
+ | S | <0.00> | prefix stability (measured); 1 in a static score |
88
+ | G | <0.00> | share of output tokens wasted |
89
+
90
+ <Measured only:> Heads: <distinct_head> distinct heads over <conversations> conversations. <One line: expected, or which finding it points to.>
91
+
92
+ <Static only:> This score is an estimate from code. A trial run with `npx leanprompt calibrate` fits it to this app.
93
+
94
+ Money is not part of the score.
95
+
96
+ ## Inventory
97
+
98
+ | # | File | Provider | Model | Call kind | Notes |
99
+ |---|---|---|---|---|---|
100
+ | 1 | <path>:<line> | <provider, or "unknown: asked"> | <model> | <chat · agent loop · one-shot · batch> | <wrapper it goes through, router, framework> |
101
+
102
+ ## Next steps
103
+
104
+ 1. <The fix to do first and why: the biggest leak, or the one the priority favours>
105
+ 2. <Prove it with `measure-loop`: the scenario to run, the field to watch>
106
+ 3. <Turn on the usage logger to get a measured score, if there is no log yet>
107
+ 4. <Calibrate the static score, if it is static>
108
+ 5. <Add volume and prices to `leanprompt.yaml`, if the report shows tokens only>
109
+ 6. <The page: `npx leanprompt report --html` writes `.leanprompt/report.html` with the same content and the copyable hand-off block>
110
+ ````
111
+
112
+ Write the numbers with their kind every time: "(estimate)" next to a figure from code, "(measured, N calls)" next to a figure from the usage log. A static score is never presented as measured, and money is shown only from the user's own volume and a price with its source and checked date; never invent either.
113
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,97 @@
1
+ ---
2
+ name: lmwarden
3
+ description: Use when an app calls a model it hosts itself (vLLM, SGLang, llama.cpp, LM Warden or another OpenAI-compatible server on your own GPUs) and prefix-cache reuse is low, a hybrid model reuses only part of a prompt, several replicas serve one model, or several apps or tenants share one server; also when deciding whether to self-host at all. Covers engine settings that change reuse, keeping a conversation on the replica that holds its cache, keys and cache isolation, and reading the engine facts from LM Warden into leanprompt.yaml.
4
+ license: CC-BY-4.0
5
+ ---
6
+
7
+ # lmwarden
8
+
9
+ What to do when the model runs on your own hardware: when that is the right choice, which engine settings change prefix-cache reuse, how to keep a conversation on the replica that holds its cache, and how to share one server between apps without mixing their usage or their caches. Three rules, `LP-LW-01` to `LP-LW-03`, each in its own file under `rules/`.
10
+
11
+ LM Warden is the self-hosted server the LM Warden Team makes, and it is one option among several here. The rules apply to any self-hosted engine unless a rule says otherwise. The `prefill-cache` skill covers the prompt itself; this skill covers the server it is sent to.
12
+
13
+ ## When to use
14
+
15
+ - The app calls a model on hardware you run, and the cached share of prompt tokens is low.
16
+ - A hybrid model reuses only part of a long prompt, or reuse falls short of what kvsig says was reusable.
17
+ - One model runs as several replicas, and conversations reuse less than they should.
18
+ - Several apps or tenants use one server and you need per-consumer usage, or need to keep their caches apart.
19
+ - You are deciding whether to self-host at all.
20
+ - The `llm-call-audit` skill sends you here for an `LP-LW-*` finding.
21
+
22
+ Caching never changes answers, so these rules apply whatever the project's priority is. A change to routing or engine flags is an operations change: propose it and ask before editing a server's launch configuration.
23
+
24
+ ## Does self-hosting pay
25
+
26
+ Self-hosting tends to pay when traffic is steady, many requests share a long prefix, the data must not leave your host, and you already own NVIDIA GPUs. It tends not to pay with no GPU, with spiky and low traffic (an idle GPU still costs), or when the work needs a frontier model that cannot be self-hosted. This skill does not price either side; the cost of a hosted call comes from [providers/](https://github.com/Podwarden/leanprompt/tree/v0.1.0-dev.8/providers/) and the cost of a GPU from your own bill.
27
+
28
+ ## The options
29
+
30
+ | Option | What it is | What this repo has on it |
31
+ |---|---|---|
32
+ | vLLM | Inference engine with automatic prefix caching in blocks | [providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md) (E9) |
33
+ | SGLang | Inference engine with a radix-tree prefix cache | [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md), documented, not yet measured here |
34
+ | llama.cpp | Inference engine for GGUF models, CPU or GPU | accepted as `target.engine` in [leanprompt.yaml](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/docs/profile.md); no cache table yet |
35
+ | Ollama | Local model runner built on llama.cpp | no table here |
36
+ | LM Warden | A server that runs vLLM and llama.cpp behind one OpenAI-compatible port on your NVIDIA GPUs | its facts are read from its own API (below); it uses the vLLM table |
37
+ | Hosted APIs | Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra | [providers/](https://github.com/Podwarden/leanprompt/tree/v0.1.0-dev.8/providers/) |
38
+
39
+ Pick on your hardware, models and operations, not on this table. Running vLLM or SGLang directly is a reasonable choice when you want one engine and already have the tooling around it.
40
+
41
+ ### What LM Warden adds, and what it does not
42
+
43
+ It adds:
44
+
45
+ - **Lifecycle.** Models are started, stopped and switched from one control plane instead of by hand-written launch commands.
46
+ - **Per-key accounting.** A key per consumer, each with its own usage figures (LP-LW-03).
47
+ - **Cache-aware routing.** For a model that runs as several data-parallel vLLM replicas, a conversation is placed on one replica and kept there (LP-LW-02).
48
+
49
+ It does not:
50
+
51
+ - **Make a model faster.** The engine does the generation; LM Warden does not change it. What E10 measures is reuse of a cache that would otherwise be rebuilt.
52
+ - **Span hosts.** It is one host.
53
+ - **Run without NVIDIA GPUs.** It is NVIDIA only, so a Mac, an AMD card or a CPU-only box is a different choice from the table above.
54
+
55
+ The routing result, with its limits (E10): on one box of four NVIDIA RTX A4000 cards serving Qwen3-4B, under a synthetic Claude Code-shaped load of 8 concurrent agent sessions with one run per arm, cache-aware routing took the median time to first byte from 2.33 s to 0.48 s, the share of prompt tokens served from cache from 44% to 86%, and output tokens a minute up 29% (8,364 to 10,752) (E10). At 24 and more sessions, where the cards were overloaded either way, the median time to first byte was worse with routing on (E10). It is an engine result, measured by LM Warden's authors, and not something a leanprompt rule achieves. Measure your own workload with routing on and off.
56
+
57
+ ## Workflow
58
+
59
+ 1. **Know the target.** Read `leanprompt.yaml` (`target.engine`, `engine:`; or the engine entries of `targets` when the app also calls a hosted API). If the project has none, infer the server from `base_url` and the launch files, and ask if it is unclear.
60
+ 2. **Get the engine facts.** For LM Warden, let the CLI read them instead of asking (next section). For vLLM or SGLang, read the block or page size and the speculative-decoding setting from the server's startup log and launch arguments, and put them under `engine:` ([docs/profile.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/docs/profile.md)).
61
+ 3. **Check each rule,** in the order of the index below. Each rule's "Detect in code" gives `rg` patterns and code shapes for launch files and for Python, TS/JS and Go clients.
62
+ 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 the launch configuration is not in this repository, the audit records the finding with `"file": "<external>"` and a `where`; when it hangs on an engine fact you do not have yet (the block size, the match unit), it also gets `status: "needs-facts"` and a `confirm` naming that fact.
63
+ 5. **Verify.** Use the rule's "Verify": the usage the server reports across two requests, and the kvsig ids that must stay equal. The `measure-loop` skill turns the second into a test.
64
+
65
+ ## Reading the engine facts from LM Warden
66
+
67
+ ```
68
+ export LMWARDEN_API_KEY=... # the inference key the app already uses
69
+ leanprompt profile detect --lmwarden https://lm.example.com [--token-env LMWARDEN_API_KEY] [--model <name>]
70
+ ```
71
+
72
+ This reads `GET <url>/api/me/engine` with the key as a bearer token and writes `block_tokens`, `match_unit_tokens` and `speculative` (true when the engine reports a speculative-decoding method) under `engine:` in `leanprompt.yaml`. It also sets `target.context_tokens` from `max_model_len` when the file does not already set it. Everything else in the file is kept. If there is no `leanprompt.yaml` it creates one with `target: {engine: lm-warden}`. In a profile with `targets:` it writes into the `lm-warden` entry (else the `vllm` entry, else it adds an `lm-warden` entry), under that entry's `engine_facts`, or under the top-level `engine:` when that block exists and the profile has one engine entry. A value the server cannot determine is left out and named in a printed note. If the key can use several models, pass `--model` or the command stops and lists their names.
73
+
74
+ Auto-detect needs an LM Warden release that has this endpoint. A server without it answers 404, and the command says so; then set the `engine:` block by hand from the engine's startup log (step 2 above). The command makes one request, to the URL you give, and never prints the key.
75
+
76
+ ## Prompt Lens (planned)
77
+
78
+ Prompt Lens is planned: an LM Warden view that names the first part of a prompt where reuse broke and what the miss cost, with an API and tools for assistants. Until it ships, find the break with kvsig ids (`prefill-cache`, "Reading kvsig ids") and the engine's cache statistics.
79
+
80
+ ## Rules
81
+
82
+ | Id | Rule | Severity | Evidence |
83
+ |---|---|---|---|
84
+ | [LP-LW-01](rules/LP-LW-01.md) | Turn on prefix caching and set the match unit | high | E9 |
85
+ | [LP-LW-02](rules/LP-LW-02.md) | Keep a conversation on the replica that holds its cache | medium | E10 |
86
+ | [LP-LW-03](rules/LP-LW-03.md) | One key per app or tenant; cache scope is a privacy boundary | medium | provider docs |
87
+
88
+ Evidence rows (E1 to E12) are in [docs/evidence.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/docs/evidence.md). A rule whose only source is documentation says "documented, not yet measured here".
89
+
90
+ ## Hardware notes
91
+
92
+ A longer context and more concurrent sequences take more KV-cache memory, and the cache that holds reusable prefixes competes for the same memory; that follows from how engines work and is untested here. Put the KV memory you have under `kv_memory_gb` in `engine:` when you know it ([docs/profile.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/docs/profile.md)). Engine flags change over versions: read the flag's meaning in your version's documentation before changing it.
93
+
94
+ ## What this skill does not do
95
+
96
+ It does not make the model faster, change how much it generates (that is `generation-economy`), or change the prompt (that is `prefill-cache`). It does not choose hardware, and it does not promise the E9 or E10 results for another model, card count or workload.
97
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,73 @@
1
+ ---
2
+ id: LP-LW-01
3
+ title: Turn on prefix caching and set the match unit
4
+ skill: lmwarden
5
+ applies_to: [vllm, sglang, lm-warden]
6
+ saves: prefill
7
+ severity: high
8
+ evidence: [E9]
9
+ ---
10
+ ## Rule
11
+ On a self-hosted engine, run with prefix caching on, and on a hybrid model set the prefix match unit (vLLM) or page size (SGLang) small enough that a prompt's tail is not thrown away.
12
+
13
+ ## Why
14
+ A block-mode prefix cache reuses whole blocks. The part of a prompt after the last full block is recomputed on every request, and an engine that drops one more block (speculative decoding does this on the hybrid model measured) recomputes that block too. With large blocks this is most of a short prompt. On one 4B hybrid model on one 16 GB card, the block was 1,584 tokens, and short prompts reused 44% of their tokens on an append-only workload (E9). With `--prefix-match-unit 16` on vLLM 0.32 the same workload reused 76%, against an ideal of 78%, with no change in decode speed (E9). That is one model, one card and thinking off; another model, engine version or card count can differ.
15
+
16
+ What the engine documents: `--prefix-match-unit` sets the granularity at which prefix-cache keys are computed. Unset, it defaults to the greatest common divisor of the cacheable block sizes, which on hybrid Mamba models is the block size; the docs suggest 64 as a starting point. On hybrid models a hit can resume only at a block boundary of the Mamba state, and the shared-prefix checkpoint option is off by default and works only with a match unit smaller than the Mamba block ([providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md)). SGLang matches at its `page_size`, and the radix tree splits a node for an exact boundary ([providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)), documented, not yet measured here. Whether prefix caching is on by default is not in the tables; check the launch arguments.
17
+
18
+ The same mechanism decides reuse in a one-shot app (a constant shared head, then a different body on every request, no history). Across requests only the full blocks inside the shared head can be reused, so a head shorter than one block reuses nothing on a block-mode engine, and when the per-request body is short, the extra block speculative decoding drops can fall inside the head too. This follows from the block mechanism measured with a block of 1,584 tokens (E9); one-shot traffic is not yet measured here. The question to ask is "is the shared head longer than one block, plus one more with speculative decoding on?", and a smaller match unit is what lowers that bar.
19
+
20
+ A non-hybrid model usually has a small block and little to gain from the match unit; the first step there is only to confirm caching is on.
21
+
22
+ ## Detect in code
23
+ Look at how the server is launched, and at code that launches it. The client code does not show this.
24
+
25
+ Launch files (compose, Kubernetes, systemd, shell, Makefile):
26
+ ```
27
+ rg -n 'vllm serve|vllm\.entrypoints|--no-enable-prefix-caching|--enable-prefix-caching|--prefix-match-unit|--enable-mamba-shared-prefix-checkpoint' .
28
+ rg -n 'sglang\.launch_server|--page-size|page_size' .
29
+ rg -n 'speculative|--speculative-config|mtp|eagle' .
30
+ ```
31
+ Shapes: a `vllm serve` command with `--no-enable-prefix-caching`; a hybrid model (a Qwen model whose `chat_template` or `config.json` names Mamba or linear-attention layers) with speculative decoding on and no `--prefix-match-unit`.
32
+
33
+ Python, TS/JS, Go: code that starts an engine as a subprocess (`subprocess.Popen(["vllm", "serve", ...])`, `spawn("vllm", ...)`, `exec.Command("vllm", ...)`) carries the same arguments; apply the same patterns to its argument lists.
34
+
35
+ For a one-shot app (no chat history) on a hybrid model, estimate the shared head's length in tokens (system prompt plus tool definitions, everything before the per-request text) and compare it with the block size from the engine's startup log or `leanprompt.yaml` `engine.block_tokens`. A head shorter than one block, or shorter than two when speculative decoding is on and the per-request body is short, is a finding even when the client code is already cache-friendly.
36
+
37
+ Check the data too: a self-hosted app whose cached share is low while kvsig says the prefix was equal (`prefill-cache`, "Reading kvsig ids"), with the shortfall close to the block size.
38
+
39
+ For LM Warden the engine facts are reported by the server; run `leanprompt profile detect` (see the skill; it needs a release with that endpoint) instead of reading launch files.
40
+
41
+ ## Fix
42
+ Confirm caching is on, then add the match unit for a hybrid model. Start from a value the engine's documentation suggests and measure; 16 is the value measured in E9, on one model.
43
+
44
+ ```bash
45
+ # before
46
+ vllm serve Qwen/<hybrid-model> --speculative-config '{"method": "mtp", "num_speculative_tokens": 2}'
47
+
48
+ # after
49
+ vllm serve Qwen/<hybrid-model> --enable-prefix-caching --prefix-match-unit 16 \
50
+ --speculative-config '{"method": "mtp", "num_speculative_tokens": 2}'
51
+ ```
52
+
53
+ Then record what the engine reports in `leanprompt.yaml`, so the scorer uses the real granularity:
54
+
55
+ ```yaml
56
+ target: {engine: vllm}
57
+ engine:
58
+ block_tokens: 1584
59
+ match_unit_tokens: 16
60
+ speculative: true
61
+ ```
62
+
63
+ ## Don't break meaning
64
+ Prefix caching does not change answers. The match unit changes what is stored and where a hit can resume, not what the model computes, but it is an engine setting with costs this skill has not measured beyond E9 (which saw no change in decode speed): watch memory headroom and decode speed after the change, and roll back if either moves. Restart the engine to apply it, which empties its cache and drops live conversations' warm prefixes. Do it in a quiet window and tell the people who use the server.
65
+
66
+ ## Verify
67
+ (a) Send the same long conversation twice, appending a short turn each time. Before the change the second request reports cached tokens only up to a block boundary (`cached_tokens` in the usage, where the server reports it, or the engine's prefix-cache hit counters); after it, `cached_tokens` is close to the previous turn's full prompt.
68
+
69
+ (b) kvsig: the two requests have equal exact `nodes[i]` up to the previous turn. The share of the reusable prefix that was actually cached should rise toward the ideal; E9 went from 44% to 76% of prompt tokens on its workload, against 78% ideal (E9). Run the same conversation before and after, on the same model and engine version.
70
+
71
+ ## Waste signal
72
+ Measured: raises E (provider-cached tokens over reusable tokens) for short prompts on a block-mode engine; the scorer treats the last partial block as the engine's rule and not as the app's, using the `engine:` values (docs/profile.md). A shortfall much larger than one block counts against the app. Static: a finding of severity high where a hybrid model runs with speculative decoding and no match unit, or with prefix caching turned off; low where the model is not hybrid and caching is on.
73
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,78 @@
1
+ ---
2
+ id: LP-LW-02
3
+ title: Keep a conversation on the replica that holds its cache
4
+ skill: lmwarden
5
+ applies_to: [vllm, lm-warden]
6
+ saves: prefill
7
+ severity: medium
8
+ evidence: [E10]
9
+ ---
10
+ ## Rule
11
+ When one model runs as several replicas, send every request of a conversation to the same replica, and send the same stable conversation key with each of them, so the cache the previous turn built is the one the next turn reads.
12
+
13
+ ## Why
14
+ Each replica has its own prefix cache. A balancer that places each request on the least busy replica, with no memory of the conversation, sends turn two to a replica that has never seen turn one's prompt, and that replica prefills it from scratch. An agent resends its whole history every turn, so the miss is large and repeats. Placing a conversation on one replica and keeping it there gives the next turn a warm cache.
15
+
16
+ The result, with its limits (E10): on one box of four NVIDIA RTX A4000 cards serving Qwen3-4B, under a synthetic Claude Code-shaped load of 8 concurrent agent sessions with one run per arm, routing conversations to their replica took the median time to first byte from 2.33 s to 0.48 s, prompt tokens served from cache from 44% to 86%, and output tokens a minute up 29% (E10). At 24 and more sessions, where the cards were saturated either way, the median time to first byte was worse with routing on (E10). It is a result for the engine's routing on one small setup, not for a change in your code, and one run per arm is not a distribution. Measure your own load with routing on and off; LM Warden can turn it off per model.
17
+
18
+ What the app controls is the key. LM Warden's routing reads a session or conversation id from the request (for example an `X-Session-Id` header or the body's `prompt_cache_key`; its routing write-up lists the order), and without one it falls back to a hash of the first user message. A client that sends a fresh random id on every request, or none and an unstable first message, defeats it. Other balancers differ: this skill has not checked them, so read your balancer's documentation for what it keys on.
19
+
20
+ ## Detect in code
21
+ Find code that sends requests to a multi-replica or load-balanced self-hosted endpoint and see what identifies the conversation.
22
+
23
+ Python:
24
+ ```
25
+ rg -n 'itertools\.cycle|random\.choice\(.*(urls|hosts|endpoints)|base_url=.*(urls|hosts)\[' -g '*.py'
26
+ rg -n 'uuid4\(\)|uuid\.uuid4' -g '*.py'
27
+ rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|session_id' -g '*.py'
28
+ ```
29
+ Shapes: a list of base URLs, one per replica, that the client cycles through per request; a `uuid4()` placed in a header or in `prompt_cache_key` on every call instead of once per conversation.
30
+
31
+ TS/JS:
32
+ ```
33
+ rg -n 'randomUUID\(\)|Math\.random\(\)' -g '*.{ts,tsx,js,mjs}'
34
+ rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|sessionId' -g '*.{ts,tsx,js,mjs}'
35
+ rg -n 'baseURL|endpoints\[|urls\[.*%' -g '*.{ts,tsx,js,mjs}'
36
+ ```
37
+ Shapes: `urls[i++ % urls.length]` choosing a replica per request; `crypto.randomUUID()` in a per-request header.
38
+
39
+ Go:
40
+ ```
41
+ rg -n 'rand\.Intn\(len\(|uuid\.New\(\)|atomic\.AddUint(32|64)' -g '*.go'
42
+ rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|SessionID' -g '*.go'
43
+ ```
44
+ Shapes: a round-robin counter over replica URLs; `uuid.New().String()` set per request.
45
+
46
+ Not a finding: a single replica (nothing to route), a stateless one-shot call with no history, and a server that routes on something the client already sends.
47
+
48
+ ## Fix
49
+ Create the key once per conversation and send it on every turn; send every turn to the same endpoint (the server's one URL, not a list of replicas).
50
+
51
+ ```python
52
+ # before: a new id per request, and a client-side round-robin across replicas
53
+ headers = {"X-Session-Id": str(uuid.uuid4())}
54
+ client = OpenAI(base_url=next(REPLICA_URLS), api_key=KEY)
55
+
56
+ # after: one id per conversation, one URL
57
+ class Conversation:
58
+ def __init__(self):
59
+ self.session_id = str(uuid.uuid4()) # created once
60
+ def headers(self):
61
+ return {"X-Session-Id": self.session_id}
62
+
63
+ client = OpenAI(base_url=SERVER_URL, api_key=KEY) # the server places the conversation
64
+ ```
65
+
66
+ Pin a key to an endpoint, do not hash a key onto a replica yourself: the server knows each replica's load.
67
+
68
+ ## Don't break meaning
69
+ The key is not part of the prompt, so answers do not change. Keeping conversations on one replica concentrates load: a replica can hold more long conversations than its neighbours, and when every replica is saturated the median wait can get worse (E10). Check the median and the tail under your peak load, not only on a quiet box, and keep the option to turn routing off. Do not put the key in the prompt text, where it would change the cache key.
70
+
71
+ ## Verify
72
+ (a) Send several turns of one conversation. With the key stable, each turn's `cached_tokens` (where the server reports it) is close to the previous turn's whole prompt; with a fresh key per request it is near zero on turns that land on another replica. The server's own per-replica counters (LM Warden's model page shows how many requests stayed on their home replica) show where the requests went.
73
+
74
+ (b) kvsig: the turns have equal exact `nodes[i]` up to the previous turn, so a low cached count with equal ids points at placement or the engine (LP-LW-01), not at the prompt. The leanprompt usage record has no replica field, so it cannot show which replica answered; use the server's counters for that.
75
+
76
+ ## Waste signal
77
+ Measured: lowers E on conversations whose prefix kvsig says was equal and that the server did not reuse; the log cannot say whether placement was the cause, so check the server's counters before reporting it. Static: severity medium where a client rotates across replica URLs or sends a per-request random conversation key to a multi-replica server; none for a single replica.
78
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,73 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
73
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,155 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md) (its SDK examples name a different field, so check the response you get), [providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md), [providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
155
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->