@clear-capabilities/agentic-security-scanner 0.120.0 → 0.122.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.
- package/CHANGELOG.md +50 -0
- package/bin/agentic-security.js +30 -0
- package/dist/752.index.js +290 -0
- package/dist/985.index.js +316 -2
- package/dist/agentic-security.mjs +1 -1
- package/dist/agentic-security.mjs.sha256 +1 -1
- package/package.json +6 -3
- package/src/mcp/tools.js +28 -1
- package/src/posture/cache-economics.js +269 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,55 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.122.0 — cache economics Phase B (depth-first, subagent offload, cost HUD)
|
|
4
|
+
|
|
5
|
+
Completes the cache-economics program (PRD `docs/CACHE_ECONOMICS_PRD.md`, F4–F6) on
|
|
6
|
+
top of the v0.121.0 measured foundation. All in `hooks/model-cost-advisor.js`,
|
|
7
|
+
`hooks/lib/transcript.js`, and `scanner/src/posture/cache-economics.js`.
|
|
8
|
+
|
|
9
|
+
- **F4 — depth-first routing.** A model switch is now chosen over a cache-safe effort
|
|
10
|
+
drop only when it saves *materially* more (`A.savings ≥ B.savings × (1 +
|
|
11
|
+
depthFirstMargin)`, default 0.25). Effort is the primary lever; switching is the
|
|
12
|
+
break-even-gated exception.
|
|
13
|
+
- **F5 — subagent offload.** For a simple one-off whose cheap-model switch is
|
|
14
|
+
cache-blocked (deep warm cache), the advisor suggests running it as a **Haiku
|
|
15
|
+
subagent** — full cheap-model savings without discarding the main session's cache.
|
|
16
|
+
Config `subagentAdvice` (default true).
|
|
17
|
+
- **F6 — cost HUD + cache budget.** `cache-statusline` CLI prints a one-line HUD
|
|
18
|
+
(`$ spent · % cached · $/turn`) for a Claude Code `statusLine` command and writes
|
|
19
|
+
`.agentic-security/cache-telemetry.json`; the `query_cache_telemetry` MCP tool gains
|
|
20
|
+
a `statusline` field. A soft `sessionBudgetUsd` biases the `costQualityTradeoff`
|
|
21
|
+
dial toward cheaper as real session spend (priced from the transcript) approaches it.
|
|
22
|
+
|
|
23
|
+
## 0.121.0 — prompt-cache economics (measured, cache-aware cost optimization)
|
|
24
|
+
|
|
25
|
+
Cache-economics core (PRD `docs/CACHE_ECONOMICS_PRD.md`, features F1–F3). Turns
|
|
26
|
+
Claude Code's own transcript usage into a dollarized, cache-aware view of token
|
|
27
|
+
cost. No network, advisory-only.
|
|
28
|
+
|
|
29
|
+
- **F1 — cache telemetry + report.** New `scanner/src/posture/cache-economics.js`
|
|
30
|
+
parses per-turn `usage` (cache read/write at 0.1× / 1.25×–2× input) and reports
|
|
31
|
+
cache-hit %, $ saved by caching, $ wasted on avoidable misses, $/turn, and a
|
|
32
|
+
per-model breakdown. Surfaced as the `cache-report` CLI subcommand (documented as
|
|
33
|
+
`/posture --cache`) and the read-only `query_cache_telemetry` MCP tool.
|
|
34
|
+
- **F2 — silent-invalidator detector ("cache bodyguard").** Retrospectively
|
|
35
|
+
attributes cache drops to model-switch / TTL-gap / prefix-change (shown in the
|
|
36
|
+
report), plus a live PreToolUse hook (`hooks/cache-invalidator-guard.js`) that warns
|
|
37
|
+
before an edit to a cache anchor (`CLAUDE.md`, `.claude/settings*.json`) with the
|
|
38
|
+
estimated re-warm cost. Throttled; `AGENTIC_SECURITY_QUIET` / `…_CACHE_GUARD=off`.
|
|
39
|
+
- **F3 — break-even + TTL-aware switching.** `hooks/model-cost-advisor.js` now reads
|
|
40
|
+
the *real* cached size from the transcript (`hooks/lib/transcript.js`), shows a
|
|
41
|
+
model switch's break-even ("worth it past ~N more turns"), suppresses switches that
|
|
42
|
+
won't pay off (preferring a cache-safe effort drop), and treats a cache gone cold
|
|
43
|
+
past the TTL as free to switch. New config: `ttlSeconds`, `breakEvenMaxTurns`.
|
|
44
|
+
|
|
45
|
+
Also lands the OpenRouter-derived advisor controls that F3 builds on: a
|
|
46
|
+
**`costQualityTradeoff` 0–10 dial** (replaces the one-sided `minSavingsUsd` gate;
|
|
47
|
+
0 = never downgrade, 10 = cheapest) and the initial per-prompt **cache-rewarm
|
|
48
|
+
penalty** that prefers a cache-preserving effort drop over a model switch.
|
|
49
|
+
|
|
50
|
+
F4–F6 (depth-first formalization, subagent-offload advice, cost HUD/statusline) are
|
|
51
|
+
specced in the PRD and ship next.
|
|
52
|
+
|
|
3
53
|
## 0.120.0 — model-cost optimizer (per-prompt model + depth advisor)
|
|
4
54
|
|
|
5
55
|
New opt-in Claude Code plugin feature; no functional change to the scanner.
|
package/bin/agentic-security.js
CHANGED
|
@@ -1631,6 +1631,36 @@ async function main() {
|
|
|
1631
1631
|
case 'rule-synth': process.exit(await cmdRuleSynth(args));
|
|
1632
1632
|
case 'digest': process.exit(await cmdDigest(args));
|
|
1633
1633
|
case 'setup': process.exit(await cmdSetup(args));
|
|
1634
|
+
case 'cache-report': {
|
|
1635
|
+
// Prompt-cache economics for the current session: parse the Claude Code
|
|
1636
|
+
// transcript usage and report cache-hit %, $ saved, and avoidable leaks.
|
|
1637
|
+
// Advisory/read-only — always exits 0.
|
|
1638
|
+
const { analyzeTranscript, formatCacheReport } = await import('../src/posture/cache-economics.js');
|
|
1639
|
+
const projectDir = path.resolve(args.flags.root || process.env.CLAUDE_PROJECT_DIR || process.cwd());
|
|
1640
|
+
const result = analyzeTranscript({ transcriptPath: args.flags.transcript, projectDir });
|
|
1641
|
+
if (args.flags.json) console.log(JSON.stringify(result, null, 2));
|
|
1642
|
+
else console.log(formatCacheReport(result));
|
|
1643
|
+
process.exit(0);
|
|
1644
|
+
}
|
|
1645
|
+
case 'cache-statusline': {
|
|
1646
|
+
// F6 — one-line cost HUD for a Claude Code statusLine command. Also writes
|
|
1647
|
+
// .agentic-security/cache-telemetry.json for other pollers. Always exits 0.
|
|
1648
|
+
const { analyzeTranscript, renderCacheStatusLine } = await import('../src/posture/cache-economics.js');
|
|
1649
|
+
const projectDir = path.resolve(args.flags.root || process.env.CLAUDE_PROJECT_DIR || process.cwd());
|
|
1650
|
+
const result = analyzeTranscript({ transcriptPath: args.flags.transcript, projectDir });
|
|
1651
|
+
if (result.ok) {
|
|
1652
|
+
try {
|
|
1653
|
+
const dir = path.join(projectDir, '.agentic-security');
|
|
1654
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1655
|
+
fs.writeFileSync(path.join(dir, 'cache-telemetry.json'),
|
|
1656
|
+
JSON.stringify({ updatedAt: new Date().toISOString(), metrics: result.metrics, leaks: result.leaks }, null, 2));
|
|
1657
|
+
} catch { /* best-effort */ }
|
|
1658
|
+
console.log(renderCacheStatusLine(result.metrics));
|
|
1659
|
+
} else {
|
|
1660
|
+
console.log('agentic-security: no session cost yet');
|
|
1661
|
+
}
|
|
1662
|
+
process.exit(0);
|
|
1663
|
+
}
|
|
1634
1664
|
case 'mcp': {
|
|
1635
1665
|
const { runStdio } = await import('../src/mcp/stdio.js');
|
|
1636
1666
|
const root = args.flags.root || process.env.AGENTIC_SECURITY_MCP_ROOT || process.cwd();
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
export const id = 752;
|
|
2
|
+
export const ids = [752];
|
|
3
|
+
export const modules = {
|
|
4
|
+
|
|
5
|
+
/***/ 8752:
|
|
6
|
+
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
7
|
+
|
|
8
|
+
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
|
|
9
|
+
/* harmony export */ analyzeTranscript: () => (/* binding */ analyzeTranscript),
|
|
10
|
+
/* harmony export */ formatCacheReport: () => (/* binding */ formatCacheReport),
|
|
11
|
+
/* harmony export */ renderCacheStatusLine: () => (/* binding */ renderCacheStatusLine)
|
|
12
|
+
/* harmony export */ });
|
|
13
|
+
/* unused harmony export _internal */
|
|
14
|
+
/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
|
|
15
|
+
/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8161);
|
|
16
|
+
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6760);
|
|
17
|
+
// Prompt-cache economics — turn Claude Code's own transcript usage into a
|
|
18
|
+
// dollarized report: how much prompt caching saved, how much was wasted on
|
|
19
|
+
// avoidable cache misses, and what invalidated the cache.
|
|
20
|
+
//
|
|
21
|
+
// Source of truth: the Claude Code transcript at
|
|
22
|
+
// ~/.claude/projects/<enc>/<session>.jsonl
|
|
23
|
+
// where <enc> is CLAUDE_PROJECT_DIR with `/` and `.` replaced by `-`. Each
|
|
24
|
+
// assistant turn carries `message.usage` with input/output/cache_read/
|
|
25
|
+
// cache_creation token counts (and a 5m/1h write split). We price those against
|
|
26
|
+
// per-model rates to compute real economics — no estimates, no network.
|
|
27
|
+
//
|
|
28
|
+
// Pure compute on parsed records; only `locateTranscript`/`parseTranscriptUsage`
|
|
29
|
+
// touch the filesystem. ESM (scanner tree). A trimmed CJS twin lives at
|
|
30
|
+
// hooks/lib/transcript.js for the CJS hooks; test/cache-economics.test.js asserts
|
|
31
|
+
// the two agree.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
// Cents-scale money formatter (fmtUsd in risk-dollars.js targets five-figure
|
|
37
|
+
// breach costs and won't round sub-dollar values).
|
|
38
|
+
function money(n) {
|
|
39
|
+
const v = Number(n) || 0;
|
|
40
|
+
return Math.abs(v) >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Per-1M-token rates (input / output). Mirror hooks/model-cost-advisor.js MODELS.
|
|
44
|
+
const MODEL_RATES = {
|
|
45
|
+
opus: { label: 'Opus 4.8', in: 5, out: 25 },
|
|
46
|
+
sonnet: { label: 'Sonnet 4.6', in: 3, out: 15 },
|
|
47
|
+
haiku: { label: 'Haiku 4.5', in: 1, out: 5 },
|
|
48
|
+
};
|
|
49
|
+
const CACHE_READ_MULT = 0.1; // cache read ≈ 0.1× input
|
|
50
|
+
const CACHE_WRITE_MULT = 1.25; // 5-minute cache write ≈ 1.25× input
|
|
51
|
+
const CACHE_WRITE_1H_MULT = 2.0; // 1-hour cache write ≈ 2× input
|
|
52
|
+
const TTL_MS = 5 * 60 * 1000;
|
|
53
|
+
|
|
54
|
+
// Map any model string to a rate family. Returns null for unpriceable models
|
|
55
|
+
// (e.g. "<synthetic>" sidechain/compaction turns) so they're skipped.
|
|
56
|
+
function rateFor(model) {
|
|
57
|
+
if (typeof model !== 'string') return null;
|
|
58
|
+
const s = model.toLowerCase();
|
|
59
|
+
if (s.includes('haiku')) return MODEL_RATES.haiku;
|
|
60
|
+
if (s.includes('sonnet')) return MODEL_RATES.sonnet;
|
|
61
|
+
if (s.includes('opus')) return MODEL_RATES.opus;
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ── Transcript discovery + parse ─────────────────────────────────────────────
|
|
66
|
+
|
|
67
|
+
function encodeProjectDir(dir) {
|
|
68
|
+
return String(dir).replace(/[/.]/g, '-');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Locate the session transcript. Prefer an explicit (hook-provided) path; else
|
|
72
|
+
// derive the project's transcript dir and take the most-recently-modified jsonl.
|
|
73
|
+
function locateTranscript({ transcriptPath, projectDir } = {}) {
|
|
74
|
+
try {
|
|
75
|
+
if (transcriptPath && node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(transcriptPath)) return transcriptPath;
|
|
76
|
+
} catch { /* fall through */ }
|
|
77
|
+
try {
|
|
78
|
+
const dir = node_path__WEBPACK_IMPORTED_MODULE_2__.join(node_os__WEBPACK_IMPORTED_MODULE_1__.homedir(), '.claude', 'projects', encodeProjectDir(projectDir || process.cwd()));
|
|
79
|
+
if (!node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(dir)) return null;
|
|
80
|
+
const files = node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir)
|
|
81
|
+
.filter(f => f.endsWith('.jsonl'))
|
|
82
|
+
.map(f => ({ f: node_path__WEBPACK_IMPORTED_MODULE_2__.join(dir, f), m: node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(node_path__WEBPACK_IMPORTED_MODULE_2__.join(dir, f)).mtimeMs }))
|
|
83
|
+
.sort((a, b) => b.m - a.m);
|
|
84
|
+
return files.length ? files[0].f : null;
|
|
85
|
+
} catch { return null; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Parse a transcript jsonl into per-assistant-turn usage records. Skips lines
|
|
89
|
+
// that aren't priceable assistant turns.
|
|
90
|
+
function parseTranscriptUsage(jsonlPath) {
|
|
91
|
+
let raw;
|
|
92
|
+
try { raw = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(jsonlPath, 'utf8'); } catch { return []; }
|
|
93
|
+
const records = [];
|
|
94
|
+
for (const line of raw.split('\n')) {
|
|
95
|
+
const t = line.trim();
|
|
96
|
+
if (!t) continue;
|
|
97
|
+
let o;
|
|
98
|
+
try { o = JSON.parse(t); } catch { continue; }
|
|
99
|
+
if (o.type !== 'assistant') continue;
|
|
100
|
+
const msg = o.message;
|
|
101
|
+
const u = msg && msg.usage;
|
|
102
|
+
if (!u || !msg.model || !rateFor(msg.model)) continue;
|
|
103
|
+
const cc = u.cache_creation || {};
|
|
104
|
+
records.push({
|
|
105
|
+
model: msg.model,
|
|
106
|
+
input: u.input_tokens || 0,
|
|
107
|
+
output: u.output_tokens || 0,
|
|
108
|
+
cacheRead: u.cache_read_input_tokens || 0,
|
|
109
|
+
cacheCreate: u.cache_creation_input_tokens || 0,
|
|
110
|
+
cacheCreate5m: cc.ephemeral_5m_input_tokens || 0,
|
|
111
|
+
cacheCreate1h: cc.ephemeral_1h_input_tokens || 0,
|
|
112
|
+
ts: o.timestamp ? Date.parse(o.timestamp) : null,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return records;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ── Pure economics ───────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
function writeCostUsd(r, inRate) {
|
|
121
|
+
const m5 = r.cacheCreate5m || 0, m1 = r.cacheCreate1h || 0;
|
|
122
|
+
if (m5 + m1 > 0) return (m5 * CACHE_WRITE_MULT + m1 * CACHE_WRITE_1H_MULT) * inRate;
|
|
123
|
+
return (r.cacheCreate || 0) * CACHE_WRITE_MULT * inRate; // breakdown absent
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Aggregate economics over parsed records.
|
|
127
|
+
function computeCacheEconomics(records) {
|
|
128
|
+
let turns = 0, inTok = 0, outTok = 0, cacheRead = 0, cacheCreate = 0;
|
|
129
|
+
let actualUsd = 0, uncachedUsd = 0, writePremiumUsd = 0;
|
|
130
|
+
const perModel = {};
|
|
131
|
+
|
|
132
|
+
for (const r of records) {
|
|
133
|
+
const rate = rateFor(r.model);
|
|
134
|
+
if (!rate) continue;
|
|
135
|
+
turns++;
|
|
136
|
+
const inRate = rate.in / 1e6, outRate = rate.out / 1e6;
|
|
137
|
+
|
|
138
|
+
const readCost = r.cacheRead * inRate * CACHE_READ_MULT;
|
|
139
|
+
const writeCost = writeCostUsd(r, inRate);
|
|
140
|
+
const inCost = r.input * inRate;
|
|
141
|
+
const outCost = r.output * outRate;
|
|
142
|
+
const turnActual = readCost + writeCost + inCost + outCost;
|
|
143
|
+
// What this turn would have cost with NO caching: every input-side token full price.
|
|
144
|
+
const turnUncached = (r.cacheRead + r.cacheCreate + r.input) * inRate + outCost;
|
|
145
|
+
|
|
146
|
+
actualUsd += turnActual;
|
|
147
|
+
uncachedUsd += turnUncached;
|
|
148
|
+
writePremiumUsd += writeCost - (r.cacheCreate * inRate); // the >1× premium paid to cache
|
|
149
|
+
|
|
150
|
+
inTok += r.input; outTok += r.output; cacheRead += r.cacheRead; cacheCreate += r.cacheCreate;
|
|
151
|
+
|
|
152
|
+
const key = rate.label;
|
|
153
|
+
const pm = perModel[key] || (perModel[key] = { turns: 0, actualUsd: 0, cacheRead: 0, inputSide: 0 });
|
|
154
|
+
pm.turns++; pm.actualUsd += turnActual; pm.cacheRead += r.cacheRead;
|
|
155
|
+
pm.inputSide += r.cacheRead + r.cacheCreate + r.input;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const inputSide = cacheRead + cacheCreate + inTok;
|
|
159
|
+
return {
|
|
160
|
+
turns,
|
|
161
|
+
tokens: { input: inTok, output: outTok, cacheRead, cacheCreate },
|
|
162
|
+
actualUsd,
|
|
163
|
+
uncachedUsd,
|
|
164
|
+
savedUsd: uncachedUsd - actualUsd, // net $ caching saved (can dip negative early)
|
|
165
|
+
writePremiumUsd, // $ invested establishing caches
|
|
166
|
+
cacheHitRatio: inputSide ? cacheRead / inputSide : 0,
|
|
167
|
+
costPerTurnUsd: turns ? actualUsd / turns : 0,
|
|
168
|
+
perModel,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Attribute cache drops: a turn that re-ingests a large prefix cold after a warm
|
|
173
|
+
// prior turn. Cause = model-switch | cache-expired | prefix-change.
|
|
174
|
+
function detectInvalidators(records) {
|
|
175
|
+
const leaks = [];
|
|
176
|
+
const MIN_WARM = 2000;
|
|
177
|
+
for (let i = 1; i < records.length; i++) {
|
|
178
|
+
const prev = records[i - 1], cur = records[i];
|
|
179
|
+
const prevWarm = prev.cacheRead + prev.input + prev.cacheCreate;
|
|
180
|
+
if (prevWarm < MIN_WARM) continue;
|
|
181
|
+
const curFresh = cur.input + cur.cacheCreate;
|
|
182
|
+
const coldish = cur.cacheRead < prevWarm * 0.25 && curFresh > prevWarm * 0.5;
|
|
183
|
+
if (!coldish) continue;
|
|
184
|
+
|
|
185
|
+
let cause;
|
|
186
|
+
if (cur.model !== prev.model) cause = 'model-switch';
|
|
187
|
+
else if (cur.ts && prev.ts && (cur.ts - prev.ts) > TTL_MS) cause = 'cache-expired';
|
|
188
|
+
else cause = 'prefix-change';
|
|
189
|
+
|
|
190
|
+
const rate = rateFor(cur.model);
|
|
191
|
+
const inRate = rate ? rate.in / 1e6 : 0;
|
|
192
|
+
// Extra paid vs. having kept the prefix as a cheap cache read.
|
|
193
|
+
const wastedUsd = prevWarm * inRate * (1 - CACHE_READ_MULT);
|
|
194
|
+
leaks.push({ turn: i, cause, wastedUsd, model: cur.model });
|
|
195
|
+
}
|
|
196
|
+
return leaks;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Convenience: locate → parse → compute → detect. Returns { ok:false } when no
|
|
200
|
+
// transcript is available.
|
|
201
|
+
function analyzeTranscript(opts = {}) {
|
|
202
|
+
const transcript = locateTranscript(opts);
|
|
203
|
+
if (!transcript) return { ok: false, reason: 'no-transcript' };
|
|
204
|
+
const records = parseTranscriptUsage(transcript);
|
|
205
|
+
if (!records.length) return { ok: false, reason: 'no-priceable-turns', transcript };
|
|
206
|
+
return {
|
|
207
|
+
ok: true,
|
|
208
|
+
transcript,
|
|
209
|
+
metrics: computeCacheEconomics(records),
|
|
210
|
+
leaks: detectInvalidators(records),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── Report formatting ────────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
const CAUSE_LABEL = {
|
|
217
|
+
'model-switch': 'model switch (cache is model-scoped)',
|
|
218
|
+
'cache-expired': 'cache expired (gap > 5-min TTL)',
|
|
219
|
+
'prefix-change': 'prefix changed (system prompt / tools / context edit)',
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
// F6 — one-line HUD for a Claude Code statusLine command (mirrors
|
|
223
|
+
// watch-mode.js renderStatusLine). Takes the metrics from computeCacheEconomics.
|
|
224
|
+
function renderCacheStatusLine(metrics) {
|
|
225
|
+
if (!metrics || !metrics.turns) return 'agentic-security: no session cost yet';
|
|
226
|
+
const hit = Math.round(metrics.cacheHitRatio * 100);
|
|
227
|
+
return `agentic-security: ${money(metrics.actualUsd)} · ${hit}% cached · ${money(metrics.costPerTurnUsd)}/turn`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function formatCacheReport(result) {
|
|
231
|
+
if (!result.ok) {
|
|
232
|
+
return result.reason === 'no-transcript'
|
|
233
|
+
? 'agentic-security: no Claude Code transcript found for this project yet.'
|
|
234
|
+
: 'agentic-security: transcript has no priceable model turns yet.';
|
|
235
|
+
}
|
|
236
|
+
const m = result.metrics;
|
|
237
|
+
const lines = [];
|
|
238
|
+
lines.push('');
|
|
239
|
+
lines.push(' Prompt-cache economics — this session');
|
|
240
|
+
lines.push(` ${result.turns ?? m.turns} model turns\n`);
|
|
241
|
+
lines.push(` cache hit ratio ${(m.cacheHitRatio * 100).toFixed(1)}% (input-side tokens served from cache)`);
|
|
242
|
+
lines.push(` spent ${money(m.actualUsd)} (~${money(m.costPerTurnUsd)}/turn)`);
|
|
243
|
+
lines.push(` ▶ saved by caching ${money(m.savedUsd)} vs. ${money(m.uncachedUsd)} with no cache`);
|
|
244
|
+
lines.push(` invested in caches ${money(m.writePremiumUsd)} (write premium over base input)`);
|
|
245
|
+
lines.push('');
|
|
246
|
+
lines.push(' tokens: '
|
|
247
|
+
+ `${m.tokens.cacheRead.toLocaleString()} cached-read · `
|
|
248
|
+
+ `${m.tokens.cacheCreate.toLocaleString()} cache-write · `
|
|
249
|
+
+ `${m.tokens.input.toLocaleString()} fresh-in · `
|
|
250
|
+
+ `${m.tokens.output.toLocaleString()} out`);
|
|
251
|
+
|
|
252
|
+
const models = Object.keys(m.perModel);
|
|
253
|
+
if (models.length > 1) {
|
|
254
|
+
lines.push('\n by model:');
|
|
255
|
+
for (const k of models.sort()) {
|
|
256
|
+
const pm = m.perModel[k];
|
|
257
|
+
const hr = pm.inputSide ? (pm.cacheRead / pm.inputSide * 100).toFixed(0) : '0';
|
|
258
|
+
lines.push(` ${k.padEnd(12)} ${pm.turns} turns · ${money(pm.actualUsd)} · ${hr}% cached`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (result.leaks && result.leaks.length) {
|
|
263
|
+
const wasted = result.leaks.reduce((s, l) => s + l.wastedUsd, 0);
|
|
264
|
+
lines.push(`\n ⚠ cache leaks (${result.leaks.length}, ~${money(wasted)} wasted re-ingesting context):`);
|
|
265
|
+
const byCause = {};
|
|
266
|
+
for (const l of result.leaks) {
|
|
267
|
+
(byCause[l.cause] || (byCause[l.cause] = { n: 0, usd: 0 })).n++;
|
|
268
|
+
byCause[l.cause].usd += l.wastedUsd;
|
|
269
|
+
}
|
|
270
|
+
for (const c of Object.keys(byCause).sort()) {
|
|
271
|
+
lines.push(` · ${byCause[c].n}× ${CAUSE_LABEL[c] || c} — ~${money(byCause[c].usd)}`);
|
|
272
|
+
}
|
|
273
|
+
lines.push(' Keep one model + a stable system prompt within a working window to avoid these.');
|
|
274
|
+
} else {
|
|
275
|
+
lines.push('\n ✓ no cache leaks detected — your context stayed warm.');
|
|
276
|
+
}
|
|
277
|
+
lines.push('');
|
|
278
|
+
return lines.join('\n');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Test surface (underscore export is exempt from the dead-module gate).
|
|
282
|
+
const _internal = {
|
|
283
|
+
MODEL_RATES, CACHE_READ_MULT, CACHE_WRITE_MULT, CACHE_WRITE_1H_MULT,
|
|
284
|
+
rateFor, locateTranscript, parseTranscriptUsage, computeCacheEconomics, detectInvalidators,
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
/***/ })
|
|
289
|
+
|
|
290
|
+
};
|