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,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
+ // leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits
@@ -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
+ # leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits
@@ -0,0 +1,66 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [models/anthropic-thinking.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [models/openai-reasoning.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md)
37
+ - **DeepInfra.** Automatic, with an optional `prompt_cache_key` and, on some models, explicit retention (E2, E3). [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md), [models/qwen.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/qwen.md)
39
+
40
+ 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 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.
66
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,103 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)). Gemini's explicit cache objects are a separate mechanism with storage billing ([providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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).
103
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,80 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md) and [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
80
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,75 @@
1
+ ---
2
+ id: LP-PC-03
3
+ title: No ids, timestamps, versions or paths at the top of the prompt
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: high
8
+ evidence: [E4, E5]
9
+ ---
10
+ ## Rule
11
+ Keep request and session ids, timestamps, version strings, hostnames and filesystem paths out of the first lines of the system prompt and out of tool definitions; put them in the newest user message, or at least after all the stable text.
12
+
13
+ ## Why
14
+ Inside one session these values do not change, so the loss is across sessions: every new session, subagent, user or deploy pays for the whole head again, up to the first line that differs.
15
+
16
+ - A coding harness writes the working directory into its long system prompt. Across sessions in different directories a self-hosted vLLM reused only the 7,920 tokens before that line (E5).
17
+ - Another harness puts a per-session version suffix and the working directory on its first system line. Anthropic still reused 12,895 tokens across sessions, because it renders tools first and the tools were equal; a route that renders the system prompt first loses everything after line 1 (E4).
18
+
19
+ Render order decides how much survives: tools, then system, then messages on Anthropic ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)); system before tools on OpenAI and DeepInfra as observed, not documented (render-order rows in [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md) and [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)); on a self-hosted engine, whatever the model's chat template says. A path or id in a tool description breaks the tool block itself, which on Anthropic comes before everything else. Dates are the mild case (they change once a day; LP-PC-02); ids and timestamps change every session or every call.
20
+
21
+ ## Detect in code
22
+ Python:
23
+ ```
24
+ rg -n 'os\.getcwd\(|Path\.cwd\(|socket\.gethostname\(|platform\.(node|platform)\(|uuid\.uuid4\(|__version__|importlib\.metadata\.version\(' -g '*.py'
25
+ ```
26
+ Shapes: `f"You are running in {os.getcwd()} on {platform.platform()}"` as the opening of the system prompt; `f"Session {session_id}. ..."`; a tool `description=f"Read files under {root}"`.
27
+
28
+ TS/JS:
29
+ ```
30
+ rg -n 'process\.cwd\(|os\.hostname\(|crypto\.randomUUID\(|randomUUID\(|npm_package_version|pkg\.version|Date\.now\(' -g '*.{ts,tsx,js,mjs}'
31
+ ```
32
+ Shapes: `` `${AGENT_NAME} v${pkg.version} (${sessionId})\n` `` as the first system line; `` description: `Search ${process.cwd()}` ``.
33
+
34
+ Go:
35
+ ```
36
+ rg -n 'os\.Getwd\(|os\.Hostname\(|uuid\.New(String)?\(|runtime\.Version\(|time\.Now\(\)|\bversion\b.*Sprintf' -g '*.go'
37
+ ```
38
+ Shapes: `fmt.Sprintf("agent %s, cwd %s\n%s", version, wd, basePrompt)`; a `Tool{Description: "Files in " + root}`.
39
+
40
+ ## Fix
41
+ Move the values into a labelled environment block in the first user message (best: the whole head stays equal across sessions), or at least to the end of the system prompt (the provider still reuses the bytes before it).
42
+
43
+ ```python
44
+ # before
45
+ system = f"agent {VERSION} session {session_id}\nWorking directory: {os.getcwd()}\n{BASE_PROMPT}"
46
+ tools = [{"name": "read_file", "description": f"Read a file under {root}", ...}]
47
+
48
+ # after
49
+ system = BASE_PROMPT + "\n\nThe working directory and environment are given in the first user message."
50
+ tools = [{"name": "read_file", "description": "Read a file under the working directory", ...}]
51
+ env = f"<environment>\nWorking directory: {os.getcwd()}\n</environment>"
52
+ first_user = {"role": "user", "content": f"{env}\n\n{task}"}
53
+ ```
54
+
55
+ ```go
56
+ // before
57
+ sys := fmt.Sprintf("agent %s, cwd %s\n%s", version, wd, basePrompt)
58
+ // after
59
+ sys := basePrompt
60
+ first := fmt.Sprintf("<environment>\nWorking directory: %s\n</environment>\n\n%s", wd, task)
61
+ ```
62
+
63
+ Keep the version out of the prompt entirely unless the model needs it; log it instead.
64
+
65
+ ## Don't break meaning
66
+ The model still needs the value. Keep it labelled ("Working directory: ..."), and update any instruction that pointed at it by position ("the directory above"). A tool description that named a path must still be correct in general terms, with the concrete path given in the environment block. Run the app's answer check on a task that depends on the moved value.
67
+
68
+ ## Verify
69
+ (a) Start two sessions that differ only in the moved value (two directories, two versions). The first request of the second session reports `cached_tokens` or `cache_read_input_tokens` covering the stable head.
70
+
71
+ (b) kvsig: the first requests of the two sessions have equal exact `tools` and `sys`, so equal `head`. If the value was moved only to the end of the system prompt, `sys` still differs: verify with (a) instead.
72
+
73
+ ## Waste signal
74
+ Measured: the score's S counts only requests that continue an earlier one, so this cross-session loss shows mostly as many distinct `head` ids among the first requests of an app whose head should be one, and as a short shared prefix on each first request. Static: severity high for a per-session or per-call value in the first lines of the system prompt or in a tool definition.
75
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,79 @@
1
+ ---
2
+ id: LP-PC-04
3
+ title: Fixed tool order and JSON key order
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: high
8
+ evidence:
9
+ - doc: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
10
+ checked: 2026-11-26
11
+ - doc: https://developers.openai.com/api/docs/guides/prompt-caching
12
+ checked: 2026-11-26
13
+ ---
14
+ ## Rule
15
+ Build the tool list in one fixed order and serialise every JSON value in the prompt (tool schemas, tool-call arguments, tool results, structured context) the same way every time.
16
+
17
+ ## Why
18
+ The tool list is part of the prefix: first on Anthropic; after the system prompt on OpenAI and DeepInfra as observed, not documented (render-order rows in [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md) and [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)); wherever the chat template puts it on a self-hosted engine. A different tool order, or the same schema with its keys in a different order, is a different prompt even though it means the same thing. On Anthropic a change to the tool definitions invalidates tools, system and messages ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)); OpenAI requires the whole rendered prefix to match ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)). Documented, not yet measured here.
19
+
20
+ Common causes: a registry filled in import or plugin-load order; MCP servers whose tools are listed in registration order, which depends on which server connected first; tools collected from concurrent discovery in completion order; a `set` of tools; Go `map` iteration, which is randomised on every run; dicts built in varying order and dumped without sorting; a schema generator whose field order changed between library versions.
21
+
22
+ ## Detect in code
23
+ Python:
24
+ ```
25
+ rg -n -i 'registry\.(values|items)\(\)|for .* in .*(tools|registry)|set\(.*tool|as_completed\(|json\.dumps\(' -g '*.py'
26
+ ```
27
+ Shapes: `tools = [t.schema() for t in REGISTRY.values()]` where `REGISTRY` is filled by decorators at import time; `tools = list({*base_tools, *mcp_tools})`; MCP tools gathered with `asyncio.as_completed` and appended in arrival order; `json.dumps(result)` on a dict whose keys arrive in varying order, or `json.dumps(..., sort_keys=False)` in one path and `sort_keys=True` in another.
28
+
29
+ TS/JS:
30
+ ```
31
+ rg -n 'Object\.(keys|values|entries)\((registry|tools)|new Set\(|Promise\.race\(|JSON\.stringify\(' -g '*.{ts,tsx,js,mjs}'
32
+ ```
33
+ Shapes: `tools: Object.values(registry)` with `registry` filled as servers connect; `for await (const server of servers) tools.push(...await server.listTools())`; objects assembled from spreads in different orders before `JSON.stringify`.
34
+
35
+ Go:
36
+ ```
37
+ rg -n 'for .*range .*(tools|Tools|registry)|map\[string\].*Tool' -g '*.go'
38
+ ```
39
+ Shapes: `for _, t := range toolsByName { params.Tools = append(params.Tools, t) }` over a `map`; goroutines appending discovered tools to a shared slice under a mutex.
40
+
41
+ ## Fix
42
+ Fix the order once at session start (sorting by name is the easy way) and serialise canonically.
43
+
44
+ ```python
45
+ # before
46
+ tools = [t.schema() for t in REGISTRY.values()]
47
+ content = json.dumps(result)
48
+ # after
49
+ tools = [REGISTRY[name].schema() for name in sorted(REGISTRY)]
50
+ content = json.dumps(result, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
51
+ ```
52
+
53
+ ```ts
54
+ // before
55
+ const tools = Object.values(registry);
56
+ // after
57
+ const tools = Object.keys(registry).sort().map((name) => registry[name]);
58
+ ```
59
+
60
+ ```go
61
+ // before
62
+ for _, t := range toolsByName { tools = append(tools, t) }
63
+ // after
64
+ for _, name := range slices.Sorted(maps.Keys(toolsByName)) { tools = append(tools, toolsByName[name]) }
65
+ ```
66
+
67
+ A tool loaded later in the session goes at the end, not into its sorted position (LP-PC-05). Serialise a tool result once, when it is first added to the history, and keep that string (LP-PC-06).
68
+
69
+ ## Don't break meaning
70
+ Some models favour tools listed earlier. If the existing order was deliberate (the most important tool first), keep that order and make it fixed rather than sorting. After a change of order, run the app's tool-choice check on a fixed set of tasks. Key order inside JSON does not change its meaning; field descriptions and `required` lists must stay as they were.
71
+
72
+ ## Verify
73
+ (a) Restart the process (new registration order, new map iteration) and send the same first request before and after the restart. The second reports `cached_tokens` or `cache_read_input_tokens` covering the tool list.
74
+
75
+ (b) kvsig: exact `tools` is equal across two runs of the app. `loose_tools` equal with exact `tools` different means only the member order inside schemas or arguments changed (the loose form ignores it): a key-order problem, not a tool-order one.
76
+
77
+ ## Waste signal
78
+ Measured: order that varies per process or per conversation shows as several `tools` ids for one tool set and a short shared prefix on first requests; order that varies per call inside a conversation lowers S. Static: severity high for a tool list built by iterating a map, set or registry without a fixed order, medium for unsorted JSON serialisation of content that goes back into the prompt.
79
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,68 @@
1
+ ---
2
+ id: LP-PC-05
3
+ title: Tool lists grow only at the end
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: medium
8
+ evidence: [E3]
9
+ ---
10
+ ## Rule
11
+ When a tool is added during a session, append it after the existing tools and never insert, remove or re-sort; on a provider that renders tools first (Anthropic), declare the full tool set at session start instead.
12
+
13
+ ## Why
14
+ On caches that render the system prompt before the tools (observed for OpenAI and DeepInfra, not documented: render-order rows in [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md) and [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)), appending a tool at the end keeps everything before it: after one deferred tool was appended, DeepInfra still cached 10,176 of 21,149 prompt tokens (E3). Inserting the tool in the middle, or re-sorting, loses everything after the insertion point.
15
+
16
+ Anthropic renders tools first, so any change to the tool list also invalidates the system prompt and the messages after it. The same append cached 0 there, with no breakpoint in front of the change (E3). A mark on the last original tool should keep at least that tool block, because marks are written at a block boundary. This is untested: E3 had no breakpoint in front of the change, and the docs do not describe this case ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)). Even if it works, the system prompt and history are recomputed once.
17
+
18
+ The shapes that do this: an MCP server that connects mid-session, a tool loaded on demand (tool search, a skill or plugin activated by the conversation), tools filtered per turn by relevance to the current message. A related case: on OpenAI, `tool_choice: "none"` drops the tool definitions from the rendered prompt, so switching `tool_choice` between turns changes the prefix ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)).
19
+
20
+ ## Detect in code
21
+ Python:
22
+ ```
23
+ rg -n 'tools\.insert\(|tools\s*=\s*(select|filter|relevant)\w*\(|tool_choice\s*=.*if ' -g '*.py'
24
+ ```
25
+ Shapes: `tools = relevant_tools(user_message)` on every turn; `tools.insert(0, new_tool)`; `tools = sorted(tools + [new_tool], key=...)` after an on-demand load; `tool_choice="none" if final_turn else "auto"`.
26
+
27
+ TS/JS:
28
+ ```
29
+ rg -n 'tools\.(unshift|splice)\(|tools\s*=\s*\w*(select|filter|relevant)\w*\(|toolChoice|tool_choice' -g '*.{ts,tsx,js,mjs}'
30
+ ```
31
+ Shapes: `tools.unshift(loaded)`; `tools: pickTools(input)` per call; `client.on("connect", s => tools = [...s.tools, ...tools])`.
32
+
33
+ Go:
34
+ ```
35
+ rg -n 'append\(\[\]\w*Tool\w*\{|slices\.Insert\(|sort\.Slice\(tools|ToolChoice' -g '*.go'
36
+ ```
37
+ Shapes: `tools = append([]Tool{loaded}, tools...)` (a prepend); `slices.Insert(tools, i, loaded)`; `sort.Slice(tools, ...)` after a load.
38
+
39
+ ## Fix
40
+ Keep the base list fixed for the session and append.
41
+
42
+ ```python
43
+ # before
44
+ tools = sorted([*tools, loaded], key=lambda t: t["name"])
45
+ # after
46
+ tools = [*tools, loaded] # the base list keeps its order; new tools go last
47
+ ```
48
+
49
+ ```ts
50
+ // before
51
+ const tools = pickTools(userMessage); // a different subset every turn
52
+ // after
53
+ const tools = ALL_TOOLS; // one list for the session; steer with instructions
54
+ ```
55
+
56
+ On Anthropic, load every tool the session may need before the first request. If a late tool cannot be avoided, a mark on the last original tool (LP-PC-01) may keep the tool block; this is untested here, so check it with step (a) of Verify before relying on it.
57
+
58
+ ## Don't break meaning
59
+ More tools in view can change which tool the model picks, so run the app's tool-choice check on a fixed set of tasks after declaring tools up front. Tools gated for permission or safety stay gated: a tool the user may not use must not be exposed to save cache. Enforce the gate in the code that executes tool calls and say so in the instructions, or keep the gated tools out of the session's list from the start. Replacing per-turn filtering with one list needs the same tool-choice check.
60
+
61
+ ## Verify
62
+ (a) Load a tool mid-session. On automatic caches the next request still reports `cached_tokens` covering the system prompt and the tools before the new one. On Anthropic with all tools declared at start, `cache_read_input_tokens` covers the previous turn on every request. If you rely on a mark on the last original tool instead, the request after the append must report `cache_read_input_tokens` of at least the original tool block; if it reports 0, the workaround does not hold for your model, so declare all tools at the start.
63
+
64
+ (b) kvsig: inside one conversation (`conv`), `sys` is equal on every turn and `tools` changes only on the turns where a tool was added (the "same conv, sys equal, tools differ" case). On Anthropic, `tools` is equal on every turn of the session.
65
+
66
+ ## Waste signal
67
+ Measured: each tool change lowers S on the turn where it happens; per-turn filtering lowers it on most turns. Static: severity medium for an on-demand load, a prepend or a re-sort, and for per-turn filtering or a per-turn `tool_choice` switch.
68
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->