@anthonymercer/contextscope 0.0.0-stage → 0.4.0

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +764 -2
  3. package/dist/cli/ansi.d.ts +31 -0
  4. package/dist/cli/ansi.js +80 -0
  5. package/dist/cli/args.d.ts +18 -0
  6. package/dist/cli/args.js +78 -0
  7. package/dist/cli/html-report.d.ts +2 -0
  8. package/dist/cli/html-report.js +119 -0
  9. package/dist/cli/index.d.ts +2 -0
  10. package/dist/cli/index.js +138 -0
  11. package/dist/cli/json-report.d.ts +1 -0
  12. package/dist/cli/json-report.js +2 -0
  13. package/dist/cli/read-input.d.ts +3 -0
  14. package/dist/cli/read-input.js +43 -0
  15. package/dist/cli/terminal-report.d.ts +7 -0
  16. package/dist/cli/terminal-report.js +271 -0
  17. package/dist/cli/usage-html.d.ts +2 -0
  18. package/dist/cli/usage-html.js +33 -0
  19. package/dist/cli/version.d.ts +2 -0
  20. package/dist/cli/version.js +3 -0
  21. package/dist/cli/write-reports.d.ts +12 -0
  22. package/dist/cli/write-reports.js +82 -0
  23. package/dist/core/analyze.d.ts +13 -0
  24. package/dist/core/analyze.js +99 -0
  25. package/dist/core/anthropic-breakpoints.d.ts +6 -0
  26. package/dist/core/anthropic-breakpoints.js +48 -0
  27. package/dist/core/anthropic-cache-scope.d.ts +12 -0
  28. package/dist/core/anthropic-cache-scope.js +47 -0
  29. package/dist/core/anthropic-injected-settings.d.ts +14 -0
  30. package/dist/core/anthropic-injected-settings.js +57 -0
  31. package/dist/core/anthropic-reasoning.d.ts +13 -0
  32. package/dist/core/anthropic-reasoning.js +57 -0
  33. package/dist/core/anthropic-speed.d.ts +4 -0
  34. package/dist/core/anthropic-speed.js +27 -0
  35. package/dist/core/cache-anthropic.d.ts +2 -0
  36. package/dist/core/cache-anthropic.js +146 -0
  37. package/dist/core/cache-openai.d.ts +2 -0
  38. package/dist/core/cache-openai.js +72 -0
  39. package/dist/core/calibrate.d.ts +43 -0
  40. package/dist/core/calibrate.js +97 -0
  41. package/dist/core/decode-text.d.ts +9 -0
  42. package/dist/core/decode-text.js +21 -0
  43. package/dist/core/detect.d.ts +10 -0
  44. package/dist/core/detect.js +102 -0
  45. package/dist/core/duplicates.d.ts +12 -0
  46. package/dist/core/duplicates.js +153 -0
  47. package/dist/core/findings.d.ts +4 -0
  48. package/dist/core/findings.js +437 -0
  49. package/dist/core/group-findings.d.ts +23 -0
  50. package/dist/core/group-findings.js +69 -0
  51. package/dist/core/index.d.ts +1 -0
  52. package/dist/core/index.js +2 -0
  53. package/dist/core/json-report.d.ts +10 -0
  54. package/dist/core/json-report.js +46 -0
  55. package/dist/core/json-utils.d.ts +28 -0
  56. package/dist/core/json-utils.js +99 -0
  57. package/dist/core/media-accounting.d.ts +11 -0
  58. package/dist/core/media-accounting.js +76 -0
  59. package/dist/core/model-id.d.ts +16 -0
  60. package/dist/core/model-id.js +36 -0
  61. package/dist/core/model-summary.d.ts +10 -0
  62. package/dist/core/model-summary.js +44 -0
  63. package/dist/core/openai-breakpoints.d.ts +14 -0
  64. package/dist/core/openai-breakpoints.js +107 -0
  65. package/dist/core/openai-context.d.ts +15 -0
  66. package/dist/core/openai-context.js +54 -0
  67. package/dist/core/parse-anthropic.d.ts +4 -0
  68. package/dist/core/parse-anthropic.js +284 -0
  69. package/dist/core/parse-error.d.ts +3 -0
  70. package/dist/core/parse-error.js +4 -0
  71. package/dist/core/parse-openai.d.ts +10 -0
  72. package/dist/core/parse-openai.js +273 -0
  73. package/dist/core/parse.d.ts +3 -0
  74. package/dist/core/parse.js +164 -0
  75. package/dist/core/prefix.d.ts +23 -0
  76. package/dist/core/prefix.js +290 -0
  77. package/dist/core/presentation.d.ts +4 -0
  78. package/dist/core/presentation.js +5 -0
  79. package/dist/core/pricing.d.ts +76 -0
  80. package/dist/core/pricing.js +130 -0
  81. package/dist/core/prompt-identity.d.ts +5 -0
  82. package/dist/core/prompt-identity.js +84 -0
  83. package/dist/core/read-json.d.ts +7 -0
  84. package/dist/core/read-json.js +74 -0
  85. package/dist/core/report.d.ts +2 -0
  86. package/dist/core/report.js +31 -0
  87. package/dist/core/reported-usage.d.ts +7 -0
  88. package/dist/core/reported-usage.js +195 -0
  89. package/dist/core/threads.d.ts +48 -0
  90. package/dist/core/threads.js +189 -0
  91. package/dist/core/token-counter.d.ts +13 -0
  92. package/dist/core/token-counter.js +21 -0
  93. package/dist/core/tokenize-claude.d.ts +18 -0
  94. package/dist/core/tokenize-claude.js +56 -0
  95. package/dist/core/tokenize-openai.d.ts +1 -0
  96. package/dist/core/tokenize-openai.js +15 -0
  97. package/dist/core/types.d.ts +326 -0
  98. package/dist/core/types.js +12 -0
  99. package/dist/core/usage-comparison.d.ts +2 -0
  100. package/dist/core/usage-comparison.js +70 -0
  101. package/dist/core/usage-labels.d.ts +5 -0
  102. package/dist/core/usage-labels.js +18 -0
  103. package/dist/core/volatile.d.ts +12 -0
  104. package/dist/core/volatile.js +31 -0
  105. package/package.json +75 -4
