@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/dist/985.index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export const id = 985;
2
- export const ids = [985];
2
+ export const ids = [985,752];
3
3
  export const modules = {
4
4
 
5
5
  /***/ 3985:
@@ -25,6 +25,8 @@ var promises_ = __webpack_require__(1455);
25
25
  var fix_history = __webpack_require__(4407);
26
26
  // EXTERNAL MODULE: ./src/posture/integrity.js
27
27
  var integrity = __webpack_require__(1130);
28
+ // EXTERNAL MODULE: ./src/posture/cache-economics.js
29
+ var cache_economics = __webpack_require__(8752);
28
30
  ;// CONCATENATED MODULE: ./src/mcp/redact.js
29
31
  // Secret redactor for MCP tool outputs and audit log argument summaries.
30
32
  //
@@ -395,6 +397,7 @@ const cve_lookup_internals = { CACHE_DIR, CVE_RE, _stalenessTier };
395
397
 
396
398
 
397
399
 
400
+
398
401
  // Lazy-loaded: these transitively pull in npm packages (fast-glob,
399
402
  // @babel/core) that aren't available in the plugin-cache install path
400
403
  // (no node_modules). Deferring keeps the MCP server bootable everywhere;
@@ -1396,6 +1399,32 @@ const lookup_cve = {
1396
1399
  },
1397
1400
  };
1398
1401
 
1402
+ const query_cache_telemetry = {
1403
+ name: 'query_cache_telemetry',
1404
+ description: 'Read prompt-cache economics for the current session from the Claude Code transcript: cache-hit %, $ saved by caching, $ wasted on avoidable cache misses (model switches / TTL gaps / prefix changes), and a per-model breakdown. Read-only, no network. Use to reason about token-cost efficiency and whether a model switch is worth the cache rewarm.',
1405
+ inputSchema: {
1406
+ type: 'object',
1407
+ additionalProperties: false,
1408
+ properties: {
1409
+ // Optional explicit transcript path; otherwise derived from the session root.
1410
+ transcript_path: { type: 'string', minLength: 1, maxLength: 4096 },
1411
+ },
1412
+ required: [],
1413
+ },
1414
+ async handler({ transcript_path } = {}, ctx) {
1415
+ const result = (0,cache_economics.analyzeTranscript)({ transcriptPath: transcript_path, projectDir: ctx?.sessionRoot || process.cwd() });
1416
+ if (!result.ok) return { _meta: META, ok: false, reason: result.reason };
1417
+ return {
1418
+ _meta: META,
1419
+ ok: true,
1420
+ metrics: result.metrics,
1421
+ leaks: result.leaks,
1422
+ report: (0,cache_economics.formatCacheReport)(result),
1423
+ statusline: (0,cache_economics.renderCacheStatusLine)(result.metrics),
1424
+ };
1425
+ },
1426
+ };
1427
+
1399
1428
  // ─── synthesize_sca_upgrade ───────────────────────────────────────────────
1400
1429
  // Phase 3 / Item 5 of the SCA improvement plan. Read-only counterpart to
1401
1430
  // apply_sca_upgrade — produces a structured upgrade plan via the
@@ -1470,7 +1499,7 @@ const apply_sca_upgrade = {
1470
1499
  },
1471
1500
  };
1472
1501
 
1473
- const ALL_TOOLS = [scan_diff, query_taint, explain_finding, apply_fix, verify_fix, synthesize_fix, find_rule_module, append_scratchpad, read_scratchpad, append_agents_memory, read_agents_memory, lookup_cve, synthesize_sca_upgrade, apply_sca_upgrade, query_triage_memory, query_findings_memory];
1502
+ const ALL_TOOLS = [scan_diff, query_taint, explain_finding, apply_fix, verify_fix, synthesize_fix, find_rule_module, append_scratchpad, read_scratchpad, append_agents_memory, read_agents_memory, lookup_cve, synthesize_sca_upgrade, apply_sca_upgrade, query_triage_memory, query_findings_memory, query_cache_telemetry];
1474
1503
 
1475
1504
  ;// CONCATENATED MODULE: ./src/mcp/validate.js
