leanprompt 0.0.0-stage → 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 +89 -2
  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 +32 -4
  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,74 @@
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](../../../providers/anthropic.md)); system before tools on OpenAI and DeepInfra as observed, not documented (render-order rows in [providers/openai.md](../../../providers/openai.md) and [providers/deepinfra.md](../../../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.
@@ -0,0 +1,78 @@
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](../../../providers/openai.md) and [providers/deepinfra.md](../../../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](../../../providers/anthropic.md)); OpenAI requires the whole rendered prefix to match ([providers/openai.md](../../../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.
@@ -0,0 +1,67 @@
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](../../../providers/openai.md) and [providers/deepinfra.md](../../../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](../../../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](../../../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.
@@ -0,0 +1,70 @@
1
+ ---
2
+ id: LP-PC-06
3
+ title: Append-only history
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
+ Send every earlier message byte for byte as it was sent before, and add new content only at the end.
16
+
17
+ ## Why
18
+ A turn can reuse the cache only if every message before it is identical to what was sent last time. A rewrite at message `k` makes everything after `k` a miss, and a rewrite that happens on every call makes every turn a miss. The provider docs require the whole rendered prefix to match ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md)). Documented, not yet measured here.
19
+
20
+ The rewrites that cause it are rarely deliberate:
21
+ - history re-serialised from objects or database rows on each call (different whitespace, key order or number formatting);
22
+ - `.strip()` or Markdown re-rendering of old messages;
23
+ - a reminder or "current state" block updated inside an old message, or inserted in the middle;
24
+ - old tool results truncated in place to stay under a budget;
25
+ - conversion between SDK message types (for example Responses items to Chat Completions messages) on each call.
26
+
27
+ ## Detect in code
28
+ Python:
29
+ ```
30
+ rg -n 'messages\[\d+\]\s*=|history\[-?\d+\]\[.content.\]\s*\+?=|messages\.insert\(|\.strip\(\)|model_dump\(|json\.dumps\(' -g '*.py'
31
+ ```
32
+ Shapes: `messages = [to_api(row) for row in db.load(conv_id)]` on every call, where `to_api` formats content; `for m in history: m["content"] = render(m)`; `history[0]["content"] += reminder`; `result[:MAX_CHARS]` applied to all old tool results on each call.
33
+
34
+ TS/JS:
35
+ ```
36
+ rg -n 'messages\.splice\(|history\.map\(|\.trim\(\)|JSON\.stringify\(\w+,\s*null,\s*\d' -g '*.{ts,tsx,js,mjs}'
37
+ ```
38
+ Shapes: `history.map(m => ({ ...m, content: render(m) }))` before each request; `JSON.stringify(result, null, 2)` when the tool result is first shown and `JSON.stringify(result)` when history is rebuilt.
39
+
40
+ Go:
41
+ ```
42
+ rg -n 'json\.MarshalIndent\(|strings\.TrimSpace\(|messages\[\w+\]\s*=' -g '*.go'
43
+ ```
44
+ Shapes: `[]Message` rebuilt from the store each call with `fmt.Sprintf`; `json.MarshalIndent` in one path and `json.Marshal` in another for the same tool result.
45
+
46
+ ## Fix
47
+ Store exactly what was sent, and replay it.
48
+
49
+ ```python
50
+ # before
51
+ messages = [{"role": r.role, "content": render(r)} for r in store.load(conv_id)]
52
+ messages[0]["content"] += f"\n\n<reminder>{state()}</reminder>"
53
+
54
+ # after
55
+ messages = store.load_sent(conv_id) # the exact dicts sent last time, stored after each send
56
+ messages.append({"role": "user", "content": f"<reminder>{state()}</reminder>\n\n{user_input}"})
57
+ ```
58
+
59
+ Truncate or redact a tool result once, when it is added, never later. Keep cache marks off the stored copies (LP-PC-01 adds them at send time).
60
+
61
+ ## Don't break meaning
62
+ If the app rewrote history to keep the model informed (an updated plan, the current state), say the same thing in a new message at the end and state that it supersedes the earlier one; do not silently drop it. If old messages were trimmed to fit the context window, trim by compaction (LP-PC-08), not on every call. Redaction for privacy still happens, once, before the first send.
63
+
64
+ ## Verify
65
+ (a) In a multi-turn session, each request reports `cached_tokens` or `cache_read_input_tokens` close to the previous request's prompt size, less the tail the engine rounds away (step and block sizes in the provider tables).
66
+
67
+ (b) kvsig: for consecutive requests A and B of one conversation, `B.nodes` starts with all of `A.nodes`. A shorter shared prefix points at the first rewritten message: the index where the two `nodes` lists first differ.
68
+
69
+ ## Waste signal
70
+ Measured: lowers S, the share of prompt tokens that requests continuing a conversation could reuse. Static: severity high for history rebuilt or modified on every call, medium for a one-off rewrite (a single insertion or truncation point).
@@ -0,0 +1,96 @@
1
+ ---
2
+ id: LP-PC-07
3
+ title: Shared context before per-user context
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: medium
8
+ evidence:
9
+ - doc: https://developers.openai.com/api/docs/guides/prompt-caching
10
+ checked: 2026-11-26
11
+ - doc: https://docs.deepinfra.com/chat/prompt-caching.md
12
+ checked: 2026-11-26
13
+ ---
14
+ ## Rule
15
+ In an app that serves many users or tenants, put what is the same for everyone (instructions, tools, shared reference documents, examples) before anything specific to a tenant, then a user, then a request.
16
+
17
+ ## Why
18
+ A cache is shared between requests only up to the first byte that differs. If the system prompt opens with "You are helping Alice at Acme" and then carries a long shared handbook, every user gets a private copy of the handbook in cache and every user's first request pays for it again. Ordered from widest to narrowest audience (everyone, tenant, user, request), each layer is reused by everyone who shares it. OpenAI and DeepInfra both ask for stable content first; OpenAI's `prompt_cache_key` groups requests that share a prefix, and it should name the group that shares it (for example the tenant), not a single request ([providers/openai.md](../../../providers/openai.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). Documented, not yet measured here.
19
+
20
+ Order is not enough if a per-user transform runs over the whole rendered prompt afterwards. A redaction step that replaces a requester's name, email or account number wherever it occurs, or a template pass that fills per-user placeholders across every message, also rewrites the shared head whenever the same value happens to appear there (a customer whose name is also a product name, a name that is also a word in the instructions). For those requests the head differs from everyone else's and is paid for again. This follows from prefix matching; not yet measured here. It is rare in any one request, invisible without comparing kvsig ids across users, and more likely the more name-like terms the shared text contains.
21
+
22
+ On a self-hosted server a cache shared across tenants is also a privacy question; see the `lmwarden` skill (keys, isolation, `cache_salt`).
23
+
24
+ ## Detect in code
25
+ Python:
26
+ ```
27
+ rg -n 'f"(You are|Hello|Hi)[^"]*\{(user|customer|tenant|account)' -g '*.py'
28
+ ```
29
+ ```
30
+ rg -n 'redact|scrub|anonymi[sz]e|presidio|mask_pii|pii' -g '*.py'
31
+ ```
32
+ Shapes: `system = f"You are assisting {user.name} ({user.plan}).\n{HANDBOOK}"`; `messages = [redact(m, user) for m in [system_msg, *msgs]]` or `scrub(render(prompt), names=[user.name])` (a per-user transform over the whole prompt, shared head included); `system = user_profile + SHARED_DOCS`; few-shot examples picked per user and placed before the shared instructions; `prompt_cache_key=request_id`.
33
+
34
+ TS/JS:
35
+ ```
36
+ rg -n '`(You are|Hello|Hi)[^`]*\$\{(user|customer|tenant|account)|prompt_cache_key' -g '*.{ts,tsx,js,mjs}'
37
+ ```
38
+ ```
39
+ rg -n 'redact|scrub|anonymi[sz]e|maskPii|pii' -g '*.{ts,tsx,js,mjs}'
40
+ ```
41
+ Shapes: `` system: `Customer: ${customer.name}\n${HANDBOOK}` ``; `messages.map((m) => redact(m, requester))` applied to the system message too; `prompt_cache_key: crypto.randomUUID()`.
42
+
43
+ Go:
44
+ ```
45
+ rg -n 'Sprintf\("(You are|User|Customer|Tenant)[^"]*%s' -g '*.go'
46
+ ```
47
+ ```
48
+ rg -n '(?i)redact|scrub|anonymi[sz]e|pii' -g '*.go'
49
+ ```
50
+ Shapes: `fmt.Sprintf("User: %s\n%s", u.Name, sharedDocs)` as the system prompt; a `Redact(prompt, user)` call on the fully rendered prompt.
51
+
52
+ ## Fix
53
+ Layer from the widest audience to the narrowest.
54
+
55
+ ```python
56
+ # before
57
+ system = f"You are assisting {user.name} at {tenant.name}.\n\n{INSTRUCTIONS}\n\n{HANDBOOK}"
58
+
59
+ # after
60
+ system = f"{INSTRUCTIONS}\n\n{HANDBOOK}" # same for every user
61
+ first_user = (
62
+ f"<tenant>{tenant.name}: {tenant.notes}</tenant>\n"
63
+ f"<user>{user.name}, plan {user.plan}</user>\n\n{question}"
64
+ )
65
+ ```
66
+
67
+ ```ts
68
+ // before
69
+ prompt_cache_key: crypto.randomUUID(),
70
+ // after
71
+ prompt_cache_key: `tenant:${tenant.id}`, // one key per group that shares the prefix
72
+ ```
73
+
74
+ Apply per-user transforms (redaction, per-user templating) only to the per-user parts, then put the shared head in front unchanged.
75
+
76
+ ```python
77
+ # before: the scrubber sees the whole prompt, shared head included
78
+ messages = scrub([{"role": "system", "content": SYSTEM}, {"role": "user", "content": request_text}], names=[requester.name])
79
+
80
+ # after: scrub only what is per request; the shared head is never transformed per user
81
+ messages = [{"role": "system", "content": SYSTEM},
82
+ {"role": "user", "content": scrub(request_text, names=[requester.name])}]
83
+ ```
84
+
85
+ When a tenant has a large block of its own (its documents), it can go at the end of the system prompt, after the shared part, so that tenant's users share it.
86
+
87
+ ## Don't break meaning
88
+ The model must still know whom it serves: keep the user and tenant blocks labelled, and update instructions that referred to them by position. If per-user settings are meant to override the shared defaults, say so in the user block ("These preferences take precedence over the defaults above"). Run the answer check on a few personalised cases before and after. Moving redaction off the shared head must not let personal data through: the shared head must hold none to begin with (it is the same for everyone), and every per-user part must still pass through the transform. If the head does contain personal data, remove it from the head; do not keep scrubbing it per user.
89
+
90
+ ## Verify
91
+ (a) Send the first request for user A, then for user B. B's request reports `cached_tokens` or `cache_read_input_tokens` covering the shared part.
92
+
93
+ (b) kvsig: build the first request for two users. Exact `tools` and `sys` are equal, so `head` is equal; the per-user part starts at the first message. Where a per-user transform runs, pick two users whose values also occur in the shared text (a name that is also a product term) and check that `sys` and `head` are still equal after the transform.
94
+
95
+ ## Waste signal
96
+ Measured: first requests of different users share a short prefix with each other; the score's S counts only continuing requests, so the loss shows as many `sys` or `head` ids for one shared prompt. Static: severity medium for per-user or per-tenant values before long shared text, low for a `prompt_cache_key` that is unique per request, low for a per-user transform run over the shared head (it costs only on the requests whose values occur in the head).
@@ -0,0 +1,66 @@
1
+ ---
2
+ id: LP-PC-08
3
+ title: Cache-aware compaction
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
6
+ saves: prefill
7
+ severity: medium
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
+ When you compact a long conversation, keep the system prompt and the tool list byte-identical and put the summary in the messages after them, and run the summarising call as a continuation of the same prompt.
16
+
17
+ ## Why
18
+ Compaction replaces the history with a summary, so the message part is recomputed once whatever you do. If the compaction also rewrites the system prompt (appending "Summary of the conversation so far: ..." to it) or rebuilds the tool list, the head is lost too, on every compaction. On Anthropic, tools and system render before messages, so an unchanged head stays cached across the compaction ([providers/anthropic.md](../../../providers/anthropic.md)). Documented, not yet measured here.
19
+
20
+ The summarising call itself is the second cost. Sent with its own system prompt ("You are a summariser") over the full history, it pays for the whole history again. Sent as the same head and history plus a final instruction to summarise, it reads the cache that the last turn wrote.
21
+
22
+ ## Detect in code
23
+ Python:
24
+ ```
25
+ rg -n '(system|system_prompt)\s*\+=|summary|summari[sz]e|compact' -g '*.py'
26
+ ```
27
+ Shapes: `system_prompt += f"\n\nEarlier conversation:\n{summary}"`; `client.messages.create(system="Summarise this conversation.", messages=history)`; tools rebuilt from the registry after compaction (LP-PC-04).
28
+
29
+ TS/JS:
30
+ ```
31
+ rg -n 'system\w*\s*\+=|system\w*\s*=\s*`\$\{\w+\}.*summary|summari[sz]e|compact' -g '*.{ts,tsx,js,mjs}'
32
+ ```
33
+ Shapes: `` systemPrompt = `${BASE}\n\n${summary}` ``; a summariser request with a different `system` and the full `messages`.
34
+
35
+ Go:
36
+ ```
37
+ rg -n 'sys(tem)?\w*\s*\+=|sys(tem)?\w*\s*=\s*\w+\s*\+\s*.*summary|Summari[sz]e|Compact' -g '*.go'
38
+ ```
39
+ Shapes: `sys = basePrompt + "\n" + summary`.
40
+
41
+ ## Fix
42
+ ```python
43
+ # before
44
+ summary = client.messages.create(system="Summarise this conversation.", messages=history, ...)
45
+ system = BASE_PROMPT + "\n\nSummary of the conversation so far:\n" + text_of(summary)
46
+ history = []
47
+
48
+ # after
49
+ ask = {"role": "user", "content": "Summarise the conversation so far for your own later use."}
50
+ summary = client.messages.create(system=BASE_PROMPT, tools=TOOLS, messages=[*history, ask], ...)
51
+ system = BASE_PROMPT # unchanged, byte for byte
52
+ history = [{"role": "user", "content": "Summary of the conversation so far:\n" + text_of(summary)}]
53
+ ```
54
+
55
+ Keep the tools exactly as they were (same list, same order, same serialisation). To stop the summarising call from calling a tool, say so in the instruction rather than changing `tool_choice`: on OpenAI `"none"` drops the tools from the rendered prompt, and on Anthropic a `tool_choice` change invalidates the message blocks ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md)).
56
+
57
+ ## Don't break meaning
58
+ The summary must still be read as context: label it ("Summary of the conversation so far"), and if the system prompt used to say how to treat the summary, keep that instruction in the stable system prompt. A summariser call made as a continuation sees the agent's own instructions; ask for a summary in plain terms, and compare a few post-compaction answers on a fixed long conversation before and after the change.
59
+
60
+ ## Verify
61
+ (a) The request right after a compaction reports `cached_tokens` or `cache_read_input_tokens` of at least the head (tools and system). The summarising call reports a read close to the size of the history it summarised.
62
+
63
+ (b) kvsig: `head` (and `sys`, `tools`) is equal before and after the compaction. `conv` changes, as expected: kvsig reads it as "different conv, same sys". The summarising call's `nodes` start with all of the last pre-compaction request's `nodes`.
64
+
65
+ ## Waste signal
66
+ Measured: compaction starts a new `conv`, so the score's S does not see it; it shows as a new `sys` right after a long conversation where the same `sys` was expected, and as a summarising call with a short shared prefix. Static: severity medium for a summary written into the system prompt or a summariser call with its own system prompt.
@@ -0,0 +1,74 @@
1
+ ---
2
+ id: LP-PC-09
3
+ title: Consistent reasoning handling; thinking fixed per session
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, vllm, sglang, openrouter]
6
+ saves: both
7
+ severity: high
8
+ evidence: [E7, E11]
9
+ ---
10
+ ## Rule
11
+ Decide once per session whether thinking is on, at what budget or effort, and how earlier reasoning is carried in the history, and keep all three the same on every turn.
12
+
13
+ ## Why
14
+ Chat templates and providers render earlier assistant turns differently depending on the thinking setting, so a setting that changes between turns changes the prefix behind them.
15
+
16
+ - On a self-hosted Qwen hybrid model, toggling thinking on and off between turns of one session lost 47% of what those turns could have reused; turns with the same setting as the turn before lost nothing (E7). The template rules are in [models/qwen.md](../../../models/qwen.md).
17
+ - On Anthropic, the thinking mode and budget are rendered into the prompt, and changing either invalidates the message blocks ([models/anthropic-thinking.md](../../../models/anthropic-thinking.md)).
18
+ - On OpenAI reasoning models, reasoning items returned with tool calls are meant to be passed back in their original order ([models/openai-reasoning.md](../../../models/openai-reasoning.md)).
19
+
20
+ Stripping reasoning from history to save tokens changes the prefix from the first stripped turn on, and it can cost more than it saves: in agent loops it produced about 3x more generation (E11).
21
+
22
+ The shapes: a router that turns thinking on for "hard" turns only; an effort level picked per request by a heuristic; a history store that keeps only the final text of each assistant turn.
23
+
24
+ ## Detect in code
25
+ Python:
26
+ ```
27
+ rg -n 'enable_thinking|reasoning_effort|budget_tokens|thinking=|reasoning_content|"thinking"' -g '*.py'
28
+ ```
29
+ Shapes: `extra_body={"chat_template_kwargs": {"enable_thinking": is_hard(msg)}}`; `reasoning_effort=pick_effort(msg)`; `thinking={"type": "enabled", "budget_tokens": budget_for(turn)}`; `m.pop("reasoning_content", None)` or `[b for b in content if b.type != "thinking"]` when saving history.
30
+
31
+ TS/JS:
32
+ ```
33
+ rg -n 'enable_thinking|reasoning_effort|reasoningEffort|budget_tokens|thinking:|reasoning_content|type !== "thinking"' -g '*.{ts,tsx,js,mjs}'
34
+ ```
35
+ Shapes: `reasoning_effort: hard ? "high" : "low"`; `content.filter(b => b.type !== "thinking")`; `delete msg.reasoning_content`.
36
+
37
+ Go:
38
+ ```
39
+ rg -n 'EnableThinking|ReasoningEffort|BudgetTokens|ReasoningContent|Thinking' -g '*.go'
40
+ ```
41
+ Shapes: `ReasoningEffort: effortFor(turn)`; history rebuilt from `resp.Choices[0].Message.Content` only, dropping the reasoning field.
42
+
43
+ ## Fix
44
+ Fix the setting on the session object, and store each assistant turn as it came back.
45
+
46
+ ```python
47
+ # before
48
+ kwargs = {"enable_thinking": is_hard(user_msg)}
49
+ history.append({"role": "assistant", "content": msg.content}) # reasoning dropped
50
+
51
+ # after
52
+ kwargs = {"enable_thinking": session.thinking} # chosen once, at session start
53
+ history.append(msg.model_dump(exclude_none=True)) # reasoning kept as returned
54
+ ```
55
+
56
+ ```ts
57
+ // before
58
+ reasoning_effort: isHard(input) ? "high" : "low",
59
+ // after
60
+ reasoning_effort: session.effort, // one value for the whole session
61
+ ```
62
+
63
+ If some steps need thinking and others do not, run them as separate sessions (a subagent with its own fixed setting) instead of toggling inside one.
64
+
65
+ ## Don't break meaning
66
+ A fixed setting changes the turns that used to differ. If hard turns needed thinking, turn it on for the whole session (quality first), or move hard steps into their own session; do not silently turn it off. Keeping reasoning in history uses more context: if context is the limit, compact (LP-PC-08) instead of stripping per turn. Compare answers and output tokens per task on a fixed set before and after.
67
+
68
+ ## Verify
69
+ (a) On consecutive turns, `cached_tokens` or `cache_read_input_tokens` is close to the previous request's prompt size. A turn whose read drops to the system prompt alone, right after a setting change, is this rule.
70
+
71
+ (b) kvsig: each request's exact `nodes` starts with all of the previous request's exact `nodes`. Use exact ids here: the loose form ignores reasoning, so `loose_nodes` that continue while exact `nodes` do not mean the reasoning was stripped or rendered differently.
72
+
73
+ ## Waste signal
74
+ Measured: the prefill side lowers S on every turn after a change. The generation side (E11) is not part of G; it shows as more output tokens per task in a before/after run (the `measure-loop` skill). Static: severity high, counted on both the prefill and the generation side (`saves: both`).
@@ -0,0 +1,75 @@
1
+ ---
2
+ id: LP-PC-10
3
+ title: Stable image and attachment placement
4
+ skill: prefill-cache
5
+ applies_to: [anthropic, openai, gemini, openrouter, vllm, sglang]
6
+ saves: prefill
7
+ severity: medium
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
+ Put each image, file or document in the message where it first appears and keep it there, with the same bytes or the same reference, for the rest of the session; never move it, re-encode it or re-upload it per call.
16
+
17
+ ## Why
18
+ Images and attachments are often the largest part of a prompt, and they are part of the prefix like any text. On Anthropic, adding or removing images invalidates the message blocks ([providers/anthropic.md](../../../providers/anthropic.md)); on OpenAI images count toward the prefix that must match ([providers/openai.md](../../../providers/openai.md)). Documented, not yet measured here.
19
+
20
+ The shapes that break it:
21
+ - "the current screenshot" attached to the newest message and removed from the older ones on every turn;
22
+ - a pre-signed URL generated on every call, so the same file has a new URL (its expiry query string) each time;
23
+ - an image resized or re-compressed on every call, which gives different base64 bytes;
24
+ - a file re-uploaded per call, which gives a new file id;
25
+ - attachments placed in the system prompt and swapped per request.
26
+
27
+ ## Detect in code
28
+ Python:
29
+ ```
30
+ rg -n 'generate_presigned_url\(|b64encode\(|\.thumbnail\(|\.resize\(|files\.(create|upload)\(' -g '*.py'
31
+ ```
32
+ Shapes: `generate_presigned_url(...)` inside the function that builds messages; `base64.b64encode(resize(img))` on each call; `for m in history: m["content"] = [p for p in m["content"] if p["type"] != "image"]`.
33
+
34
+ TS/JS:
35
+ ```
36
+ rg -n 'getSignedUrl\(|toString\("base64"\)|sharp\(|files\.create\(' -g '*.{ts,tsx,js,mjs}'
37
+ ```
38
+ Shapes: `image_url: { url: await getSignedUrl(s3, cmd) }` in the request builder; `sharp(buf).resize(...)` per request.
39
+
40
+ Go:
41
+ ```
42
+ rg -n 'PresignGetObject\(|base64\.StdEncoding\.EncodeToString\(|imaging\.Resize\(' -g '*.go'
43
+ ```
44
+ Shapes: a presign call or a resize inside the loop that builds each request.
45
+
46
+ ## Fix
47
+ Encode or upload once, when the attachment enters the conversation, and store the exact content part.
48
+
49
+ ```python
50
+ # before
51
+ def build(history, shot):
52
+ for m in history:
53
+ m["content"] = [p for p in m["content"] if p.get("type") != "image_url"]
54
+ url = s3.generate_presigned_url("get_object", Params=shot.key)
55
+ history[-1]["content"].append({"type": "image_url", "image_url": {"url": url}})
56
+
57
+ # after
58
+ def add_screenshot(history, shot, step):
59
+ part = {"type": "image_url", "image_url": {"url": to_data_url(shot)}} # encoded once
60
+ history.append({"role": "user", "content": [
61
+ {"type": "text", "text": f"Screenshot after step {step}; it supersedes earlier ones."}, part]})
62
+ ```
63
+
64
+ If old images must leave the context to save space, drop them in a compaction step (LP-PC-08), not on every turn.
65
+
66
+ ## Don't break meaning
67
+ If the app removed old images so the model would look only at the latest one, keep that intent with a label ("supersedes earlier ones") on the new image instead of deleting the old ones, and check that answers still refer to the latest image. Text that refers to an image stays next to it. Do not lower image resolution once to make bytes stable if the task needs the detail.
68
+
69
+ ## Verify
70
+ (a) In a session with an image, the next turn reports `cached_tokens` or `cache_read_input_tokens` covering the message that holds the image.
71
+
72
+ (b) kvsig: `msgs[i]` of the message that carries the attachment is equal on every later request, and `nodes` continue (each request's `nodes` start with all of the previous one's).
73
+
74
+ ## Waste signal
75
+ Measured: lowers S on every turn that moves or re-encodes an attachment. Static: severity medium for a per-call presign, re-encode or re-upload, or for attachments removed from older messages each turn.