package/README.md CHANGED
@@ -1,3 +1,765 @@
1
- # Temporary Holding Version
1
+ # contextscope
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See what's actually in your LLM context window, and why your prompt cache keeps missing.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@anthonymercer/contextscope)](https://www.npmjs.com/package/@anthonymercer/contextscope)
6
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ [![Live demo](https://img.shields.io/badge/live%20demo-antonsoo.github.io%2Fcontextscope-1baf7a)](https://antonsoo.github.io/contextscope/)
8
+
9
+ <p align="center">
10
+ <img src="docs/assets/web-dashboard-dark.png" alt="contextscope web app on a synthetic 24-turn coding-agent session: headline numbers, two grouped findings (a timestamp in the system prompt breaks the cache on requests 2 to 24), and a token-usage treemap of the 78,715-token last request" width="880">
11
+ </p>
12
+
13
+ An agent resends its tools, rules and growing history on every turn. A timestamp
14
+ in those rules, a rebuilt tool list or a changed request setting can invalidate
15
+ the cache even when most of the text is identical. Contextscope reads the raw
16
+ JSON requests, locates those changes and simulates each provider's cache rules.
17
+ When the log includes response usage, it compares the prediction with the
18
+ captured counters and preserves discrepancies for inspection.
19
+
20
+ File import, local analysis and report generation run on your device. The web
21
+ app's Content-Security-Policy (`connect-src 'self'`) prevents it from sending
22
+ your input to another host. The CLI's optional `--calibrate` operation sends
23
+ the selected Anthropic request to its token-counting endpoint; ordinary local
24
+ analysis does not need a key or upload.
25
+
26
+ The CLI, library and demo include corrections for empty/refusal histories, reasoning
27
+ settings, injected prompt instructions, media accounting and unresolved OpenAI
28
+ stored-context boundaries. Their
29
+ [source, package and demo status](docs/source-status.md) is recorded separately,
30
+ with retained counterexamples and verification artifacts. The measurements below
31
+ describe the public agent trajectories used to check the analyzer.
32
+
33
+ They also preserve unresolved MCP tool context in Anthropic and
34
+ Responses logs. A server URL or toolset declaration no longer supplies a finite
35
+ whole-request token count or simulated cache hit without the resolved prompt.
36
+ Pinned/returned lists stay inspectable; their MCP rendering is not implemented
37
+ here. [Native SDK bodies, a real public catalog and before/after reports](studies/mcp-context/README.md).
38
+
39
+ ## On real agent trajectories
40
+
41
+ The first measurement of contextscope against what a provider reported, not against
42
+ requests its own author wrote: 360 SWE-bench agent runs (mini-SWE-agent, public
43
+ [trajectories](studies/real-trajectories/README.md)), 12,760 requests rebuilt from them, each
44
+ next to the `usage` the API returned for it. Claude Sonnet 4.5, Opus 4.5, Haiku 4.5, Opus 4.6,
45
+ gpt-5.1 and gpt-5.2.
46
+
47
+ - **Claude token counts were 15 to 25% low (0.3.3).** Code and command output tokenize denser
48
+ than the estimate assumed. Re-fitted on half of the trajectories, the held-out mean error is
49
+ +1.6 to +3.3% on plain-text sessions and −6.5 to −11.3% on sessions that send tools (the
50
+ roughly 500-token tool-use system prompt is not modelled). Fixed in 0.4.0.
51
+ - **OpenAI counts are exact once the message framing is added.** `prompt_tokens` was the
52
+ o200k_base count of the contents plus exactly 5 per message, in 2,205 of 2,205 requests.
53
+ 0.3.3 left the 5 out (0.8 to 1.1% low).
54
+ - **Work after 0.3.3 had broken the cache simulation on tool-using Claude sessions.**
55
+ A tool result sent as a string in one request and as a one-element list of text blocks in
56
+ the next was read as different content. On mini-SWE-agent 2.0 sessions the agreement with
57
+ Anthropic on "did this request read the cache" fell from 88 to 100% (0.3.3) to 6.5 to 23%, and
58
+ 5,715 requests that did read the cache got a "breakpoint is outside the 20-position lookback
59
+ window" finding. 0.3.3 is not affected, and 0.4.0 ships with the fix.
60
+ - **With those fixed it agrees with Anthropic on 96 to 100% of requests** about whether the
61
+ cache was read, and its predicted share of input tokens read from cache is within 0.0 to
62
+ 1.6 points of the reported one. Two Claude 4.5 models were missing from the model table and
63
+ were checked against a 512-token minimum instead of 4,096 (Opus 4.5).
64
+ - **The legacy OpenAI simulation is optimistic.** 27% of requests matched the reported
65
+ `cached_tokens` exactly; 34% got none where it predicted a read. gpt-5.2 cached 56 to 57% of
66
+ the predicted tokens, gpt-5.1 88%.
67
+
68
+ **Reported usage is inspectable in the CLI and live demo.** Pair a request with
69
+ `response.usage` and the report compares captured counts with the simulation,
70
+ preserving missing counters and the exact source fields. Verification covered
71
+ 17,425 responses from 520 hash-checked trajectories; full analysis of 2,205 OpenAI
72
+ Chat requests exposed 712 simulated hits with a recorded zero. See the
73
+ [reported-usage workflow](docs/reported-usage.md) and [verification study](studies/reported-usage/README.md).
74
+ ## Contents
75
+
76
+ - [Quickstart](#quickstart)
77
+ - [Features](#features)
78
+ - [Usage](#usage)
79
+ - [How it works](#how-it-works)
80
+ - [On real agent trajectories](#on-real-agent-trajectories)
81
+ - [Accuracy and limitations](#accuracy-and-limitations)
82
+ - [Development](#development)
83
+ - [Contributing](#contributing)
84
+ - [License](#license)
85
+
86
+ ## Quickstart
87
+
88
+ Run it against your own request log:
89
+
90
+ ```sh
91
+ npx @anthonymercer/contextscope analyze your-requests.jsonl
92
+ ```
93
+
94
+ That runs the published package
95
+ ([`@anthonymercer/contextscope`](https://www.npmjs.com/package/@anthonymercer/contextscope)
96
+ on npm; the command it installs is `contextscope`). Version 0.4.0 adds the reported-usage review and the cache-accounting
97
+ corrections, including [processing-speed scopes and prices](studies/fast-mode/README.md).
98
+ To work from source with the bundled examples, clone the repository:
99
+
100
+ ```sh
101
+ git clone https://github.com/antonsoo/contextscope && cd contextscope
102
+ npm ci
103
+ node dist/cli/index.js analyze examples/anthropic-agent-cache-bust.jsonl.gz
104
+ ```
105
+
106
+ `npm ci` runs the package's `prepare` script, which compiles the CLI and
107
+ library with `tsc`.
108
+
109
+ Or skip the CLI and open **[antonsoo.github.io/contextscope](https://antonsoo.github.io/contextscope/)**:
110
+ drop a request file, paste one, or click a built-in example.
111
+
112
+ ## Features
113
+
114
+ - **Token usage treemap.** Every request in a session, broken into segments
115
+ (system, tool definitions, user/assistant text, tool calls, tool results,
116
+ images, thinking). Countable segments are colored by category and sized by
117
+ tokens. In source and the demo, unmodeled media stays inspectable in the segment table
118
+ while totals, context usage and cache costs are unavailable; encoded payloads
119
+ do not become text tokens. Click a segment to see its original content, path
120
+ and cache status. [Media accounting and nullable source types](studies/media-accounting/README.md).
121
+ - **Unresolved stored context.** In source and the demo, Responses history IDs, reusable prompts,
122
+ input references and opaque reasoning/compaction remain inspectable. Whole-request
123
+ counts and sequence cache estimates are unavailable until that context can be
124
+ accounted for; captured usage remains separate. [Stored-context evidence](studies/stored-context/README.md).
125
+ - **Prompt-cache simulation across a sequence.** For each request and the
126
+ request it continues, contextscope finds the longest common prefix in the provider's own
127
+ serialization order, shows a readable diff of exactly what changed, and
128
+ simulates cache reads, writes and misses under that provider's rules:
129
+ Anthropic's `cache_control` breakpoints, per-model minimum cacheable length,
130
+ 20-position lookback window and 5-minute/1-hour write pricing; OpenAI's
131
+ explicit/implicit breakpoint caching on the listed GPT-6 models and a legacy
132
+ approximation on GPT-5.1/5.2. It reports simulated cost against an optimized
133
+ scenario, and projects the difference to 1,000 sessions shaped like yours (a
134
+ straight multiplication, not a separate estimate).
135
+ - **Reported usage review (source and live demo).** Paired response counters stay
136
+ separate from estimates. Compare input and cache-read totals over identical
137
+ covered requests, filter simulated hits with reported zero, and inspect each
138
+ original counter path. Missing or ambiguous totals remain unavailable.
139
+ Browser JSON and offline HTML exports retain all requests, including those
140
+ hidden by a filter or page. [Capture formats and limitations](docs/reported-usage.md).
141
+ - **Cache accounting corrections (source and live demo).** Several Anthropic
142
+ breakpoints now share one disjoint read/write calculation; lookup includes
143
+ exactly 20 positions, and the optimized scenario respects four marker slots.
144
+ Invalid cache configurations fail with the request and field location.
145
+ Browser JSON and offline HTML downloads also work without response usage.
146
+ [Reproduction and limits](docs/cache-accounting.md).
147
+ - **Logs of more than one conversation.** A proxy capture of an agent holds
148
+ its main loop and, between the turns, side requests on another model; a
149
+ gateway's log holds every user's conversation, interleaved. Each request is
150
+ matched to the request it continues, wherever in the file that is, and the
151
+ cache is simulated as the providers keep it: by content, per model. A
152
+ session reads the same whether it is alone in the file or not.
153
+ - **Priced per request.** The model named in each request
154
+ picks the pricing and cache rules (dated snapshots and Bedrock/Vertex ids
155
+ included); `--model` overrides all rows, and an id with no pricing entry is reported
156
+ instead of silently priced as something else. All eleven current Claude
157
+ models are covered, including the ones whose minimum cacheable prefix or
158
+ cache-read price differs from the usual, and the two 4.5
159
+ models that coding agents still run, Opus 4.5 and Sonnet 4.5. Mixed logs retain
160
+ each request's prices, cache minimum and context window; model names appear
161
+ beside the costs. The browser's "from each request" option restores detection
162
+ after an override. [Counterexample and replay](studies/mixed-models/README.md).
163
+ - **Findings with concrete fixes**, grouped so a problem that recurs on every
164
+ request is reported once: *"System prompt contains a value that changes every
165
+ request (requests 2–24, 23×)"*, *"Tools reordered between requests 2 and 3:
166
+ positions 2–3: [read_file, grep_search] → [grep_search, read_file]"*, *"tool
167
+ schema key order differs"*, *"Model changed mid-conversation"*, *"prefix below
168
+ Claude Opus 4.6's 4,096-token minimum"*, *"No cache breakpoint on the
169
+ conversation tail"* (often the single highest-value fix for a real agent loop).
170
+ Different severities and message variants remain
171
+ separate: a pricing warning can no longer disappear inside an informational
172
+ fast-mode group. [Before/after report replay](studies/finding-groups/README.md).
173
+ This grouping correction does not change pricing or token counts.
174
+ - **Duplicate content detection** (5-word shingling + Jaccard similarity): the
175
+ same file or tool output fetched more than once in one conversation.
176
+ - **Reads the files you already have.** Anthropic Messages bodies, OpenAI Chat
177
+ Completions and Responses API bodies, as a single request, a JSON array, or
178
+ JSONL, optionally gzipped. The parsers are tested on request bodies written
179
+ by the real Python SDKs (`tests/fixtures/sdk/`), not only on hand-made ones. Anthropic Message Batches and OpenAI Batch API
180
+ files, and gateway logs that wrap each body in `request`/`request_body`, are
181
+ unwrapped automatically. The format is auto-detected.
182
+ - **Exact OpenAI token counts** (o200k_base, via `gpt-tokenizer`) and
183
+ **estimated Claude token counts**, always labelled `≈`, with optional
184
+ calibration against a measured whole-request count. The CLI can call
185
+ Anthropic's `count_tokens` endpoint; the browser accepts a count you supply locally.
186
+ - **A Node CLI** that works as a CI gate (`--fail-on warning` exits 2) and
187
+ writes HTML or JSON reports, and **a Vite + TypeScript web app** for
188
+ interactive exploration, sharing one core library.
189
+
190
+ ## Usage
191
+
192
+ ### CLI
193
+
194
+ ```text
195
+ contextscope analyze <file> [options]
196
+
197
+ Options:
198
+ --format <anthropic|openai> Override auto-detected format
199
+ --model <id> Price as this model (default: the model named in the requests)
200
+ --calibrate Anthropic only: count the largest request exactly with the
201
+ count_tokens endpoint (reads ANTHROPIC_API_KEY) and scale
202
+ every Claude estimate to match
203
+ --fail-on <error|warning|info> Exit 2 for incomplete input, invalid usage, or a finding
204
+ at least this severe
205
+ --html <out.html> Also write a self-contained HTML report
206
+ --json <out.json> Also write the analysis as JSON: counts, findings and cache
207
+ steps for every request and segment, without raw prompt values
208
+ -v, --verbose Show every request's breakdown and every prefix/cache row
209
+ ```
210
+
211
+ Exit status is 0 on success, 1 on bad arguments or unreadable input, and 2
212
+ when `--fail-on` is set and input coverage is incomplete, reported usage is
213
+ invalid, a usage aggregate overflows, or a finding meets the threshold.
214
+ Missing optional response usage alone does not fail a gate. Gzipped input is detected by
215
+ extension or, failing that, by gzip magic bytes.
216
+
217
+ Report paths must be distinct from the input and from
218
+ each other, including hard links and symlinked parent directories. Output
219
+ symlinks are refused. Both reports are staged before replacing either file;
220
+ each replacement is atomic and uses private permissions (0600 on POSIX).
221
+ Invalid destinations and write failures exit 1. See the
222
+ [captured overwrite and corrected workflow](studies/report-destinations/README.md).
223
+ Shell redirection and concurrent filesystem changes are outside this guard.
224
+
225
+ Real output on `examples/anthropic-agent-cache-bust.jsonl.gz`, a synthetic
226
+ 24-turn, ~79,000-token coding-agent session where a timestamp inside the system
227
+ prompt busts the cache on every turn:
228
+
229
+ <p align="center">
230
+ <img src="docs/assets/cli-cache-bust.png" alt="Terminal output of contextscope analyze: the largest request's token breakdown, all 23 request pairs rewriting the system block, zero cache reads across 24 requests, $2.8460 actual vs $0.4570 optimized (84% lower), and two grouped findings pinpointing the timestamp" width="880">
231
+ </p>
232
+
233
+ The screenshots, and the token counts and dollar figures in this section and
234
+ the next, come from 0.3.3. 0.4.0's larger Claude estimate (see
235
+ [On real agent trajectories](#on-real-agent-trajectories)) prices the same two
236
+ sessions at $3.4459 actual and $0.5533 optimized, still 84% lower; the findings
237
+ are unchanged. The other percentages here were not recomputed.
238
+
239
+ The paired example, `examples/anthropic-agent-cache-fixed.jsonl.gz`, is the
240
+ same session with two changes: the timestamp is gone from the system prompt,
241
+ and a second `cache_control` breakpoint rolls forward onto the latest turn of
242
+ every request, next to the first breakpoint on the static system prompt. That
243
+ is the "one breakpoint on the stable prefix, one rolling on the growing tail"
244
+ pattern Anthropic recommends for agent loops. Fixing only the timestamp and
245
+ stopping there is a common half-fix: the system-prompt breakpoint finally reads,
246
+ but every turn still resends the whole conversation history uncached, because
247
+ nothing marks where that history ends. contextscope has a finding for that gap
248
+ (`missing_tail_breakpoint`), so it never reports "no findings" while still
249
+ showing a large potential saving. On the fixed example, actual cost is $0.4570,
250
+ identical to the optimized figure, with zero findings. The timestamp fix alone
251
+ would have saved 13.3%; both fixes together save 84%.
252
+
253
+ ### Web app
254
+
255
+ ```sh
256
+ npm run build:web # outputs web/dist/
257
+ npm run preview:web # serve the built app locally
258
+ ```
259
+
260
+ Drop a file (plain or gzipped), paste JSON/JSONL, or pick one of five built-in
261
+ synthetic examples, labelled as such: the 24-turn cache-busting session above
262
+ (a ~5.7 MB session, shipped gzipped at ~0.48 MB and fetched only when you pick
263
+ it), its fixed counterpart, a session with a file re-read three times, and an
264
+ OpenAI session with tools reordered mid-conversation, and a six-request paired
265
+ capture with authored reported-usage counters. The view opens on the
266
+ *last* request, where a growing conversation is biggest. Findings come first,
267
+ each with links to every request it fired on; below them are the treemap, the
268
+ segment table, the line-level diff between each request and the one it
269
+ continues, and the cache table. A file of several conversations opens on its
270
+ largest request. The format and model pickers in the top bar override detection for the
271
+ current input only.
272
+
273
+ <p align="center">
274
+ <img src="docs/assets/web-inspector.png" alt="Segment inspector drawer open on the grep_search tool definition, showing its raw JSON schema and token counts" width="420">
275
+ <img src="docs/assets/web-openai-light.png" alt="The same app in light mode on an OpenAI session, with one finding naming the two tools that swapped places" width="420">
276
+ </p>
277
+
278
+ ### As a library
279
+
280
+ ```ts
281
+ import { analyze, groupFindings } from "@anthonymercer/contextscope";
282
+
283
+ const result = analyze(rawRequestJsonOrJsonl); // or { model: "claude-opus-5-5" } to override
284
+ // result.reports[i].model — this request's model, override or explicit fallback
285
+ // result.model — compatibility summary only; not the pricing for every row
286
+ // result.parse.complete — false for skipped/non-request records or a mismatched format override
287
+ // result.parse.requests[i].source — original record index, JSONL line, and envelope field
288
+ // result.reports — per-request token totals and category breakdown
289
+ // result.prefixMatches — longest common prefix + diff between each request and the one it continues
290
+ // result.conversations — how many conversations the input holds, and which one each request is in
291
+ // result.cacheSimulation — simulated reads/writes/cost, current vs. optimized
292
+ // result.usageComparison — reported vs. simulated counts with per-metric coverage
293
+ // result.findings — concrete, located issues (groupFindings() collapses repeats)
294
+ // result.duplicates — near-duplicate content groups
295
+ ```
296
+
297
+ Source token fields can be `null` for unmodeled media or unresolved stored/opaque
298
+ context. Check them before
299
+ arithmetic; `null` is not zero. `cacheSimulation.unavailableReason` explains why
300
+ sequence estimates are withheld. Captured provider counters keep their original
301
+ known/missing/invalid states. [Contract and examples](studies/media-accounting/README.md#source-library-and-json-contract).
302
+
303
+ ## How it works
304
+
305
+ **Parsing.** Each request is normalized into a flat, ordered list of
306
+ `Segment`s in the *provider's own serialization order*: `tools → system →
307
+ messages` for Anthropic, and `tools → messages` for OpenAI (whose system or
308
+ developer message is `messages[0]`, or `instructions` in the Responses API).
309
+ Every other analysis operates on this list, so the wire formats are understood
310
+ once, in `src/core/parse-*.ts`. Each record can be a raw body or a supported
311
+ `params`, `body`, `request`, or `request_body` envelope, including a JSON-encoded
312
+ body string. Two possible bodies in one record are rejected as ambiguous.
313
+ Original record positions and physical JSONL lines are retained after skips.
314
+ Strong evidence for both providers requires separate analyses; an explicit
315
+ format override remains available, with warnings and incomplete status for
316
+ mismatches. Repeated plain-text messages cannot outweigh a provider signal.
317
+
318
+ Duplicate JSON fields (including escaped equivalent keys), numbers whose value
319
+ changes when parsed and serialized, and nesting beyond 128 containers are
320
+ rejected. The numeric check includes overflow, underflow and precision loss:
321
+ distinct 64-bit IDs must not silently become the same tool-schema value and
322
+ produce a false cache match. Equivalent decimal spellings such as `1.0` and
323
+ `1e0` remain supported. This check covers the whole record, including metadata
324
+ and JSON-encoded request bodies; it rejects unsupported precision rather than
325
+ providing arbitrary-precision analysis. See the
326
+ [SDK reproduction and Decimal cross-check](studies/numeric-integrity/README.md).
327
+ Malformed JSONL syntax is
328
+ retained as a visible coverage gap: `parse.complete` is false,
329
+ `parse.sourceRecords` includes skipped nonblank lines, and `parse.skippedRecords`
330
+ counts malformed lines plus records with no analyzable segments. Any configured
331
+ `--fail-on` gate exits 2 for incomplete input, regardless of finding severity.
332
+ Reports retain the partial evidence and warnings. Completeness describes source
333
+ coverage, not API validity or measured cache behavior. An empty request array is
334
+ an error.
335
+
336
+ File decoding is strict UTF-8, or UTF-16 selected by its byte-order mark. Corrupt
337
+ encodings are rejected before replacement characters can rewrite the evidence,
338
+ including gzipped inputs. A real U+FFFD character in a valid encoding is retained.
339
+
340
+ **Token counts.** OpenAI counts are exact: `gpt-tokenizer`'s pure-JS o200k_base
341
+ encoder, the BPE vocabulary GPT-4o and newer OpenAI models use. Claude counts
342
+ are a documented heuristic (`src/core/tokenize-claude.ts`), because Anthropic
343
+ does not publish Claude's tokenizer, and they are labelled `≈` everywhere. The
344
+ method: characters per token scaled by how symbol-dense the text is (about 3.3
345
+ chars/token for prose and 2.5 for JSON/code, interpolated by the fraction of
346
+ non-alphanumeric characters), since BPE tokenizers split more often on
347
+ punctuation. (These were 4.0 and 2.9 through 0.3.3, which counted
348
+ the agent transcripts in [the real-trajectory study](studies/real-trajectories/README.md)
349
+ 20 to 30% low.) An agent loop re-sends its whole history on every request, so each
350
+ distinct segment text is tokenized once per analysis: the flagship session has
351
+ 1,259 segments but only 109 distinct ones.
352
+
353
+ **Literal tokenizer spellings.** Strings such as
354
+ `<|endoftext|>` in a prompt, tokenizer configuration or tool result are counted
355
+ as ordinary text. They no longer abort the analysis or become control tokens.
356
+ [Native-tokenizer checks and complete CLI/browser replays](studies/token-literals/README.md)
357
+ retain the before/after behavior and distinguish text counts from framing and
358
+ provider billing. The published package and hosted demo are unchanged.
359
+
360
+ **Calibration.** The CLI's optional `--calibrate` flag sends the largest
361
+ Anthropic request to `POST /v1/messages/count_tokens`, using the API key you
362
+ provide. This is the only network operation in the CLI. In the web app,
363
+ enter the measured `input_tokens` total for the selected request and model in
364
+ **Calibrate Claude estimates**. The browser does not ask for an API key or
365
+ contact Anthropic; its same-origin network policy remains enforced.
366
+
367
+ Both paths divide the measured whole-request count by the original heuristic
368
+ estimate and rescale the session's Claude estimates. The UI identifies the
369
+ reference request, model, count, and scale. Other requests and individual
370
+ segments remain estimates; rounding means their sum may differ slightly from
371
+ the measured total. Repeating a calibration starts from the original input,
372
+ so scales do not compound. Undo it at any time; changing the model, format,
373
+ or input clears it.
374
+
375
+ Scalar calibration requires countable request content. It cannot recover
376
+ unmodeled media segments or their cache boundaries. The source CLI refuses
377
+ `--calibrate` on such a sequence before contacting a provider; the browser
378
+ preserves the report and explains the refusal for a selected media request.
379
+
380
+ **Conversations.** A request log is rarely one conversation, and the line
381
+ before a request is then some other conversation's. `src/core/threads.ts` pairs
382
+ each request with the earlier request it continues: the one whose messages it
383
+ starts with, all of them and in order (the previous turn of an agent loop);
384
+ failing that, a recent request at least half of whose messages it re-sends (the
385
+ same conversation with its history edited: a sliding window, a trimmed tool
386
+ result); failing that, the earlier request that shares the most of its tools
387
+ and system prompt once volatile values and ordering are normalized away (a new
388
+ conversation of the same application, compared only as far as that shared
389
+ setup). A request that matches nothing starts a conversation with nothing to
390
+ compare it to. Prefixes are interned in a trie, so analyzing 3,000 requests of
391
+ 150 interleaved conversations takes about half a second. In a file that is one
392
+ conversation, every request is paired with the one before it, as before.
393
+
394
+ Real output for the fixed example session with a 27-token request on another
395
+ model after every second turn (36 requests; alone, the session costs $0.4570
396
+ and has no findings):
397
+
398
+ ```
399
+ contextscope — anthropic · 36 requests in 13 conversations (auto-detected)
400
+ priced as Claude Sonnet 5 (from the requests)
401
+ ...
402
+ Prefix match across the sequence
403
+ 13 conversations in this file; each request is compared with the request it continues
404
+ all 23 follow-up requests only append to the request they continue
405
+ 11 requests start a new conversation on a setup already sent
406
+ ...
407
+ total actual cost: $0.4576
408
+ total optimized cost: $0.4576 (findings fixed, plus a breakpoint on each request's tail)
409
+
410
+ No findings — this sequence caches cleanly.
411
+ ```
412
+
413
+ **Prefix matching and diffing.** `src/core/prefix.ts` finds the longest common
414
+ prefix between the segment lists of a request and the one it continues, then diffs the *whole*
415
+ lists, not just the tail, so a single reordered tool or one edited system block
416
+ shows up as a small, localized change instead of "everything after position 3
417
+ differs." Identity includes the original prompt block, message header and message
418
+ boundary, separately from the text used for token counts. Tool destinations,
419
+ error flags, thinking signatures, document metadata and speaker names therefore
420
+ cannot disappear from a prefix comparison when visible text stays the same.
421
+ Metadata-only changes are marked in readable diffs. The optimized scenario sorts
422
+ keys and parameterizes volatile text while preserving routing IDs, names, roles,
423
+ types and signed/opaque thinking. Following tool calls have their own identity;
424
+ they are not compared as part of the assistant text before them.
425
+ The diff is Myers' O((N+M)·D) algorithm (E. W. Myers, "An O(ND)
426
+ Difference Algorithm and Its Variations", *Algorithmica* 1, 1986): consecutive
427
+ agent requests differ by a few edits, so D is small even when N and M are in
428
+ the thousands. A randomized test checks that the unchanged lines always form a
429
+ longest common subsequence.
430
+
431
+ **Cache simulation.** `src/core/cache-anthropic.ts` and `cache-openai.ts`
432
+ implement each provider's documented rules:
433
+
434
+ - **Anthropic**: up to 4 `cache_control` breakpoints per request. A top-level
435
+ `cache_control`, beside `model` (automatic caching), is a breakpoint on the
436
+ last cacheable block of the request, the last block that is not thinking or
437
+ empty text; it is simulated like a marker placed there by hand, and takes
438
+ one of the four. Breakpoints are read against
439
+ the entries earlier requests wrote at theirs: an entry is read if its prefix
440
+ matches this request's modeled prompt units up to that point, whichever earlier
441
+ request wrote it, and the position distance is within the 20-block lookback window (a
442
+ run of consecutive `tool_use` or `tool_result` blocks counts as one position,
443
+ per Anthropic's documented rule). Writes cost 1.25× (5-minute TTL) or 2×
444
+ (1-hour TTL) the input price. Reads cost 0.1× on most models, but 0.05× on
445
+ Claude Opus 5.5 and 0.025× on Claude Fable 5.1. A breakpoint below the
446
+ model's minimum cacheable length silently never caches, and that minimum is
447
+ not monotonic across generations: 512 tokens on the newest models, 1,024 on
448
+ Opus 4.8 and Sonnet 5, 2,048 on Opus 4.7, 4,096 on Opus 4.6 and Haiku 4.5.
449
+ Figures are from Anthropic's pricing and prompt-caching documentation as of
450
+ 2026-09-25.
451
+ Message entries also require matching `tool_choice` and explicit image
452
+ presence. Changing either preserves tools and top-level system entries,
453
+ but cannot reuse the other setting's message entries, even when an image
454
+ is added after a breakpoint. Both simulation scenarios enforce this.
455
+ [Reproduction, defaults and boundaries](studies/cache-settings/README.md).
456
+ Standard/fast speed changes isolate system and message entries while
457
+ preserving separately marked tools. Supported fast requests use current
458
+ premium input rates, including reads and writes; reports show the modeled
459
+ speed. Unrecognized rates leave costs unavailable. The current Opus 4.6
460
+ standard-speed fallback is explicit.
461
+ [Fast-mode replay and pricing boundaries](studies/fast-mode/README.md).
462
+ Structured-output formats isolate all prompt levels. Citation enablement
463
+ isolates system/messages and preserves separately marked tools. Earlier
464
+ matching settings remain reusable; grammar compilation is a separate cache.
465
+ [Injected-prompt settings and calibration](studies/injected-settings/README.md).
466
+ - **OpenAI**: listed GPT-6 models use explicit/implicit breakpoint simulation.
467
+ No markers in explicit mode means zero reads and writes. Lookup uses eligible
468
+ incoming boundaries, and cache writes have their own 30-minute column and
469
+ premium. GPT-5.1/5.2 keep the older optimistic 1,024/128-token approximation.
470
+ Cache keys and renderer settings isolate entries; changing either cannot
471
+ silently inherit another request's predicted hit. The SDK-serialized
472
+ [cache modes example](examples/openai-cache-modes.jsonl.gz) demonstrates why
473
+ identical developer text can still miss when the last user message changes.
474
+ [Rules, counterexamples and limits](studies/openai-cache/README.md).
475
+ - **Both**: a cached prefix is the model's own attention state, so a request
476
+ reads only what earlier requests on its own model cached, however much of the
477
+ prefix another model was sent.
478
+
479
+ The **"optimized"** scenario re-runs the same simulation with the findings
480
+ fixed: ISO-8601 timestamps, UUIDs and epoch-looking integers are normalized out
481
+ of the prefix comparison (the "timestamp in the system prompt" fix), JSON keys
482
+ and the tool list are put in a deterministic order, and, for Anthropic, every
483
+ request gets a `cache_control` breakpoint on its last cacheable block. With four
484
+ occupied slots, the final marker moves there with its TTL preserved. The actual scenario compares blocks exactly as sent,
485
+ key order included, so a schema whose keys drift is a miss there and a saving
486
+ here. A `cache_control` marker itself is never part of the comparison: a
487
+ rolling breakpoint moves every turn without changing the cached content. The
488
+ dollar difference is the "potential savings" figure.
489
+
490
+ **Duplicate detection (current source).** Every pair in a group must have
491
+ five-word-shingle Jaccard similarity of at least 0.85. Similarity is not
492
+ transitive: two successive edits cannot establish that the first and last
493
+ versions are interchangeable. The greedy partition follows source order and
494
+ does not enumerate every possible match. Actual strings establish identity;
495
+ identical text is pooled before comparison, and the short debug signature is
496
+ never used as proof of equality.
497
+
498
+ Groups distinguish identical analyzed text from similar text, report the true
499
+ minimum pairwise similarity, and let you inspect the original members. A 100%
500
+ shingle match can still change repetition or ordering. `estimatedReviewTokens`
501
+ counts Claude-estimated tokens in members after the first; it replaces the
502
+ unsupported `estimatedWastedTokens` claim in the source library/JSON contract.
503
+ It is a review budget, not established removable content or cost savings.
504
+ [Counterexamples, public-history audit and verification](studies/duplicate-evidence/README.md)
505
+ are retained.
506
+
507
+ The browser now compares each displayed later member with the first,
508
+ showing literal changed lines, both source positions and complete text/JSON
509
+ downloads. Choose **Similar file reads: inspect the edits** to try the existing
510
+ configuration example. Whitespace and line endings remain significant; large
511
+ comparisons show an explicit limit instead of a partial verdict.
512
+ [Workflow, bounds and retained evidence](studies/text-comparison/README.md).
513
+ This browser feature has not been deployed to the live demo.
514
+
515
+ Detection remains scoped to terminal requests of each inferred conversation.
516
+ In an agent loop every later request resends its history, so comparing across
517
+ requests would flag earlier turns as duplicates of themselves. The final
518
+ request retains repeated reads inside its accumulated context.
519
+
520
+ Large histories use an exact candidate filter before the complete-link checks.
521
+ On a constructed 2,000-block history, duplicate review fell from 67.41 to 2.69
522
+ seconds on Node 24.21.0; all 466 groups in the 240 public terminal snapshots
523
+ stayed identical. The temporary index uses extra memory, and dense comparisons
524
+ can remain quadratic. [Measurements, algorithm and limits](studies/duplicate-scaling/README.md)
525
+ are retained.
526
+
527
+ **Findings.** A fixed set of rule-based checks over the parsed sequence, the
528
+ prefix diffs and the duplicate groups (`src/core/findings.ts`), not an LLM
529
+ judgment, so the same input always produces the same findings. Most are
530
+ structural (a reordered tool, a changed schema, a model switch). One,
531
+ `missing_tail_breakpoint`, is derived from the Anthropic simulation's own
532
+ actual-vs-optimized cost gap, so the findings and the "potential savings"
533
+ figure can't contradict each other: whenever fixing the findings would lower
534
+ the cost by 10% or more, at least one finding says so. "No findings" is a
535
+ factual claim: the simulated optimized cost is (within rounding) the actual
536
+ cost already. Advice is model-aware; for example, a mid-conversation `system`
537
+ message is suggested only for models that accept one.
538
+
539
+ **Categorical palette.** The eight content categories use a colorblind-safe
540
+ palette (worst-case simulated CVD ΔE ≥ 8.4 OKLab, worst-case normal-vision ΔE
541
+ ≥ 19.3, both checked against the actual dark and light surface colors) in a
542
+ fixed hue order, so a color always means the same category.
543
+
544
+ **Treemap.** A hand-rolled squarified treemap (Bruls, Huizing & van Wijk,
545
+ 2000), about 40 lines in `web/src/lib/treemap.ts`.
546
+
547
+ ## Accuracy and limitations
548
+
549
+ - **Media accounting is unavailable in source and the demo.** Images, opaque PDFs/files and
550
+ input audio are preserved without tokenizing their encodings or references.
551
+ Affected totals and context fractions are unavailable, as are cache partitions
552
+ and costs for the whole sequence. Other segments retain text counts, and
553
+ captured usage remains visible. This is targeted coverage of recognized
554
+ content types, not complete request validation or multimodal token support.
555
+ [Identical-pixel counterexample and limits](studies/media-accounting/README.md).
556
+ - **Claude token counts are estimates** unless calibrated. There is no public
557
+ Claude tokenizer, and Claude's tokenizers differ between generations
558
+ (Anthropic documents that the tokenizer introduced with Opus 4.7 uses up to
559
+ about 1.35× as many tokens as Opus 4.6's for the same text), so no single
560
+ heuristic can be accurate for every model. Measured against the input tokens
561
+ Anthropic reported for 10,555 requests on Claude Sonnet 4.5, Opus 4.5,
562
+ Haiku 4.5 and Opus 4.6 ([study](studies/real-trajectories/README.md)), 0.3.3
563
+ was 15 to 25% low on average. In this checkout, on trajectories held out of
564
+ the fit, the mean error is +1.6 to +3.3% on plain-text sessions and −6.5 to
565
+ −11.3% on sessions that send tools, with 95% of requests within 11 to 15% and
566
+ 13 to 22% respectively. The tool-use system prompt Anthropic adds (about 500
567
+ tokens on these models) and thinking blocks are not modelled. Nothing is
568
+ measured for Opus 4.7 and later. Calibration aligns the total for the counted
569
+ request, subject to segment rounding; segments denser or sparser than that
570
+ request's average keep some error.
571
+ - **OpenAI token counts are exact** for the o200k_base encoding, cross-checked
572
+ in `tests/tokenize-openai.test.ts` against `js-tiktoken`, an independently
573
+ maintained pure-JS tokenizer, on prose, code, JSON,
574
+ non-English text, emoji, repeated text and literal delimiter spellings; all match exactly. A model that uses
575
+ a different encoding still gets the o200k_base count. Chat Completions
576
+ messages with plain-string content carry 5 framing tokens each in this
577
+ checkout, the amount gpt-5.1 and gpt-5.2 reported for 2,205 requests with no
578
+ exception (0.3.3 left them out and was 0.8 to 1.1% low); messages with array
579
+ content, tool calls or tool definitions have framing that has not been
580
+ measured and is still not counted.
581
+ - **The legacy OpenAI simulation is optimistic, especially on gpt-5.2.**
582
+ Against the `cached_tokens` OpenAI reported for 2,085 steps whose prefix the
583
+ tool predicted would be cached, 27% matched exactly, 34% reported no cached
584
+ tokens at all and 38% fewer than predicted. gpt-5.1 cached 88% of the
585
+ predicted tokens, gpt-5.2 56 to 57%. OpenAI states that hits are not
586
+ guaranteed and that cached state lives on individual machines. For Anthropic
587
+ the same comparison agreed on whether a request read the cache in 96 to 100%
588
+ of 10,555 requests.
589
+ - **The cache simulation is a documented model, not a measurement.** Request
590
+ bodies carry no timestamps, so it assumes every request arrives within the
591
+ TTL (the steady agent loop this tool targets) and never models an entry
592
+ expiring between requests minutes apart. Matching is at segment granularity:
593
+ the legacy OpenAI approximation cannot give partial credit for a match ending
594
+ inside a segment. Modern OpenAI simulation checks modeled content/message
595
+ endpoints; provider framing and hidden content can change their token counts.
596
+ Prompt identities retain source structure;
597
+ they are not a reproduction of a provider's private prompt renderer or a
598
+ guarantee of its live cache behavior. Each request uses its own model
599
+ for prices, cache thresholds and context windows. `--model` overrides those
600
+ assumptions for every row while preserving captured model identities for
601
+ cache isolation. Unknown IDs use an explicitly reported provider-default
602
+ fallback; missing model names form their own cache group. Invalid Anthropic cache-marker configurations are rejected before
603
+ simulation; [accounting rules](docs/cache-accounting.md).
604
+ - **Anthropic request-setting coverage is partial.** Message caches account for
605
+ tool choice (including parallel-tool policy) and explicit image presence.
606
+ Speed changes isolate system/message entries. Thinking mode, budget and
607
+ top-level effort changes conservatively isolate all three levels; actual
608
+ tool/system survival is model-specific and may differ. Documented mode and
609
+ effort defaults use the recorded model, with no default inference for missing
610
+ or unknown IDs. Per-message effort remains part of the message prefix.
611
+ Structured-output formats and citation enablement affect cache scopes;
612
+ their provider-injected instructions are absent from local token estimates
613
+ and costs. Calibration forwards those settings to `count_tokens` but does
614
+ not establish actual reuse. Other feature toggles, provider transformations
615
+ of thinking history, and images rendered from opaque documents are not fully
616
+ modeled. Compare captured usage before treating predictions as evidence of a hit.
617
+ - **Server-side state is invisible.** Responses can reference stored responses,
618
+ conversations, reusable prompts or input items. The current source preserves
619
+ those units and visible text counts but withholds whole-request totals and
620
+ sequence cache estimates. Opaque reasoning/compaction is also withheld rather
621
+ than tokenized as serialized transport. Nothing is fetched or reconstructed.
622
+ [Boundaries and native SDK counterexamples](studies/stored-context/README.md).
623
+ - **Reported usage requires an explicit pair.** Usage must be beside its wrapped
624
+ request in the same record. Separate responses and streaming deltas are not
625
+ joined implicitly. Historical Claude gateway totals with cache creation are
626
+ ambiguous and remain unavailable; their cache-read counters are retained.
627
+ Captured usage does not authenticate the provider, identify a mismatch's cause,
628
+ or turn simulated costs into observed costs. [Details](docs/reported-usage.md).
629
+ - **Duplicate detection is scoped to the last request of each conversation**,
630
+ so it won't flag the same content appearing in two different conversations.
631
+ - **Conversations are told apart by their content.** Two conversations that
632
+ send exactly the same messages are one as far as the analysis can see, which
633
+ is also how the cache sees them. A conversation whose history is replaced
634
+ wholesale (a summary in place of every earlier message) is read as a new
635
+ conversation, not as a rewrite of the old one.
636
+ - **The web app's exact-tokenizer worker is large.** Its o200k_base vocabulary
637
+ is fetched and validated at startup, before the file chooser appears. The
638
+ self-contained worker is about 2.1 MB uncompressed; moving that existing
639
+ first-analysis download earlier enables the first local import offline.
640
+ Startup creates and terminates one validation worker without sending it a
641
+ request. The flagship example is a separate ~0.48 MB static asset,
642
+ decompressed in the browser with `DecompressionStream`.
643
+ - **Input limits.** The browser accepts up to 50 MiB and the CLI up to 500 MiB,
644
+ for both the input bytes and the decompressed JSON. Reads and gzip inflation
645
+ stop at the limit. Split larger logs into separate sessions. Browser import
646
+ reads and computation can be cancelled or replaced. Parsing, tokenization,
647
+ cache simulation and calibration run in disposable same-origin workers;
648
+ cancellation/reset terminates the worker and discards stale replies. Large
649
+ results still require memory to retain and transfer, and download serialization
650
+ runs on the UI thread. Byte/depth limits do not guarantee a fixed memory or
651
+ processing-time budget.
652
+ - **Worker privacy.** Production fetches only the same-origin analysis asset
653
+ and runs its self-contained code in a blob module that inherits the page's
654
+ CSP, so `connect-src 'self'` covers worker computation too. Bootstrap URLs are
655
+ revoked when work succeeds, fails or is
656
+ cancelled. This uses the documented [worker CSP inheritance rule](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#content_security_policy);
657
+ the production suite probes an off-origin fetch from inside the worker.
658
+ - **Performance.** `npm run bench` times `analyze()` on the flagship session
659
+ (24 requests, 5.7 MB) and on a generated 300-request conversation (12.1 MB,
660
+ 93,900 segments in total). Measured back to back on a 14-vCPU WSL2 machine,
661
+ v0.2.0 took a median 138 ms and 361 ms against 902 ms and 2,770 ms for
662
+ v0.1.0. Pairing requests into conversations (v0.3.0) costs nothing
663
+ measurable: run alternately four times, v0.2.2 took 111-166 ms and
664
+ 423-558 ms, and v0.3.0 120-131 ms and 476-570 ms. That machine was shared
665
+ with other jobs, so run the script for numbers on yours.
666
+ - Synthetic example data is labelled synthetic, in both the CLI filenames and
667
+ the web app's example picker.
668
+
669
+ ## Browser workspace
670
+
671
+ - Requests are keyboard tabs: use Left/Right, Home, and End. Selecting one
672
+ updates its prefix comparison; selecting a comparison opens its destination
673
+ request. In a multi-conversation log, the largest request is chosen using
674
+ the analyzed provider's token counts.
675
+ - Treemap blocks and segment labels open a keyboard-accessible inspector.
676
+ Escape closes it and returns focus. The treemap resizes with the viewport.
677
+ - Large requests show their 128 largest positive-token segments individually
678
+ and group the rest by category, preserving every token in the area totals.
679
+ A grouped block filters the segment table. The table has 100-row pages,
680
+ category and label/path filters, and first/last navigation; every segment
681
+ remains available. Inspector previews show at most 20,000 characters, with
682
+ complete original raw JSON downloads. Sequence navigation and findings are
683
+ still proportional to the number of requests/issues.
684
+ - A failed import preserves the last successful analysis. A newer import or
685
+ **cancel import** discards pending reads; **new analysis** clears the app's
686
+ request data, pasted text, rendered panels, and inspector contents.
687
+
688
+ <details>
689
+ <summary>Updated workspace, desktop and mobile</summary>
690
+
691
+ ![Dark desktop workspace](docs/assets/workspace-dark-1440.png)
692
+ ![Light mobile workspace](docs/assets/workspace-light-375.png)
693
+
694
+ </details>
695
+
696
+ ## Development
697
+
698
+ ```sh
699
+ npm install # installs deps and builds dist/ via the `prepare` script
700
+ npm run lint # eslint
701
+ npm run typecheck # tsc --noEmit, core + cli and the web app
702
+ npm test # vitest
703
+ npm run build # core + cli (dist/) and the web app (web/dist/)
704
+ npx playwright install chromium firefox
705
+ npm run test:browser # production browser workflows + axe, after building
706
+ npm run bench # analyze() timings on the flagship and a 300-request session
707
+ npm run dev:web # Vite dev server for the web app
708
+ ```
709
+
710
+ `src/cli/index.ts` calls `main()` unconditionally rather than comparing
711
+ `import.meta.url` with `argv[1]`, so it also runs through the symlink that `npx`
712
+ and `npm install -g` create.
713
+
714
+ Regenerating the example sessions:
715
+
716
+ ```sh
717
+ node scripts/generate-examples.mjs
718
+ ```
719
+
720
+ This writes the small examples as plain `examples/*.jsonl` and the flagship
721
+ pair as gzipped `examples/*.jsonl.gz`. `web/public/examples` is a committed
722
+ symlink to `../../examples`, so the web app picks up whatever the generator
723
+ writes. The flagship pair is built from `scripts/lib/`: a long, internally
724
+ consistent "enterprise coding agent" system prompt, a 16-tool surface, and a
725
+ library of synthetic file contents, diffs and test/lint/CI output for a
726
+ fictional `ledger-core` billing repository, assembled into a 24-turn
727
+ transcript. Nothing in it is copied from a real project; it exists so the
728
+ treemap and the dollar figures reflect a session at real agent-loop scale.
729
+
730
+ Project layout:
731
+
732
+ ```
733
+ src/core/ shared library: parsers, tokenizers, prefix/diff, cache
734
+ simulation, findings, duplicates, calibration (no I/O, no DOM)
735
+ src/cli/ Node CLI: argument parsing, terminal and HTML report renderers
736
+ web/ Vite + TypeScript web app (imports src/core directly, no framework)
737
+ tests/ vitest suite for core, CLI and input handling
738
+ tests/browser/ Chromium + Firefox workflow and accessibility regressions
739
+ scripts/ example generator and benchmark (not part of the shipped package)
740
+ examples/ synthetic example sessions, shared by the CLI and the web app
741
+ docs/assets/ README screenshots
742
+ ```
743
+
744
+ The [2026-10-04 verification record](docs/verification-context-2026-10-04.md)
745
+ documents input-integrity counterexamples, worker recovery/privacy checks,
746
+ clean package consumption and inspected desktop/phone screenshots.
747
+
748
+ Summary JSON omits raw blocks, prompt identities, analyzed segment text and
749
+ textual diff previews. Match counts/boundaries, source positions, cache steps and
750
+ findings remain. Tool names, paths and rule explanations can still identify an
751
+ application; review those before sharing. Detailed text diffs remain in local
752
+ browser, terminal and HTML inspection. The [follow-up verification record](docs/verification-prompt-2026-10-04.md)
753
+ covers structural comparisons, strict decoding and this export boundary.
754
+
755
+ ## Contributing
756
+
757
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
758
+
759
+ ## License
760
+
761
+ [MIT](LICENSE) © 2026 Anthony Mercer
762
+
763
+ ---
764
+
765
+ <sub>Part of [Officina](https://antonsoo.github.io/officina/), a set of small open-source tools by [Anthony Mercer](https://github.com/antonsoo).</sub>