@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
@@ -0,0 +1,271 @@
1
+ import { describeRequestIndices, groupFindings } from "../core/index.js";
2
+ import { modelGroups, modelLabel, modelNotes, modelSummary } from "../core/model-summary.js";
3
+ import { USAGE_OUTCOME_LABEL, usageDelta, usageNumber, usageSourceLabel } from "../core/usage-labels.js";
4
+ import { bar, blue, bold, cyan, dim, fmtPct, fmtTokens, fmtUsd, fmtUsdRounded, green, magenta, red, severityColor, visible, wrapIndented, yellow } from "./ansi.js";
5
+ const CATEGORY_LABEL = {
6
+ system: "system",
7
+ tools: "tools",
8
+ user: "user text",
9
+ assistant: "assistant text",
10
+ tool_call: "tool calls",
11
+ tool_result: "tool results",
12
+ image: "images",
13
+ thinking: "thinking",
14
+ reference: "unresolved refs",
15
+ };
16
+ const CATEGORY_COLOR = {
17
+ system: blue,
18
+ tools: yellow,
19
+ user: green,
20
+ assistant: yellow,
21
+ tool_call: magenta,
22
+ tool_result: (s) => s,
23
+ image: cyan,
24
+ thinking: red,
25
+ reference: dim,
26
+ };
27
+ // Above this many requests the cache table is abbreviated to its head and tail unless --verbose.
28
+ const CACHE_TABLE_FULL_ROWS = 30;
29
+ const CACHE_TABLE_HEAD = 10;
30
+ const CACHE_TABLE_TAIL = 5;
31
+ export function renderTerminalReport(result, options = {}) {
32
+ const lines = [];
33
+ const { parse, reports, prefixMatches, cacheSimulation, findings, duplicates, model } = result;
34
+ const verbose = options.verbose === true;
35
+ const n = parse.requests.length;
36
+ const mixedModels = modelGroups(result).length > 1;
37
+ const showSpeed = cacheSimulation.actual.some((step) => step.speed !== undefined);
38
+ const openai = cacheSimulation.provider === "openai";
39
+ const modelNote = model.source === "option" ? "set with --model" : "per-request metadata";
40
+ const conversationNote = result.conversations.count > 1 ? ` in ${result.conversations.count} conversations` : "";
41
+ lines.push(bold(`contextscope — ${parse.format} · ${n} request${n === 1 ? "" : "s"}${conversationNote}${parse.autoDetected ? " (auto-detected)" : ""}`));
42
+ lines.push(dim(`priced as ${visible(modelSummary(result))} (${modelNote})${parse.envelope ? ` · requests read from each record's "${visible(parse.envelope)}" field` : ""}`));
43
+ for (const note of modelNotes(result))
44
+ lines.push(...wrapIndented(visible(note), 2));
45
+ if (!parse.complete)
46
+ lines.push(yellow(`Incomplete input: ${parse.skippedRecords} of ${parse.sourceRecords} source records skipped or not analyzable; check parse warnings. Counts and simulations cover the retained content only.`));
47
+ if (options.calibration) {
48
+ const c = options.calibration;
49
+ const error = (c.estimatedTokens - c.exactTokens) / c.exactTokens;
50
+ lines.push(green(`calibrated: request ${c.requestIndex + 1} is ${fmtTokens(c.exactTokens)} tokens by count_tokens (${visible(c.model)}); the estimate was ≈${fmtTokens(c.estimatedTokens)} (${error >= 0 ? "+" : ""}${(error * 100).toFixed(1)}%). Claude figures below are scaled ×${c.scale.toFixed(3)}.`));
51
+ }
52
+ lines.push("");
53
+ lines.push(...reportedUsageSection(result, verbose), "");
54
+ if (verbose) {
55
+ for (const report of reports)
56
+ lines.push(...breakdown(`Request ${report.requestIndex + 1} · ${visible(modelLabel(report.model))}`, report), "");
57
+ }
58
+ else if (reports.length > 0) {
59
+ const complete = reports.every(r => r.totals.claudeTokensEstimate !== null);
60
+ const largest = complete ? reports.reduce((best, r) => (r.totals.claudeTokensEstimate > best.totals.claudeTokensEstimate ? r : best)) : reports.at(-1);
61
+ const title = reports.length === 1 ? "Request 1" : `${complete ? "Largest" : "Latest"} request: ${largest.requestIndex + 1} of ${reports.length}`;
62
+ lines.push(...breakdown(`${title} · ${visible(modelLabel(largest.model))}`, largest));
63
+ if (reports.length > 1)
64
+ lines.push(dim(" (every request's breakdown: --verbose)"));
65
+ lines.push("");
66
+ }
67
+ if (prefixMatches.length > 0)
68
+ lines.push(...prefixSection(result, verbose), "");
69
+ lines.push(bold(`Cache simulation (${cacheSimulation.provider}, ${visible(modelSummary(result))})`));
70
+ if (cacheSimulation.unavailableReason)
71
+ lines.push(...wrapIndented(visible(cacheSimulation.unavailableReason), 2));
72
+ lines.push(dim(` ${"request".padEnd(10)} ${"read".padStart(8)} ${openai ? "write(30m)" : `${"write(5m)".padStart(8)} ${"write(1h)".padStart(8)}`} ${"uncached".padStart(9)} ${"cost".padStart(9)}${openai ? " mode" : ""}${showSpeed ? " modeled speed" : ""}${mixedModels ? " model" : ""}`));
73
+ const rows = cacheSimulation.actual.map((step, i) => ` req ${String(i + 1).padEnd(6)} ${fmtTokens(step.readTokens).padStart(8)} ${openai ? fmtTokens(step.unavailableReason ? null : step.writeTokens30m ?? 0).padStart(10) : `${fmtTokens(step.writeTokens5m).padStart(8)} ${fmtTokens(step.writeTokens1h).padStart(8)}`} ${fmtTokens(step.uncachedTokens).padStart(9)} ${fmtUsd(step.costUsd).padStart(9)}${openai ? ` ${(step.cacheMode ?? "legacy").padEnd(8)}` : ""}${showSpeed ? ` ${step.speed ?? "standard"}` : ""}${mixedModels ? ` ${visible(modelLabel(reports[i].model))}` : ""}`);
74
+ if (verbose || rows.length <= CACHE_TABLE_FULL_ROWS) {
75
+ lines.push(...rows);
76
+ }
77
+ else {
78
+ const hidden = rows.length - CACHE_TABLE_HEAD - CACHE_TABLE_TAIL;
79
+ lines.push(...rows.slice(0, CACHE_TABLE_HEAD), dim(` ⋯ ${hidden} more requests (--verbose) ⋯`), ...rows.slice(-CACHE_TABLE_TAIL));
80
+ }
81
+ lines.push(dim(` total simulated cost: ${fmtUsd(cacheSimulation.totalActualCostUsd)}`));
82
+ const optimizedNote = cacheSimulation.provider === "anthropic"
83
+ ? "content normalized; tail breakpoint added, or last marker moved if four slots are used"
84
+ : "content normalized; OpenAI markers unchanged";
85
+ lines.push(dim(` total optimized cost: ${fmtUsd(cacheSimulation.totalOptimizedCostUsd)} (${optimizedNote})`));
86
+ if (cacheSimulation.totalActualCostUsd !== undefined && cacheSimulation.totalOptimizedCostUsd !== undefined) {
87
+ const savings = cacheSimulation.totalActualCostUsd - cacheSimulation.totalOptimizedCostUsd;
88
+ // Below half of the last digit shown, the line would read "would save $0.0000 (0%)".
89
+ if (savings >= 0.00005) {
90
+ const how = cacheSimulation.provider === "anthropic" ? "applying the fixes below (plus that trailing breakpoint)" : "applying the fixes below";
91
+ lines.push(green(` → ${how} would save ${fmtUsd(savings)} (${((savings / cacheSimulation.totalActualCostUsd) * 100).toFixed(0)}%) on this sequence`));
92
+ lines.push(dim(` ≈ ${fmtUsdRounded(savings * 1000)} per 1,000 sessions shaped like this one`));
93
+ }
94
+ }
95
+ lines.push("");
96
+ const groups = groupFindings(findings);
97
+ if (groups.length > 0) {
98
+ const recurring = findings.length > groups.length ? dim(` from ${findings.length} findings across the sequence`) : "";
99
+ lines.push(bold(`Findings (${groups.length} issue${groups.length === 1 ? "" : "s"})`) + recurring);
100
+ for (const group of groups) {
101
+ const color = severityColor(group.severity);
102
+ const where = describeRequestIndices(group.requestIndices);
103
+ const times = group.requestIndices.length > 1 ? `, ${group.requestIndices.length}×` : "";
104
+ lines.push(` ${color(`[${group.severity}]`)} ${bold(visible(group.title))} ${dim(`(${where}${times})`)}`);
105
+ lines.push(...wrapIndented(visible(group.detail), 6));
106
+ }
107
+ lines.push("");
108
+ }
109
+ else {
110
+ lines.push(dim("No supported cache or duplicate-content issues detected. This does not verify live cache hits."));
111
+ lines.push("");
112
+ }
113
+ if (duplicates.length > 0) {
114
+ lines.push(bold(`Duplicate content (${duplicates.length} group${duplicates.length === 1 ? "" : "s"})`));
115
+ for (const group of duplicates) {
116
+ lines.push(` ${group.members.length}× "${visible(group.members[0].label)}" — ${group.matchKind === "exact" ? "identical text" : `at least ${Math.floor(group.similarity * 100)}% word-shingle similarity`}; ≈${fmtTokens(group.estimatedReviewTokens)} tokens in later matches to review`);
117
+ }
118
+ lines.push("");
119
+ }
120
+ if (parse.warnings.length > 0) {
121
+ lines.push(yellow(`${parse.warnings.length} parse warning${parse.warnings.length === 1 ? "" : "s"}:`));
122
+ for (const w of parse.warnings)
123
+ lines.push(dim(` ${visible(w.message)}`));
124
+ }
125
+ return lines.join("\n").replace(/\n+$/, "");
126
+ }
127
+ function reportedUsageSection(result, verbose) {
128
+ const review = result.usageComparison;
129
+ if (review.capturedRequests === 0)
130
+ return [dim(result.cacheSimulation.unavailableReason ? "No paired response usage. Local cache estimates are unavailable." : "No paired response usage. Cache reads and costs below are simulations.")];
131
+ const out = [bold("Reported usage vs simulation"), dim(" Each total compares the same covered requests. Delta = estimate/simulation - reported.")];
132
+ out.push(dim(" metric coverage reported estimated/sim. delta"));
133
+ for (const [label, metric] of [["input tokens", review.input], ["cache reads", review.cacheRead]]) {
134
+ out.push(` ${label.padEnd(15)} ${`${metric.requestIndices.length}/${review.rows.length}`.padStart(8)} ${usageNumber(metric.reportedTokens).padStart(14)} ${usageNumber(metric.simulatedTokens).padStart(17)} ${usageDelta(metric.deltaTokens).padStart(13)}`);
135
+ }
136
+ const misses = review.readOutcomes.simulated_hit_reported_zero;
137
+ const unexpected = review.readOutcomes.reported_hit_simulated_zero;
138
+ out.push(` ${misses} simulated hit / reported zero; ${unexpected} reported hit / simulated zero.`);
139
+ out.push(dim(` ${review.readOutcomes.unavailable} read comparisons unavailable; ${review.invalidRequestIndices.length} invalid usage record(s) excluded. n/a is not zero.`));
140
+ out.push(dim(" Counts do not establish a cause: cache routing, eviction, timing and hidden context are not captured."));
141
+ out.push(dim(" request / source reported read simulated read comparison"));
142
+ const rows = verbose || review.rows.length <= CACHE_TABLE_FULL_ROWS ? review.rows : [...review.rows.slice(0, CACHE_TABLE_HEAD), ...review.rows.slice(-CACHE_TABLE_TAIL)];
143
+ for (const row of rows) {
144
+ const request = result.parse.requests[row.requestIndex];
145
+ const source = usageSourceLabel(request);
146
+ out.push(` ${`req ${row.requestIndex + 1} / ${source}`.padEnd(25)} ${usageNumber(row.reportedReadTokens).padStart(12)} ${fmtTokens(row.simulatedReadTokens).padStart(17)} ${USAGE_OUTCOME_LABEL[row.readOutcome]}`);
147
+ const usage = request.reportedUsage;
148
+ if (verbose && usage) {
149
+ out.push(dim(` ${usage.schema} · ${usage.status}; total input ${usageNumber(usage.inputTokens)}, cache writes ${usageNumber(usage.cacheWriteTokens)}, output ${usageNumber(usage.outputTokens)}`));
150
+ for (const counter of usage.counters)
151
+ out.push(dim(` ${counter.path} = ${counter.status === "reported" ? fmtTokens(counter.value) : counter.status}`));
152
+ for (const issue of usage.issues)
153
+ out.push(yellow(` ${issue}`));
154
+ for (const note of usage.notes)
155
+ out.push(dim(` ${note}`));
156
+ }
157
+ }
158
+ if (rows.length < review.rows.length)
159
+ out.push(dim(` ${review.rows.length - rows.length} rows omitted. --verbose shows every row and source counter; --json and --html include all rows.`));
160
+ else if (!verbose)
161
+ out.push(dim(" --verbose shows the original counter paths; --json and --html retain all evidence."));
162
+ for (const index of review.uncomparedRequestIndices) {
163
+ const request = result.parse.requests[index];
164
+ out.push(yellow(` req ${index + 1} / ${usageSourceLabel(request)}: paired usage retained, but no analyzable prompt; excluded from comparisons.`));
165
+ if (verbose)
166
+ for (const counter of request.reportedUsage.counters)
167
+ out.push(dim(` ${counter.path} = ${counter.status === "reported" ? fmtTokens(counter.value) : counter.status}`));
168
+ }
169
+ if (!verbose) {
170
+ for (const index of review.invalidRequestIndices.slice(0, 5))
171
+ out.push(yellow(` req ${index + 1}: ${result.parse.requests[index].reportedUsage.issues.join(" ")}`));
172
+ if (review.invalidRequestIndices.length > 5)
173
+ out.push(yellow(` ${review.invalidRequestIndices.length - 5} more invalid usage records; inspect the full export.`));
174
+ }
175
+ for (const issue of review.issues)
176
+ out.push(yellow(` ${issue}`));
177
+ return out;
178
+ }
179
+ function breakdown(title, report) {
180
+ const claude = report.totals.claudeTokensEstimate === null ? "Claude tokens unavailable" : `≈${fmtTokens(report.totals.claudeTokensEstimate)} Claude tokens`;
181
+ const openai = report.totals.openaiTokens === null ? "OpenAI tokens unavailable" : `${fmtTokens(report.totals.openaiTokens)} OpenAI (o200k_base) tokens`;
182
+ const out = [
183
+ bold(title) +
184
+ dim(` ${claude} · ${openai}${report.percentOfContextWindow !== undefined ? ` · ${fmtPct(report.percentOfContextWindow)} of context window` : ""}`),
185
+ ];
186
+ for (const cat of report.byCategory) {
187
+ const label = CATEGORY_LABEL[cat.category].padEnd(15);
188
+ const tokens = fmtTokens(cat.claudeTokensEstimate).padStart(8);
189
+ const total = report.totals.claudeTokensEstimate;
190
+ const fraction = total === null || cat.claudeTokensEstimate === null ? null : total > 0 ? cat.claudeTokensEstimate / total : 0;
191
+ out.push(` ${CATEGORY_COLOR[cat.category](fraction === null ? " ".repeat(20) : bar(fraction, 20))} ${label} ${tokens} ≈tok ${dim(`(${cat.segmentCount} segment${cat.segmentCount === 1 ? "" : "s"})`)}`);
192
+ }
193
+ return out;
194
+ }
195
+ /**
196
+ * A pair is healthy when the later request only appends to the earlier one: everything the earlier
197
+ * request sent is still there, byte for byte. Otherwise it "breaks" at the first segment that
198
+ * changed. Default output lists the breaks grouped by where they happen; --verbose lists every pair.
199
+ */
200
+ function prefixSection(result, verbose) {
201
+ const { parse, prefixMatches, conversations } = result;
202
+ const out = [bold("Prefix match across the sequence")];
203
+ if (conversations.count > 1) {
204
+ out.push(dim(` ${conversations.count} conversations in this file; each request is compared with the request it continues`));
205
+ }
206
+ if (verbose) {
207
+ for (const match of prefixMatches) {
208
+ const total = parse.requests[match.toIndex].segments.length;
209
+ const pct = total > 0 ? match.matchedSegments / total : 0;
210
+ out.push(` req ${match.fromIndex + 1} → req ${match.toIndex + 1}: ${bar(pct, 20)} ${match.matchedSegments}/${total} segments matched, ${match.matchedClaudeTokensEstimate === null ? "token count unavailable" : `≈${fmtTokens(match.matchedClaudeTokensEstimate)} tokens`}` +
211
+ (match.relation === "new_conversation"
212
+ ? dim(` new conversation${match.divergedAt?.fromSegmentId ? `, setup differs at ${visible(match.divergedAt.fromSegmentId)}` : ""}`)
213
+ : match.divergedAt
214
+ ? dim(` diverges at ${visible(match.divergedAt.toSegmentId ?? "(end)")}`)
215
+ : dim(" (identical)")));
216
+ }
217
+ return out;
218
+ }
219
+ // A pair breaks when something the earlier request sent is not there any more, byte for byte.
220
+ // For a new conversation that means its setup: the rest of the other conversation was never
221
+ // its to re-send.
222
+ const breaks = new Map();
223
+ let starts = 0;
224
+ let brokenStarts = 0;
225
+ for (const match of prefixMatches) {
226
+ const previous = parse.requests[match.fromIndex];
227
+ const startsConversation = match.relation === "new_conversation";
228
+ if (startsConversation)
229
+ starts++;
230
+ const sent = startsConversation ? setupLength(previous.segments) : previous.segments.length;
231
+ if (match.matchedSegments >= sent)
232
+ continue;
233
+ if (startsConversation)
234
+ brokenStarts++;
235
+ const label = previous.segments[match.matchedSegments].label;
236
+ breaks.set(label, [...(breaks.get(label) ?? []), match]);
237
+ }
238
+ const total = prefixMatches.length;
239
+ const broken = [...breaks.values()].reduce((sum, pairs) => sum + pairs.length, 0);
240
+ const followUps = total - starts;
241
+ const startsNote = starts === 0 ? [] : [dim(` ${starts} request${starts === 1 ? " starts a new conversation" : "s start a new conversation"} on a setup already sent${brokenStarts > 0 ? ` (${brokenStarts} with a changed setup, above)` : ""}`)];
242
+ if (broken === 0) {
243
+ if (starts === 0)
244
+ out.push(green(` all ${total} consecutive pair${total === 1 ? "" : "s"} only append to the previous request`));
245
+ else if (followUps > 0)
246
+ out.push(green(` all ${followUps} follow-up request${followUps === 1 ? "" : "s"} only append to the request they continue`));
247
+ out.push(...startsNote);
248
+ return out;
249
+ }
250
+ const pair = (match) => `req ${match.fromIndex + 1} → ${match.toIndex + 1}`;
251
+ for (const [label, pairs] of breaks) {
252
+ const span = pairs.length === 1 ? pair(pairs[0]) : `${pair(pairs[0])} … ${pair(pairs[pairs.length - 1])}`;
253
+ out.push(` ${red(`${pairs.length} of ${total}`)} pair${pairs.length === 1 ? "" : "s"} rewrite content already sent, starting at ${bold(`"${visible(label)}"`)} ${dim(`(${span})`)}`);
254
+ }
255
+ if (starts === 0)
256
+ out.push(dim(` ${total - broken} of ${total} only append to the previous request`));
257
+ else {
258
+ if (followUps > 0)
259
+ out.push(dim(` ${followUps - (broken - brokenStarts)} of ${followUps} follow-up request${followUps === 1 ? "" : "s"} only append to the request they continue`));
260
+ out.push(...startsNote);
261
+ }
262
+ return out;
263
+ }
264
+ /** The leading tool definitions and system blocks: what a request sends before its conversation. */
265
+ function setupLength(segments) {
266
+ let n = 0;
267
+ while (n < segments.length && (segments[n].category === "tools" || segments[n].category === "system"))
268
+ n++;
269
+ return n;
270
+ }
271
+ //# sourceMappingURL=terminal-report.js.map
@@ -0,0 +1,2 @@
1
+ import type { AnalysisResult } from "../core/types.js";
2
+ export declare function renderUsageHtml(result: AnalysisResult): string;
@@ -0,0 +1,33 @@
1
+ import { USAGE_OUTCOME_LABEL, usageDelta, usageNumber, usageSourceLabel } from "../core/usage-labels.js";
2
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3
+ export function renderUsageHtml(result) {
4
+ const review = result.usageComparison;
5
+ if (!review.capturedRequests)
6
+ return result.cacheSimulation.unavailableReason
7
+ ? '<p class="muted">No paired response usage. Local cache estimates are unavailable.</p>'
8
+ : '<p class="muted">No paired response usage. Cache reads and costs are simulations.</p>';
9
+ const metrics = [['Input tokens', review.input], ['Cache reads', review.cacheRead]].map(([label, metric]) => `<tr><th scope="row">${label}</th><td>${metric.requestIndices.length}/${review.rows.length}</td><td>${usageNumber(metric.reportedTokens)}</td><td>${usageNumber(metric.simulatedTokens)}</td><td>${usageDelta(metric.deltaTokens)}</td></tr>`).join("");
10
+ const rows = review.rows.map((row) => `<tr><th scope="row"><a href="#usage-${row.requestIndex}">req ${row.requestIndex + 1}</a><br>${usageSourceLabel(result.parse.requests[row.requestIndex])}</th><td>${usageNumber(row.reportedInputTokens)}</td><td>${usageNumber(row.estimatedInputTokens)}</td><td>${usageNumber(row.reportedReadTokens)}</td><td>${usageNumber(row.simulatedReadTokens)}</td><td>${USAGE_OUTCOME_LABEL[row.readOutcome]}</td></tr>`).join("");
11
+ const details = result.parse.requests.filter((request) => request.segments.length || request.reportedUsage).map((request) => {
12
+ const index = request.index;
13
+ const usage = request.reportedUsage;
14
+ return `<details id="usage-${index}" class="usage-evidence"><summary>Request ${index + 1} · ${usageSourceLabel(request)} · ${usage?.status ?? "not recorded"}</summary>
15
+ ${!request.segments.length ? '<p>No analyzable prompt; excluded from comparisons. Paired usage is retained below.</p>' : ""}
16
+ ${usage ? `<p>${usage.schema}; source: ${esc(usage.sources.join(", "))}. Reported input: ${usageNumber(usage.inputTokens)}; cache reads: ${usageNumber(usage.cacheReadTokens)}; cache writes: ${usageNumber(usage.cacheWriteTokens)}; output: ${usageNumber(usage.outputTokens)}.</p>
17
+ ${usage.issues.length ? `<ul>${usage.issues.map((issue) => `<li>${esc(issue)}</li>`).join("")}</ul>` : ""}
18
+ ${usage.notes.map((note) => `<p>${esc(note)}</p>`).join("")}
19
+ <div class="table-scroll" tabindex="0" role="group" aria-label="Source counters for request ${index + 1}"><table><thead><tr><th scope="col">Original counter path</th><th scope="col">Value / state</th></tr></thead><tbody>${usage.counters.map((counter) => `<tr><th scope="row"><code>${counter.path}</code></th><td>${counter.status === "reported" ? usageNumber(counter.value) : counter.status}</td></tr>`).join("")}</tbody></table></div>` : "<p>No paired response usage for this request.</p>"}
20
+ </details>`;
21
+ }).join("");
22
+ return `<section class="card"><h2>Reported usage vs simulation</h2>
23
+ <p>Each total compares the same covered requests. Delta = estimate/simulation minus reported. Missing or invalid counts are n/a, never zero.</p>
24
+ <div class="table-scroll" tabindex="0" role="group" aria-label="Usage totals"><table><thead><tr><th scope="col">Metric</th><th scope="col">Coverage</th><th scope="col">Reported</th><th scope="col">Estimated / simulated</th><th scope="col">Delta</th></tr></thead><tbody>${metrics}</tbody></table></div>
25
+ <p>${review.readOutcomes.simulated_hit_reported_zero} simulated hit / reported zero; ${review.readOutcomes.reported_hit_simulated_zero} reported hit / simulated zero. ${review.readOutcomes.unavailable} read comparison unavailable. ${review.invalidRequestIndices.length} invalid usage record(s) excluded.</p>
26
+ ${review.uncomparedRequestIndices.length ? `<p>${review.uncomparedRequestIndices.length} request(s) have paired usage but no analyzable prompt; excluded from comparisons. Their original counters are retained below.</p>` : ""}
27
+ <p class="muted">Counts do not establish a cause: cache routing, eviction, timing and hidden context are not captured. Reuse on both sides does not mean the token counts agree. Reported writes are retained below; ${result.cacheSimulation.unavailableReason ? "local cache costs are unavailable" : "costs remain simulated"}.</p>
28
+ ${review.issues.map((issue) => `<p>${esc(issue)}</p>`).join("")}
29
+ <div class="table-scroll" tabindex="0" role="group" aria-label="Per-request usage comparison"><table><thead><tr><th scope="col">Request / source</th><th scope="col">Reported input</th><th scope="col">Estimated input</th><th scope="col">Reported read</th><th scope="col">Simulated read</th><th scope="col">Read comparison</th></tr></thead><tbody>${rows}</tbody></table></div>
30
+ <h3>Original counters</h3>${details}
31
+ </section>`;
32
+ }
33
+ //# sourceMappingURL=usage-html.js.map
@@ -0,0 +1,2 @@
1
+ /** Printed by --version; tests/cli.test.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.3.3";
@@ -0,0 +1,3 @@
1
+ /** Printed by --version; tests/cli.test.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.3.3";
3
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1,12 @@
1
+ export interface ReportPath {
2
+ path: string;
3
+ label: "HTML" | "JSON";
4
+ }
5
+ export interface ReportFile extends ReportPath {
6
+ text: string;
7
+ }
8
+ /** Validate every destination together, before analysis or optional calibration. */
9
+ export declare function validateReportPaths(input: string, reports: readonly ReportPath[]): void;
10
+ /** Stage all reports before replacing any; each replacement is atomic.
11
+ * This is not a transaction across both reports or a lock against other writers. */
12
+ export declare function writeReports(input: string, reports: readonly ReportFile[]): void;
@@ -0,0 +1,82 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, fsyncSync, lstatSync, openSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ function missing(error) {
5
+ return error.code === "ENOENT";
6
+ }
7
+ /** Validate every destination together, before analysis or optional calibration. */
8
+ export function validateReportPaths(input, reports) {
9
+ if (!reports.length)
10
+ return;
11
+ const seen = [
12
+ { label: "input", path: realpathSync(input), info: statSync(input, { bigint: true }) },
13
+ ];
14
+ for (const report of reports) {
15
+ const path = resolve(report.path);
16
+ const info = (() => {
17
+ try {
18
+ return lstatSync(path, { bigint: true });
19
+ }
20
+ catch (error) {
21
+ if (missing(error))
22
+ return undefined;
23
+ throw error;
24
+ }
25
+ })();
26
+ // Do not follow a link or replace the link itself with a regular file.
27
+ // Parents may be symlinked; their resolved names still identify the same file.
28
+ if (info?.isSymbolicLink())
29
+ throw new Error(`${report.label} output must not be a symbolic link: ${report.path}`);
30
+ if (info && !info.isFile())
31
+ throw new Error(`${report.label} output must be a regular file: ${report.path}`);
32
+ const canonical = join(realpathSync(dirname(path)), basename(path));
33
+ for (const previous of seen) {
34
+ if (canonical === previous.path || (info && previous.info && info.dev === previous.info.dev && info.ino === previous.info.ino)) {
35
+ throw new Error(`${report.label} output and ${previous.label} must use distinct files, including file aliases.`);
36
+ }
37
+ }
38
+ seen.push({ label: report.label, path: canonical, info });
39
+ }
40
+ }
41
+ /** Stage all reports before replacing any; each replacement is atomic.
42
+ * This is not a transaction across both reports or a lock against other writers. */
43
+ export function writeReports(input, reports) {
44
+ validateReportPaths(input, reports);
45
+ const staged = [];
46
+ const errors = [];
47
+ try {
48
+ for (const report of reports) {
49
+ const destination = resolve(report.path);
50
+ const temporary = join(dirname(destination), `.contextscope-${randomUUID()}.tmp`);
51
+ const fd = openSync(temporary, "wx", 0o600);
52
+ staged.push({ temporary, destination });
53
+ try {
54
+ writeFileSync(fd, report.text, "utf8");
55
+ fsyncSync(fd);
56
+ }
57
+ finally {
58
+ closeSync(fd);
59
+ }
60
+ }
61
+ validateReportPaths(input, reports);
62
+ for (const file of staged)
63
+ renameSync(file.temporary, file.destination);
64
+ }
65
+ catch (error) {
66
+ errors.push(error);
67
+ }
68
+ finally {
69
+ for (const file of staged) {
70
+ try {
71
+ unlinkSync(file.temporary);
72
+ }
73
+ catch (error) {
74
+ if (!missing(error))
75
+ errors.push(error);
76
+ }
77
+ }
78
+ }
79
+ if (errors.length)
80
+ throw errors[0];
81
+ }
82
+ //# sourceMappingURL=write-reports.js.map
@@ -0,0 +1,13 @@
1
+ import type { AnalysisOptions, AnalysisResult } from "./types.js";
2
+ /** Runs the full contextscope pipeline: parse -> per-request token report -> prefix diffs
3
+ * (actual and volatile-normalized) -> cache simulation (actual and optimized) -> duplicates -> findings. */
4
+ export declare function analyze(input: string, options?: AnalysisOptions): AnalysisResult;
5
+ export { ContextScopeParseError, parseInput } from "./parse.js";
6
+ export { computeAllPrefixMatches, computePrefixMatch } from "./prefix.js";
7
+ export { threadRequests, type Threads } from "./threads.js";
8
+ export * from "./types.js";
9
+ export { toJsonReport } from "./json-report.js";
10
+ export { ANTHROPIC_MODELS, OPENAI_MODELS, DEFAULT_ANTHROPIC_MODEL, DEFAULT_OPENAI_MODEL, findAnthropicModel, findOpenAiModel, normalizeModelId, resolveModel, } from "./pricing.js";
11
+ export { groupFindings, describeRequestIndices, type FindingGroup } from "./group-findings.js";
12
+ export { calibrateRequest, calibrationScale, countRequestTokens, countTokensBody, CalibrationError, type CalibrationResult } from "./calibrate.js";
13
+ export { clearMergeCache as clearTokenCache } from "gpt-tokenizer/encoding/o200k_base";
@@ -0,0 +1,99 @@
1
+ import { ContextScopeParseError, parseInput } from "./parse.js";
2
+ import { computeAllPrefixMatches } from "./prefix.js";
3
+ import { prefixPaths, threadRequests } from "./threads.js";
4
+ import { buildRequestReport } from "./report.js";
5
+ import { simulateAnthropicCacheSequence } from "./cache-anthropic.js";
6
+ import { simulateOpenAiCacheSequence } from "./cache-openai.js";
7
+ import { findDuplicates } from "./duplicates.js";
8
+ import { computeFindings } from "./findings.js";
9
+ import { resolveModel } from "./pricing.js";
10
+ import { compareReportedUsage } from "./usage-comparison.js";
11
+ /** Runs the full contextscope pipeline: parse -> per-request token report -> prefix diffs
12
+ * (actual and volatile-normalized) -> cache simulation (actual and optimized) -> duplicates -> findings. */
13
+ export function analyze(input, options = {}) {
14
+ const parse = parseInput(input, options.format);
15
+ const { format } = parse;
16
+ const scale = validScale(options.claudeTokenScale);
17
+ if (scale !== 1)
18
+ parse.requests = parse.requests.map((r) => scaleClaudeEstimates(r, scale));
19
+ const { requests } = parse;
20
+ const model = resolveModel(format, options.model, requests.map((r) => r.model));
21
+ const reports = requests.map((r) => buildRequestReport(r, format, options.model));
22
+ // Which earlier request each request continues: the line before it only when the file is one
23
+ // conversation (see threads.ts).
24
+ const paths = prefixPaths(requests, false);
25
+ const optimizedPaths = prefixPaths(requests, true);
26
+ const threads = threadRequests(requests, paths, optimizedPaths);
27
+ const prefixMatches = computeAllPrefixMatches(requests, false, true, threads);
28
+ let cacheSimulation;
29
+ if (format === "anthropic") {
30
+ const actual = simulateAnthropicCacheSequence(requests, paths, options.model, false);
31
+ const optimized = simulateAnthropicCacheSequence(requests, optimizedPaths, options.model, true);
32
+ cacheSimulation = {
33
+ provider: "anthropic",
34
+ model: model.id,
35
+ actual,
36
+ optimized,
37
+ totalActualCostUsd: sumCost(actual),
38
+ totalOptimizedCostUsd: sumCost(optimized),
39
+ };
40
+ }
41
+ else {
42
+ const actual = simulateOpenAiCacheSequence(requests, paths, options.model);
43
+ const optimized = simulateOpenAiCacheSequence(requests, optimizedPaths, options.model);
44
+ cacheSimulation = {
45
+ provider: "openai",
46
+ model: model.id,
47
+ actual,
48
+ optimized,
49
+ totalActualCostUsd: sumCost(actual),
50
+ totalOptimizedCostUsd: sumCost(optimized),
51
+ };
52
+ }
53
+ const unavailableReason = cacheSimulation.actual.find(step => step.unavailableReason)?.unavailableReason;
54
+ if (unavailableReason)
55
+ cacheSimulation.unavailableReason = unavailableReason;
56
+ // Each conversation is scanned where it is longest: at the requests no later request continues.
57
+ const continued = new Set(prefixMatches.filter((m) => m.relation !== "new_conversation").map((m) => m.fromIndex));
58
+ const duplicates = findDuplicates(requests, requests.map((r) => r.index).filter((i) => !continued.has(i)));
59
+ const findings = computeFindings(format, requests, prefixMatches, options.model, duplicates, cacheSimulation);
60
+ const conversations = { count: threads.conversationCount, byRequest: threads.conversation };
61
+ const usageComparison = compareReportedUsage(requests, reports, cacheSimulation);
62
+ return { parse, model, claudeTokenScale: scale, reports, prefixMatches, conversations, cacheSimulation, usageComparison, findings, duplicates };
63
+ }
64
+ function validScale(scale) {
65
+ if (scale === undefined || !Number.isFinite(scale) || scale <= 0)
66
+ return 1;
67
+ return scale;
68
+ }
69
+ function scaleClaudeEstimates(request, scale) {
70
+ let total = 0;
71
+ return {
72
+ ...request,
73
+ segments: request.segments.map((s) => {
74
+ if (s.claudeTokensEstimate === null)
75
+ return s;
76
+ const tokens = Math.max(s.claudeTokensEstimate > 0 ? 1 : 0, Math.round(s.claudeTokensEstimate * scale));
77
+ total += tokens;
78
+ if (!Number.isSafeInteger(total))
79
+ throw new ContextScopeParseError(`Calibration scale makes request ${request.index + 1} token counts exceed the safe integer range. Use a smaller measured count or scale.`);
80
+ return { ...s, claudeTokensEstimate: tokens };
81
+ }),
82
+ };
83
+ }
84
+ function sumCost(steps) {
85
+ if (steps.some((s) => s.costUsd === undefined))
86
+ return undefined;
87
+ return steps.reduce((sum, s) => sum + (s.costUsd ?? 0), 0);
88
+ }
89
+ export { ContextScopeParseError, parseInput } from "./parse.js";
90
+ export { computeAllPrefixMatches, computePrefixMatch } from "./prefix.js";
91
+ export { threadRequests } from "./threads.js";
92
+ export * from "./types.js";
93
+ export { toJsonReport } from "./json-report.js";
94
+ export { ANTHROPIC_MODELS, OPENAI_MODELS, DEFAULT_ANTHROPIC_MODEL, DEFAULT_OPENAI_MODEL, findAnthropicModel, findOpenAiModel, normalizeModelId, resolveModel, } from "./pricing.js";
95
+ export { groupFindings, describeRequestIndices } from "./group-findings.js";
96
+ export { calibrateRequest, calibrationScale, countRequestTokens, countTokensBody, CalibrationError } from "./calibrate.js";
97
+ // Tokenizer merge caches retain input substrings; interactive callers can release them on reset.
98
+ export { clearMergeCache as clearTokenCache } from "gpt-tokenizer/encoding/o200k_base";
99
+ //# sourceMappingURL=analyze.js.map
@@ -0,0 +1,6 @@
1
+ import type { Segment } from "./types.js";
2
+ /** Consecutive tool-use blocks and consecutive tool-result blocks each occupy one lookup position. */
3
+ export declare function anthropicPositions(segments: readonly Segment[]): number[];
4
+ export declare function isCacheableSegment(segment: Segment): boolean;
5
+ /** Automatic and hypothetical tail markers must skip thinking and empty text. */
6
+ export declare function lastCacheableSegment(segments: readonly Segment[]): number;
@@ -0,0 +1,48 @@
1
+ import { isRecord } from "./json-utils.js";
2
+ function isEmptyMessageHeader(segment) {
3
+ if (!/^messages\[\d+\]\.content$/.test(segment.path) || !isRecord(segment.raw))
4
+ return false;
5
+ const content = segment.raw.content;
6
+ return content === null || content === "" || (Array.isArray(content) && content.length === 0);
7
+ }
8
+ /** Consecutive tool-use blocks and consecutive tool-result blocks each occupy one lookup position. */
9
+ export function anthropicPositions(segments) {
10
+ let position = -1;
11
+ let run;
12
+ return segments.map((segment) => {
13
+ if (isEmptyMessageHeader(segment)) {
14
+ run = undefined;
15
+ return position;
16
+ }
17
+ const kind = segment.category === "tool_call" || segment.category === "tool_result" ? segment.category : undefined;
18
+ if (kind === undefined || kind !== run)
19
+ position++;
20
+ run = kind;
21
+ return position;
22
+ });
23
+ }
24
+ export function isCacheableSegment(segment) {
25
+ if (segment.category === "thinking")
26
+ return false;
27
+ // A retained empty message header (for example, per-message effort) is
28
+ // structural evidence, not a content block where a marker may be placed.
29
+ if (isEmptyMessageHeader(segment))
30
+ return false;
31
+ // An empty tool_result is still a block with routing information. Only empty
32
+ // text is forbidden; counted text alone cannot decide whether a block exists.
33
+ if (typeof segment.raw === "string")
34
+ return segment.raw.length > 0;
35
+ if (isRecord(segment.raw) && segment.raw.type === "text")
36
+ return segment.text.length > 0;
37
+ return true;
38
+ }
39
+ /** Automatic and hypothetical tail markers must skip thinking and empty text. */
40
+ export function lastCacheableSegment(segments) {
41
+ for (let i = segments.length - 1; i >= 0; i--) {
42
+ const segment = segments[i];
43
+ if (isCacheableSegment(segment))
44
+ return i;
45
+ }
46
+ return -1;
47
+ }
48
+ //# sourceMappingURL=anthropic-breakpoints.js.map
@@ -0,0 +1,12 @@
1
+ import type { ParsedRequest, Segment } from "./types.js";
2
+ /** Message entries depend on request settings even when their visible prefix is unchanged.
3
+ * Tools and the top-level system prompt survive these two documented invalidators.
4
+ * https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache
5
+ */
6
+ export interface AnthropicMessageCacheScope {
7
+ toolChoice: string;
8
+ hasImages: boolean;
9
+ }
10
+ export declare function isAnthropicMessageSegment(segment: Segment): boolean;
11
+ export declare function anthropicMessageCacheScope(request: ParsedRequest): AnthropicMessageCacheScope;
12
+ export declare function anthropicMessageCacheKey(scope: AnthropicMessageCacheScope): string;