1476
1505
  // Minimal JSON Schema validator — just the subset our tool schemas use.
@@ -1912,6 +1941,291 @@ function runStdio({
1912
1941
  }
1913
1942
 
1914
1943
 
1944
+ /***/ }),
1945
+
1946
+ /***/ 8752:
1947
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1948
+
1949
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1950
+ /* harmony export */ analyzeTranscript: () => (/* binding */ analyzeTranscript),
1951
+ /* harmony export */ formatCacheReport: () => (/* binding */ formatCacheReport),
1952
+ /* harmony export */ renderCacheStatusLine: () => (/* binding */ renderCacheStatusLine)
1953
+ /* harmony export */ });
1954
+ /* unused harmony export _internal */
1955
+ /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
1956
+ /* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8161);
1957
+ /* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6760);
1958
+ // Prompt-cache economics — turn Claude Code's own transcript usage into a
1959
+ // dollarized report: how much prompt caching saved, how much was wasted on
1960
+ // avoidable cache misses, and what invalidated the cache.
1961
+ //
1962
+ // Source of truth: the Claude Code transcript at
1963
+ // ~/.claude/projects/<enc>/<session>.jsonl
1964
+ // where <enc> is CLAUDE_PROJECT_DIR with `/` and `.` replaced by `-`. Each
1965
+ // assistant turn carries `message.usage` with input/output/cache_read/
1966
+ // cache_creation token counts (and a 5m/1h write split). We price those against
1967
+ // per-model rates to compute real economics — no estimates, no network.
1968
+ //
1969
+ // Pure compute on parsed records; only `locateTranscript`/`parseTranscriptUsage`
1970
+ // touch the filesystem. ESM (scanner tree). A trimmed CJS twin lives at
1971
+ // hooks/lib/transcript.js for the CJS hooks; test/cache-economics.test.js asserts
1972
+ // the two agree.
1973
+
1974
+
1975
+
1976
+
1977
+ // Cents-scale money formatter (fmtUsd in risk-dollars.js targets five-figure
1978
+ // breach costs and won't round sub-dollar values).
1979
+ function money(n) {
1980
+ const v = Number(n) || 0;
1981
+ return Math.abs(v) >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;
1982
+ }
1983
+
1984
+ // Per-1M-token rates (input / output). Mirror hooks/model-cost-advisor.js MODELS.
1985
+ const MODEL_RATES = {
1986
+ opus: { label: 'Opus 4.8', in: 5, out: 25 },
1987
+ sonnet: { label: 'Sonnet 4.6', in: 3, out: 15 },
1988
+ haiku: { label: 'Haiku 4.5', in: 1, out: 5 },
1989
+ };
1990
+ const CACHE_READ_MULT = 0.1; // cache read ≈ 0.1× input
1991
+ const CACHE_WRITE_MULT = 1.25; // 5-minute cache write ≈ 1.25× input
1992
+ const CACHE_WRITE_1H_MULT = 2.0; // 1-hour cache write ≈ 2× input
1993
+ const TTL_MS = 5 * 60 * 1000;
1994
+
1995
+ // Map any model string to a rate family. Returns null for unpriceable models
1996
+ // (e.g. "<synthetic>" sidechain/compaction turns) so they're skipped.
1997
+ function rateFor(model) {
1998
+ if (typeof model !== 'string') return null;
1999
+ const s = model.toLowerCase();
2000
+ if (s.includes('haiku')) return MODEL_RATES.haiku;
2001
+ if (s.includes('sonnet')) return MODEL_RATES.sonnet;
2002
+ if (s.includes('opus')) return MODEL_RATES.opus;
2003
+ return null;
2004
+ }
2005
+
2006
+ // ── Transcript discovery + parse ─────────────────────────────────────────────
2007
+
2008
+ function encodeProjectDir(dir) {
2009
+ return String(dir).replace(/[/.]/g, '-');
2010
+ }
2011
+
2012
+ // Locate the session transcript. Prefer an explicit (hook-provided) path; else
2013
+ // derive the project's transcript dir and take the most-recently-modified jsonl.
2014
+ function locateTranscript({ transcriptPath, projectDir } = {}) {
2015
+ try {
2016
+ if (transcriptPath && node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(transcriptPath)) return transcriptPath;
2017
+ } catch { /* fall through */ }
2018
+ try {
2019
+ const dir = node_path__WEBPACK_IMPORTED_MODULE_2__.join(node_os__WEBPACK_IMPORTED_MODULE_1__.homedir(), '.claude', 'projects', encodeProjectDir(projectDir || process.cwd()));
2020
+ if (!node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(dir)) return null;
2021
+ const files = node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir)
2022
+ .filter(f => f.endsWith('.jsonl'))
2023
+ .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 }))
2024
+ .sort((a, b) => b.m - a.m);
2025
+ return files.length ? files[0].f : null;
2026
+ } catch { return null; }
2027
+ }
2028
+
2029
+ // Parse a transcript jsonl into per-assistant-turn usage records. Skips lines
2030
+ // that aren't priceable assistant turns.
2031
+ function parseTranscriptUsage(jsonlPath) {
2032
+ let raw;
2033
+ try { raw = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(jsonlPath, 'utf8'); } catch { return []; }
2034
+ const records = [];
2035
+ for (const line of raw.split('\n')) {
2036
+ const t = line.trim();
2037
+ if (!t) continue;
2038
+ let o;
2039
+ try { o = JSON.parse(t); } catch { continue; }
2040
+ if (o.type !== 'assistant') continue;
2041
+ const msg = o.message;
2042
+ const u = msg && msg.usage;
2043
+ if (!u || !msg.model || !rateFor(msg.model)) continue;
2044
+ const cc = u.cache_creation || {};
2045
+ records.push({
2046
+ model: msg.model,
2047
+ input: u.input_tokens || 0,
2048
+ output: u.output_tokens || 0,
2049
+ cacheRead: u.cache_read_input_tokens || 0,
2050
+ cacheCreate: u.cache_creation_input_tokens || 0,
2051
+ cacheCreate5m: cc.ephemeral_5m_input_tokens || 0,
2052
+ cacheCreate1h: cc.ephemeral_1h_input_tokens || 0,
2053
+ ts: o.timestamp ? Date.parse(o.timestamp) : null,
2054
+ });
2055
+ }
2056
+ return records;
2057
+ }
2058
+
2059
+ // ── Pure economics ───────────────────────────────────────────────────────────
2060
+
2061
+ function writeCostUsd(r, inRate) {
2062
+ const m5 = r.cacheCreate5m || 0, m1 = r.cacheCreate1h || 0;
2063
+ if (m5 + m1 > 0) return (m5 * CACHE_WRITE_MULT + m1 * CACHE_WRITE_1H_MULT) * inRate;
2064
+ return (r.cacheCreate || 0) * CACHE_WRITE_MULT * inRate; // breakdown absent
2065
+ }
2066
+
2067
+ // Aggregate economics over parsed records.
2068
+ function computeCacheEconomics(records) {
2069
+ let turns = 0, inTok = 0, outTok = 0, cacheRead = 0, cacheCreate = 0;
2070
+ let actualUsd = 0, uncachedUsd = 0, writePremiumUsd = 0;
2071
+ const perModel = {};
2072
+
2073
+ for (const r of records) {
2074
+ const rate = rateFor(r.model);
2075
+ if (!rate) continue;
2076
+ turns++;
2077
+ const inRate = rate.in / 1e6, outRate = rate.out / 1e6;
2078
+
2079
+ const readCost = r.cacheRead * inRate * CACHE_READ_MULT;
2080
+ const writeCost = writeCostUsd(r, inRate);
2081
+ const inCost = r.input * inRate;
2082
+ const outCost = r.output * outRate;
2083
+ const turnActual = readCost + writeCost + inCost + outCost;
2084
+ // What this turn would have cost with NO caching: every input-side token full price.
2085
+ const turnUncached = (r.cacheRead + r.cacheCreate + r.input) * inRate + outCost;
2086
+
2087
+ actualUsd += turnActual;
2088
+ uncachedUsd += turnUncached;
2089
+ writePremiumUsd += writeCost - (r.cacheCreate * inRate); // the >1× premium paid to cache
2090
+
2091
+ inTok += r.input; outTok += r.output; cacheRead += r.cacheRead; cacheCreate += r.cacheCreate;
2092
+
2093
+ const key = rate.label;
2094
+ const pm = perModel[key] || (perModel[key] = { turns: 0, actualUsd: 0, cacheRead: 0, inputSide: 0 });
2095
+ pm.turns++; pm.actualUsd += turnActual; pm.cacheRead += r.cacheRead;
2096
+ pm.inputSide += r.cacheRead + r.cacheCreate + r.input;
2097
+ }
2098
+
2099
+ const inputSide = cacheRead + cacheCreate + inTok;
2100
+ return {
2101
+ turns,
2102
+ tokens: { input: inTok, output: outTok, cacheRead, cacheCreate },
2103
+ actualUsd,
2104
+ uncachedUsd,
2105
+ savedUsd: uncachedUsd - actualUsd, // net $ caching saved (can dip negative early)
2106
+ writePremiumUsd, // $ invested establishing caches
2107
+ cacheHitRatio: inputSide ? cacheRead / inputSide : 0,
2108
+ costPerTurnUsd: turns ? actualUsd / turns : 0,
2109
+ perModel,
2110
+ };
2111
+ }
2112
+
2113
+ // Attribute cache drops: a turn that re-ingests a large prefix cold after a warm
2114
+ // prior turn. Cause = model-switch | cache-expired | prefix-change.
2115
+ function detectInvalidators(records) {
2116
+ const leaks = [];
2117
+ const MIN_WARM = 2000;
2118
+ for (let i = 1; i < records.length; i++) {
2119
+ const prev = records[i - 1], cur = records[i];
2120
+ const prevWarm = prev.cacheRead + prev.input + prev.cacheCreate;
2121
+ if (prevWarm < MIN_WARM) continue;
2122
+ const curFresh = cur.input + cur.cacheCreate;
2123
+ const coldish = cur.cacheRead < prevWarm * 0.25 && curFresh > prevWarm * 0.5;
2124
+ if (!coldish) continue;
2125
+
2126
+ let cause;
2127
+ if (cur.model !== prev.model) cause = 'model-switch';
2128
+ else if (cur.ts && prev.ts && (cur.ts - prev.ts) > TTL_MS) cause = 'cache-expired';
2129
+ else cause = 'prefix-change';
2130
+
2131
+ const rate = rateFor(cur.model);
2132
+ const inRate = rate ? rate.in / 1e6 : 0;
2133
+ // Extra paid vs. having kept the prefix as a cheap cache read.
2134
+ const wastedUsd = prevWarm * inRate * (1 - CACHE_READ_MULT);
2135
+ leaks.push({ turn: i, cause, wastedUsd, model: cur.model });
2136
+ }
2137
+ return leaks;
2138
+ }
2139
+
2140
+ // Convenience: locate → parse → compute → detect. Returns { ok:false } when no
2141
+ // transcript is available.
2142
+ function analyzeTranscript(opts = {}) {
2143
+ const transcript = locateTranscript(opts);
2144
+ if (!transcript) return { ok: false, reason: 'no-transcript' };
2145
+ const records = parseTranscriptUsage(transcript);
2146
+ if (!records.length) return { ok: false, reason: 'no-priceable-turns', transcript };
2147
+ return {
2148
+ ok: true,
2149
+ transcript,
2150
+ metrics: computeCacheEconomics(records),
2151
+ leaks: detectInvalidators(records),
2152
+ };
2153
+ }
2154
+
2155
+ // ── Report formatting ────────────────────────────────────────────────────────
2156
+
2157
+ const CAUSE_LABEL = {
2158
+ 'model-switch': 'model switch (cache is model-scoped)',
2159
+ 'cache-expired': 'cache expired (gap > 5-min TTL)',
2160
+ 'prefix-change': 'prefix changed (system prompt / tools / context edit)',
2161
+ };
2162
+
2163
+ // F6 — one-line HUD for a Claude Code statusLine command (mirrors
2164
+ // watch-mode.js renderStatusLine). Takes the metrics from computeCacheEconomics.
2165
+ function renderCacheStatusLine(metrics) {
2166
+ if (!metrics || !metrics.turns) return 'agentic-security: no session cost yet';
2167
+ const hit = Math.round(metrics.cacheHitRatio * 100);
2168
+ return `agentic-security: ${money(metrics.actualUsd)} · ${hit}% cached · ${money(metrics.costPerTurnUsd)}/turn`;
2169
+ }
2170
+
2171
+ function formatCacheReport(result) {
2172
+ if (!result.ok) {
2173
+ return result.reason === 'no-transcript'
2174
+ ? 'agentic-security: no Claude Code transcript found for this project yet.'
2175
+ : 'agentic-security: transcript has no priceable model turns yet.';
2176
+ }
2177
+ const m = result.metrics;
2178
+ const lines = [];
2179
+ lines.push('');
2180
+ lines.push(' Prompt-cache economics — this session');
2181
+ lines.push(` ${result.turns ?? m.turns} model turns\n`);
2182
+ lines.push(` cache hit ratio ${(m.cacheHitRatio * 100).toFixed(1)}% (input-side tokens served from cache)`);
2183
+ lines.push(` spent ${money(m.actualUsd)} (~${money(m.costPerTurnUsd)}/turn)`);
2184
+ lines.push(` ▶ saved by caching ${money(m.savedUsd)} vs. ${money(m.uncachedUsd)} with no cache`);
2185
+ lines.push(` invested in caches ${money(m.writePremiumUsd)} (write premium over base input)`);
2186
+ lines.push('');
2187
+ lines.push(' tokens: '
2188
+ + `${m.tokens.cacheRead.toLocaleString()} cached-read · `
2189
+ + `${m.tokens.cacheCreate.toLocaleString()} cache-write · `
2190
+ + `${m.tokens.input.toLocaleString()} fresh-in · `
2191
+ + `${m.tokens.output.toLocaleString()} out`);
2192
+
2193
+ const models = Object.keys(m.perModel);
2194
+ if (models.length > 1) {
2195
+ lines.push('\n by model:');
2196
+ for (const k of models.sort()) {
2197
+ const pm = m.perModel[k];
2198
+ const hr = pm.inputSide ? (pm.cacheRead / pm.inputSide * 100).toFixed(0) : '0';
2199
+ lines.push(` ${k.padEnd(12)} ${pm.turns} turns · ${money(pm.actualUsd)} · ${hr}% cached`);
2200
+ }
2201
+ }
2202
+
2203
+ if (result.leaks && result.leaks.length) {
2204
+ const wasted = result.leaks.reduce((s, l) => s + l.wastedUsd, 0);
2205
+ lines.push(`\n ⚠ cache leaks (${result.leaks.length}, ~${money(wasted)} wasted re-ingesting context):`);
2206
+ const byCause = {};
2207
+ for (const l of result.leaks) {
2208
+ (byCause[l.cause] || (byCause[l.cause] = { n: 0, usd: 0 })).n++;
2209
+ byCause[l.cause].usd += l.wastedUsd;
2210
+ }
2211
+ for (const c of Object.keys(byCause).sort()) {
2212
+ lines.push(` · ${byCause[c].n}× ${CAUSE_LABEL[c] || c} — ~${money(byCause[c].usd)}`);
2213
+ }
2214
+ lines.push(' Keep one model + a stable system prompt within a working window to avoid these.');
2215
+ } else {
2216
+ lines.push('\n ✓ no cache leaks detected — your context stayed warm.');
2217
+ }
2218
+ lines.push('');
2219
+ return lines.join('\n');
2220
+ }
2221
+
2222
+ // Test surface (underscore export is exempt from the dead-module gate).
2223
+ const _internal = {
2224
+ MODEL_RATES, CACHE_READ_MULT, CACHE_WRITE_MULT, CACHE_WRITE_1H_MULT,
2225
+ rateFor, locateTranscript, parseTranscriptUsage, computeCacheEconomics, detectInvalidators,
2226
+ };
2227
+
2228
+
1915
2229
  /***/ })
1916
2230
 
1917
2231
  };