tierview 0.0.0-stage → 0.1.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/bin.js ADDED
@@ -0,0 +1,2486 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
5
+ import { Command } from "commander";
6
+
7
+ // src/config.ts
8
+ import { existsSync, readFileSync } from "fs";
9
+ import { join as join2 } from "path";
10
+ import { parse } from "yaml";
11
+ import { z } from "zod";
12
+
13
+ // src/root.ts
14
+ import { fileURLToPath } from "url";
15
+ import { dirname, join } from "path";
16
+ var here = dirname(fileURLToPath(import.meta.url));
17
+ function configPath(name) {
18
+ return join(here, "..", "config", name);
19
+ }
20
+
21
+ // src/config.ts
22
+ var ConfigError = class extends Error {
23
+ };
24
+ var Effort = z.enum(["low", "medium", "high", "xhigh", "max"]);
25
+ var TierModel = z.object({ model: z.string().min(1), effort: Effort });
26
+ var TierNum = z.union([z.literal(1), z.literal(2), z.literal(3)]);
27
+ var Category = z.object({
28
+ weight: z.number(),
29
+ path: z.array(z.string()).default([]),
30
+ content: z.array(z.string()).default([]),
31
+ content_added: z.array(z.string()).default([]),
32
+ content_removed: z.array(z.string()).default([]),
33
+ logic: z.array(z.string()).default([])
34
+ }).strict();
35
+ var Rule = z.object({
36
+ paths: z.array(z.string()).min(1),
37
+ min_tier: TierNum.optional(),
38
+ max_tier: TierNum.optional(),
39
+ add: z.number().optional()
40
+ }).strict().refine((r) => !r.min_tier || !r.max_tier || r.min_tier <= r.max_tier, "min_tier must be <= max_tier");
41
+ var Structure = z.object({
42
+ size: z.array(z.tuple([z.union([z.number(), z.literal(Infinity)]), z.number()])).min(1),
43
+ scatter: z.object({ max_files: z.number(), max_top_dirs: z.number(), points: z.number() }),
44
+ many_hunks_in_file: z.object({ more_than: z.number(), points: z.number() }),
45
+ churn: z.object({ enabled: z.boolean(), days: z.number(), min_commits: z.number(), points: z.number() }),
46
+ hotspot: z.object({
47
+ enabled: z.boolean(),
48
+ days: z.number(),
49
+ min_fix_commits: z.number(),
50
+ points: z.number(),
51
+ pattern: z.string()
52
+ }),
53
+ deletion_only: z.object({ points: z.number() }),
54
+ diff_weakens_tests: z.object({ points: z.number() }),
55
+ no_tests_changed: z.object({ min_source_lines: z.number(), points: z.number() })
56
+ });
57
+ var ConfigSchema = z.object({
58
+ version: z.literal(1),
59
+ models: z.object({ tier1: TierModel, tier2: TierModel, tier3: TierModel }),
60
+ thresholds: z.object({ tier2: z.number(), tier3: z.number() }),
61
+ escalation: z.object({
62
+ tier1_min_confidence: z.number().min(0).max(1),
63
+ tier2_min_confidence: z.number().min(0).max(1),
64
+ tier1_verify_severity: z.string(),
65
+ tier2_verify_severity: z.string(),
66
+ max_rate: z.number().min(0).max(1)
67
+ }),
68
+ budget: z.object({ max_cost_usd: z.number().positive().nullable() }),
69
+ receipt: z.object({ baseline: TierModel }),
70
+ /** File context for Tier 1: none (diff only) or the same as Tier 3 (bench-config-v2). */
71
+ tier1_context: z.enum(["none", "tier3"]).default("tier3"),
72
+ /** Opt-in for Fable on the claude-code backend (PLAN §5a). camelCase as the user-facing key; --allow-fable sets it too. */
73
+ allowFable: z.boolean().default(false),
74
+ backend: z.object({
75
+ default: z.enum(["claude-code", "api"]),
76
+ claude_code: z.object({
77
+ binary: z.string().nullable(),
78
+ max_hunks_per_call: z.number().int().positive(),
79
+ max_tokens_per_call: z.number().int().positive(),
80
+ timeout_s: z.number().positive()
81
+ }),
82
+ api: z.object({ max_tokens: z.number().int().positive(), concurrency: z.number().int().positive() })
83
+ }),
84
+ ignore: z.array(z.string()),
85
+ rules: z.array(Rule),
86
+ file_kinds: z.object({
87
+ generated: z.array(z.string()),
88
+ docs: z.array(z.string()),
89
+ test: z.array(z.string()),
90
+ config: z.array(z.string())
91
+ }),
92
+ categories: z.record(z.string(), Category),
93
+ structure: Structure,
94
+ reductions: z.object({ test_file_without_test_signal: z.number(), docs_or_trivial_cap: z.number() })
95
+ });
96
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
97
+ function deepMerge(base, over) {
98
+ if (!isObj(base) || !isObj(over)) return over;
99
+ const out = { ...base };
100
+ for (const [k, v] of Object.entries(over)) out[k] = k in base ? deepMerge(base[k], v) : v;
101
+ return out;
102
+ }
103
+ function applySignals(cfg, signals) {
104
+ if (signals === void 0 || signals === null) return;
105
+ if (!isObj(signals)) throw new ConfigError("`signals` must be a mapping");
106
+ const cats = cfg.categories;
107
+ const structure = cfg.structure;
108
+ for (const [name, value] of Object.entries(signals)) {
109
+ if (name in cats) cats[name] = deepMerge(cats[name], value);
110
+ else if (name in structure) structure[name] = deepMerge(structure[name], value);
111
+ else {
112
+ const known = [...Object.keys(cats), ...Object.keys(structure)].join(", ");
113
+ throw new ConfigError(`unknown signal "${name}" in .tierview.yml (known: ${known})`);
114
+ }
115
+ }
116
+ }
117
+ function checkRegexes(cfg) {
118
+ const check = (where, src) => {
119
+ try {
120
+ new RegExp(src, "i");
121
+ } catch (e) {
122
+ throw new ConfigError(`invalid regex in ${where}: ${src} (${e.message})`);
123
+ }
124
+ };
125
+ for (const [name, c] of Object.entries(cfg.categories)) {
126
+ for (const key4 of ["path", "content", "content_added", "content_removed"]) {
127
+ for (const p of c[key4]) check(`categories.${name}.${key4}`, p);
128
+ }
129
+ }
130
+ check("structure.hotspot.pattern", cfg.structure.hotspot.pattern);
131
+ }
132
+ function loadConfig(opts = {}) {
133
+ const defaults = parse(readFileSync(configPath("default-rules.yml"), "utf8"));
134
+ const file = opts.path ?? join2(opts.cwd ?? process.cwd(), ".tierview.yml");
135
+ let merged = defaults;
136
+ if (existsSync(file)) {
137
+ let user;
138
+ try {
139
+ user = parse(readFileSync(file, "utf8"));
140
+ } catch (e) {
141
+ throw new ConfigError(`cannot parse ${file}: ${e.message}`);
142
+ }
143
+ if (user !== null && user !== void 0) {
144
+ if (!isObj(user)) throw new ConfigError(`${file} must be a mapping`);
145
+ const { signals, ...rest } = user;
146
+ merged = deepMerge(defaults, rest);
147
+ applySignals(merged, signals);
148
+ }
149
+ } else if (opts.path) {
150
+ throw new ConfigError(`config file not found: ${file}`);
151
+ }
152
+ const parsed = ConfigSchema.safeParse(merged);
153
+ if (!parsed.success) {
154
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
155
+ throw new ConfigError(`invalid config: ${issues}`);
156
+ }
157
+ const cfg = parsed.data;
158
+ if (cfg.thresholds.tier2 >= cfg.thresholds.tier3) throw new ConfigError("thresholds.tier2 must be below thresholds.tier3");
159
+ checkRegexes(cfg);
160
+ return cfg;
161
+ }
162
+
163
+ // src/estimate.ts
164
+ import { readFileSync as readFileSync3 } from "fs";
165
+ import { z as z3 } from "zod";
166
+
167
+ // src/prices.ts
168
+ import { readFileSync as readFileSync2 } from "fs";
169
+ import { z as z2 } from "zod";
170
+ var ModelPrice = z2.object({
171
+ input: z2.number(),
172
+ cache_write_5m: z2.number(),
173
+ cache_write_1h: z2.number().optional(),
174
+ cache_read: z2.number(),
175
+ output: z2.number(),
176
+ batch_input: z2.number().optional(),
177
+ batch_output: z2.number().optional()
178
+ });
179
+ var PricesFile = z2.object({
180
+ as_of: z2.string(),
181
+ source: z2.string().optional(),
182
+ models: z2.record(z2.string(), ModelPrice)
183
+ });
184
+ var PricesError = class extends Error {
185
+ };
186
+ var cached;
187
+ function loadPrices(path = configPath("prices.json")) {
188
+ if (path === configPath("prices.json") && cached) return cached;
189
+ const parsed = PricesFile.safeParse(JSON.parse(readFileSync2(path, "utf8")));
190
+ if (!parsed.success) throw new PricesError(`invalid ${path}: ${parsed.error.message}`);
191
+ if (path === configPath("prices.json")) cached = parsed.data;
192
+ return parsed.data;
193
+ }
194
+ function priceFor(model, prices = loadPrices()) {
195
+ const p = prices.models[model];
196
+ if (!p) {
197
+ throw new PricesError(
198
+ `no price for model "${model}" in config/prices.json (known: ${Object.keys(prices.models).join(", ")})`
199
+ );
200
+ }
201
+ return p;
202
+ }
203
+ function costOf(usage, model, prices = loadPrices()) {
204
+ const p = priceFor(model, prices);
205
+ const oneHour = Math.min(usage.cache_creation_1h_input_tokens ?? 0, usage.cache_creation_input_tokens);
206
+ return (usage.input_tokens * p.input + (usage.cache_creation_input_tokens - oneHour) * p.cache_write_5m + oneHour * (p.cache_write_1h ?? p.cache_write_5m) + usage.cache_read_input_tokens * p.cache_read + usage.output_tokens * p.output) / 1e6;
207
+ }
208
+ function costOfModels(byModel, prices = loadPrices()) {
209
+ let cost = 0;
210
+ const unpriced = [];
211
+ for (const [model, u] of Object.entries(byModel)) {
212
+ if (prices.models[model]) cost += costOf(u.usage, model, prices);
213
+ else {
214
+ cost += u.reportedCostUsd ?? 0;
215
+ unpriced.push(model);
216
+ }
217
+ }
218
+ return { cost, unpriced };
219
+ }
220
+
221
+ // src/costs.ts
222
+ var inputSide = (t) => t.input_tokens + t.cache_write_tokens + t.cache_read_tokens;
223
+ function priceTokens(t, model, prices, backend) {
224
+ const p = priceFor(model, prices);
225
+ const oneHour = t.cache_write_1h_tokens ?? (backend === "claude-code" ? t.cache_write_tokens : 0);
226
+ return (t.input_tokens * p.input + (t.cache_write_tokens - oneHour) * p.cache_write_5m + oneHour * (p.cache_write_1h ?? p.cache_write_5m) + t.cache_read_tokens * p.cache_read + t.output_tokens * p.output) / 1e6;
227
+ }
228
+ function directApiCost(t, model, prices, backend, overheadPerCall) {
229
+ if (backend === "api") return priceTokens(t, model, prices, backend);
230
+ const p = priceFor(model, prices);
231
+ const input = Math.max(0, inputSide(t) - overheadPerCall * t.requests);
232
+ return (input * p.input + t.output_tokens * p.output) / 1e6;
233
+ }
234
+ function costViews(tiers, baselineModel, prices, backend, overheadPerCall) {
235
+ const v = { actual_usd: 0, direct_api_usd: 0, baseline_usd: 0, baseline_direct_api_usd: 0 };
236
+ for (const t of tiers) {
237
+ if (!t.requests && !t.output_tokens && !inputSide(t)) continue;
238
+ v.actual_usd += t.cost_usd;
239
+ v.direct_api_usd += backend === "api" ? t.cost_usd : directApiCost(t, t.model, prices, backend, overheadPerCall);
240
+ v.baseline_usd += priceTokens(t, baselineModel, prices, backend);
241
+ v.baseline_direct_api_usd += directApiCost(t, baselineModel, prices, backend, overheadPerCall);
242
+ }
243
+ return v;
244
+ }
245
+ var savingsPct = (cost, baseline) => baseline > 0 ? Math.round((1 - cost / baseline) * 1e3) / 10 : 0;
246
+
247
+ // src/tier0/diff.ts
248
+ var HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/;
249
+ function unquote(p) {
250
+ if (p.startsWith('"') && p.endsWith('"')) {
251
+ return p.slice(1, -1).replace(/\\(["\\])/g, "$1");
252
+ }
253
+ return p;
254
+ }
255
+ function stripPrefix(p) {
256
+ return unquote(p).replace(/^[ab]\//, "");
257
+ }
258
+ function pathFromGitHeader(rest) {
259
+ const m = /^"?a\/(.+?)"? "?b\/(.+)"?$/.exec(rest);
260
+ if (m && m[1] === m[2]) return m[2];
261
+ const half = rest.length >> 1;
262
+ return stripPrefix(rest.slice(half + 1));
263
+ }
264
+ function parseDiffFiles(text) {
265
+ const lines2 = text.split("\n");
266
+ if (lines2[lines2.length - 1] === "") lines2.pop();
267
+ const files = [];
268
+ let i = 0;
269
+ while (i < lines2.length) {
270
+ const line = lines2[i].replace(/\r$/, "");
271
+ if (!line.startsWith("diff --git ")) {
272
+ i++;
273
+ continue;
274
+ }
275
+ const file = {
276
+ path: pathFromGitHeader(line.slice("diff --git ".length)),
277
+ status: "modified",
278
+ binary: false,
279
+ hunks: []
280
+ };
281
+ let oldPath;
282
+ let newPath;
283
+ i++;
284
+ for (; i < lines2.length; i++) {
285
+ const l = lines2[i].replace(/\r$/, "");
286
+ if (l.startsWith("diff --git ") || l.startsWith("@@")) break;
287
+ if (l.startsWith("new file mode")) file.status = "added";
288
+ else if (l.startsWith("deleted file mode")) file.status = "deleted";
289
+ else if (l.startsWith("rename from ")) {
290
+ file.status = "renamed";
291
+ oldPath = unquote(l.slice("rename from ".length));
292
+ } else if (l.startsWith("rename to ")) newPath = unquote(l.slice("rename to ".length));
293
+ else if (l.startsWith("Binary files ") || l.startsWith("GIT binary patch")) file.binary = true;
294
+ else if (l.startsWith("--- ")) {
295
+ const p = l.slice(4);
296
+ if (p !== "/dev/null") oldPath ??= stripPrefix(p);
297
+ } else if (l.startsWith("+++ ")) {
298
+ const p = l.slice(4);
299
+ if (p !== "/dev/null") newPath = stripPrefix(p);
300
+ }
301
+ }
302
+ if (file.status === "deleted") file.path = oldPath ?? file.path;
303
+ else file.path = newPath ?? file.path;
304
+ if (file.status === "renamed") file.oldPath = oldPath;
305
+ let n2 = 0;
306
+ while (i < lines2.length && !lines2[i].startsWith("diff --git ")) {
307
+ const m = HUNK_RE.exec(lines2[i].replace(/\r$/, ""));
308
+ if (!m) {
309
+ i++;
310
+ continue;
311
+ }
312
+ i++;
313
+ const oldStart = Number(m[1]);
314
+ const oldLines = m[2] === void 0 ? 1 : Number(m[2]);
315
+ const newStart = Number(m[3]);
316
+ const newLines = m[4] === void 0 ? 1 : Number(m[4]);
317
+ const body = [];
318
+ let oldNo = oldStart;
319
+ let newNo = newStart;
320
+ let oldLeft = oldLines;
321
+ let newLeft = newLines;
322
+ let added = 0;
323
+ let deleted = 0;
324
+ while (i < lines2.length && (oldLeft > 0 || newLeft > 0 || lines2[i].startsWith("\\"))) {
325
+ const raw = lines2[i];
326
+ if (raw.startsWith("\\")) {
327
+ i++;
328
+ continue;
329
+ }
330
+ const c = raw[0];
331
+ const text2 = raw.slice(1);
332
+ if (c === "+") {
333
+ body.push({ kind: "add", text: text2, newNo: newNo++ });
334
+ newLeft--;
335
+ added++;
336
+ } else if (c === "-") {
337
+ body.push({ kind: "del", text: text2, oldNo: oldNo++ });
338
+ oldLeft--;
339
+ deleted++;
340
+ } else {
341
+ body.push({ kind: "ctx", text: c === " " ? text2 : raw, oldNo: oldNo++, newNo: newNo++ });
342
+ oldLeft--;
343
+ newLeft--;
344
+ }
345
+ i++;
346
+ }
347
+ n2++;
348
+ file.hunks.push({
349
+ id: `${file.path}#${n2}`,
350
+ file: file.path,
351
+ ...file.oldPath ? { oldFile: file.oldPath } : {},
352
+ status: file.status,
353
+ oldStart,
354
+ oldLines,
355
+ newStart,
356
+ newLines,
357
+ header: (m[5] ?? "").trim(),
358
+ lines: body,
359
+ added,
360
+ deleted
361
+ });
362
+ }
363
+ files.push(file);
364
+ }
365
+ return files;
366
+ }
367
+ function formatHunk(h) {
368
+ const out = [`@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@ ${h.header}`.trimEnd()];
369
+ for (const l of h.lines) out.push((l.kind === "add" ? "+" : l.kind === "del" ? "-" : " ") + l.text);
370
+ return out.join("\n");
371
+ }
372
+
373
+ // src/tiers/batch.ts
374
+ function limitsFor(backend, tier, cfg, est) {
375
+ if (backend === "claude-code") {
376
+ const c = cfg.backend.claude_code;
377
+ return { mode: "batch", maxHunks: c.max_hunks_per_call, maxTokens: c.max_tokens_per_call };
378
+ }
379
+ if (tier === 1) return { mode: "batch", maxHunks: est.tier1_batch.max_hunks, maxTokens: est.tier1_batch.max_tokens };
380
+ return { mode: "file", maxHunks: Infinity, maxTokens: Infinity };
381
+ }
382
+ var hunkIndex = (h) => Number(h.id.slice(h.id.lastIndexOf("#") + 1));
383
+ function packHunks(hunks, limits, tokensOf) {
384
+ const byFile = /* @__PURE__ */ new Map();
385
+ for (const h of [...hunks].sort((a, b) => a.file.localeCompare(b.file) || hunkIndex(a) - hunkIndex(b))) {
386
+ const g = byFile.get(h.file);
387
+ if (g) g.push(h);
388
+ else byFile.set(h.file, [h]);
389
+ }
390
+ const groups = [...byFile.values()];
391
+ if (limits.mode === "file") return groups;
392
+ const out = [];
393
+ let cur = [];
394
+ let curTokens = 0;
395
+ const flush = () => {
396
+ if (cur.length) out.push(cur);
397
+ cur = [];
398
+ curTokens = 0;
399
+ };
400
+ const fits = (n2, t) => cur.length + n2 <= limits.maxHunks && curTokens + t <= limits.maxTokens;
401
+ for (const g of groups) {
402
+ const gTokens = g.reduce((a, h) => a + tokensOf(h), 0);
403
+ if (fits(g.length, gTokens)) {
404
+ cur.push(...g);
405
+ curTokens += gTokens;
406
+ continue;
407
+ }
408
+ flush();
409
+ if (g.length <= limits.maxHunks && gTokens <= limits.maxTokens) {
410
+ cur.push(...g);
411
+ curTokens = gTokens;
412
+ continue;
413
+ }
414
+ for (const h of g) {
415
+ const t = tokensOf(h);
416
+ if (cur.length && !fits(1, t)) flush();
417
+ cur.push(h);
418
+ curTokens += t;
419
+ }
420
+ }
421
+ flush();
422
+ return out;
423
+ }
424
+
425
+ // src/tiers/collapse.ts
426
+ var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
427
+ var tiersMerged = (cfg) => cfg.models.tier2.model === cfg.models.tier3.model;
428
+ function collapseTiers(cfg, routed) {
429
+ if (!tiersMerged(cfg)) return { cfg, routed, merged: false };
430
+ const e2 = EFFORTS.indexOf(cfg.models.tier2.effort);
431
+ const e3 = EFFORTS.indexOf(cfg.models.tier3.effort);
432
+ const effort = EFFORTS[Math.max(e2, e3)];
433
+ const merged = { ...cfg, models: { ...cfg.models, tier3: { ...cfg.models.tier3, effort } } };
434
+ const out = routed.map(
435
+ (h) => h.tier === 2 ? { ...h, tier: 3, reasons: [...h.reasons, { signal: "merge", weight: 0, detail: `Tier 2 and Tier 3 run the same model: one call at ${effort} effort` }] } : h
436
+ );
437
+ return { cfg: merged, routed: out, merged: true };
438
+ }
439
+
440
+ // src/estimate.ts
441
+ var PerTier = z3.object({ tier1: z3.number(), tier2: z3.number(), tier3: z3.number() });
442
+ var EstimatesFile = z3.object({
443
+ calibrated: z3.boolean(),
444
+ note: z3.string().optional(),
445
+ chars_per_token: z3.number().positive(),
446
+ system_prompt_tokens: z3.number(),
447
+ shared_context_tokens_per_file: z3.number(),
448
+ shared_context_tokens_per_hunk: z3.number(),
449
+ context_tokens_per_hunk: PerTier,
450
+ output_tokens_per_hunk: PerTier,
451
+ tier1_batch: z3.object({ max_hunks: z3.number(), max_tokens: z3.number() }),
452
+ escalation_reserve: z3.number(),
453
+ /** Tokens Claude Code adds to every `claude -p` call (its structured-output tool and second turn). */
454
+ claude_code_overhead_tokens_per_call: z3.number().default(0)
455
+ });
456
+ function loadEstimates(path = configPath("estimates.json")) {
457
+ return EstimatesFile.parse(JSON.parse(readFileSync3(path, "utf8")));
458
+ }
459
+ function estimateTokens(text, est) {
460
+ return Math.ceil(text.length / est.chars_per_token);
461
+ }
462
+ var key = (t) => `tier${t}`;
463
+ var ctxTokens = (tier, cfg, est) => est.context_tokens_per_hunk[key(tier === 1 && cfg.tier1_context === "tier3" ? 3 : tier)];
464
+ function requestsFor(tier, hunks, tokens2, cfg, est, backend) {
465
+ if (hunks.length === 0) return 0;
466
+ const ctx = ctxTokens(tier, cfg, est);
467
+ return packHunks(hunks, limitsFor(backend, tier, cfg, est), (h) => tokens2.get(h.id) + (backend === "claude-code" ? ctx : 0)).length;
468
+ }
469
+ function estimateTier(tier, hunks, all, cfg, prices, est, tokens2, backend, model = cfg.models[key(tier)].model, outputPerHunk = est.output_tokens_per_hunk[key(tier)]) {
470
+ const m = cfg.models[key(tier)];
471
+ const p = priceFor(model, prices);
472
+ const requests = requestsFor(tier, hunks, tokens2, cfg, est, backend);
473
+ const files = new Set(all.map((h) => h.file)).size;
474
+ const shared = files * est.shared_context_tokens_per_file + all.length * est.shared_context_tokens_per_hunk;
475
+ const perRequest = est.system_prompt_tokens + shared + (backend === "claude-code" ? est.claude_code_overhead_tokens_per_call : 0);
476
+ let input = requests * perRequest;
477
+ for (const h of hunks) input += tokens2.get(h.id) + ctxTokens(tier, cfg, est);
478
+ const output = Math.round(hunks.length * outputPerHunk);
479
+ return {
480
+ tier,
481
+ model,
482
+ effort: m.effort,
483
+ hunks: hunks.length,
484
+ requests,
485
+ input_tokens: input,
486
+ output_tokens: output,
487
+ cost_usd: (input * p.input + output * p.output) / 1e6
488
+ };
489
+ }
490
+ function estimatePlan(routed, cfg, prices = loadPrices(), est = loadEstimates(), backend = "api") {
491
+ ({ cfg, routed } = collapseTiers(cfg, routed));
492
+ const reviewable = routed.filter((h) => h.tier !== 0);
493
+ const tokens2 = new Map(reviewable.map((h) => [h.id, estimateTokens(formatHunk(h), est)]));
494
+ const tiers = [1, 2, 3].map(
495
+ (t) => estimateTier(t, reviewable.filter((h) => h.tier === t), reviewable, cfg, prices, est, tokens2, backend)
496
+ );
497
+ const overhead = backend === "claude-code" ? est.claude_code_overhead_tokens_per_call : 0;
498
+ const v = costViews(
499
+ tiers.map((t) => ({ model: t.model, cost_usd: t.cost_usd, requests: t.requests, input_tokens: t.input_tokens, cache_write_tokens: 0, cache_read_tokens: 0, output_tokens: t.output_tokens })),
500
+ cfg.receipt.baseline.model,
501
+ prices,
502
+ backend,
503
+ overhead
504
+ );
505
+ const total = v.actual_usd;
506
+ const reserve = total * est.escalation_reserve;
507
+ return {
508
+ tiers,
509
+ total_usd: total,
510
+ total_direct_api_usd: v.direct_api_usd,
511
+ reserve_usd: reserve,
512
+ baseline: { model: cfg.receipt.baseline.model, method: "estimated_tokens_at_baseline_prices", cost_usd: v.baseline_usd, direct_api_cost_usd: v.baseline_direct_api_usd },
513
+ savings_pct: savingsPct(total, v.baseline_usd),
514
+ backend,
515
+ skipped_hunks: routed.length - reviewable.length,
516
+ calibrated: est.calibrated
517
+ };
518
+ }
519
+
520
+ // src/fable.ts
521
+ var FABLE_NOT_ENABLED = "Fable not enabled";
522
+ var FABLE_WARNING = "tierview: Fable is enabled (--allow-fable / allowFable). On some Claude plans Fable may use paid extra usage, and `claude -p` does not ask before using it.\n";
523
+ var isFable = (model) => /fable/i.test(model);
524
+ function displayName(id) {
525
+ const m = /^claude-([a-z]+)-(\d+)-(\d+)/.exec(id);
526
+ if (!m) return id;
527
+ return `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}.${m[3]}`;
528
+ }
529
+ function applyFablePolicy(cfg, backend, allowFable) {
530
+ if (backend !== "claude-code" || allowFable) return { cfg, substitutions: [] };
531
+ const tiers = [1, 2, 3];
532
+ const fableTiers = tiers.filter((t) => isFable(cfg.models[`tier${t}`].model));
533
+ if (!fableTiers.length) return { cfg, substitutions: [] };
534
+ const substitute = [cfg.models.tier2.model, cfg.models.tier1.model].find((m) => !isFable(m));
535
+ if (!substitute) throw new ConfigError("every tier model is Fable, but Fable is not enabled. Pass --allow-fable, set allowFable: true, or choose another model.");
536
+ const models = { ...cfg.models };
537
+ const substitutions = [];
538
+ for (const t of fableTiers) {
539
+ const k = `tier${t}`;
540
+ substitutions.push({ tier: t, requested: models[k].model, used: substitute, reason: FABLE_NOT_ENABLED });
541
+ models[k] = { ...models[k], model: substitute };
542
+ }
543
+ return { cfg: { ...cfg, models }, substitutions };
544
+ }
545
+ var usesFable = (cfg) => [cfg.models.tier1, cfg.models.tier2, cfg.models.tier3].some((m) => isFable(m.model));
546
+ function substitutionLine(s) {
547
+ if (s.reason === FABLE_NOT_ENABLED) return `Tier ${s.tier} ran on ${displayName(s.used)} (${FABLE_NOT_ENABLED})`;
548
+ return `Tier ${s.tier} ran on ${displayName(s.used)} instead of ${displayName(s.requested)} (${s.reason})`;
549
+ }
550
+
551
+ // src/git.ts
552
+ import { execFileSync } from "child_process";
553
+ import { readFileSync as readFileSync4 } from "fs";
554
+ import { join as join3 } from "path";
555
+ function git(args, cwd) {
556
+ return execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
557
+ }
558
+ function getDiff(opts = {}) {
559
+ const args = ["diff", "--no-color", "-U3", "-M"];
560
+ if (opts.staged) args.push("--cached");
561
+ args.push(opts.base ?? "HEAD");
562
+ if (opts.head) args.push(opts.head);
563
+ let out = git(args, opts.cwd);
564
+ if (opts.includeUntracked) {
565
+ if (opts.head || opts.staged) throw new Error("--include-untracked only works on a working-tree diff (no --head, no --staged)");
566
+ for (const f of untrackedFiles(opts.cwd)) out += diffNewFile(f, opts.cwd);
567
+ }
568
+ return out;
569
+ }
570
+ function untrackedFiles(cwd) {
571
+ const root = repoRoot(cwd);
572
+ return git(["ls-files", "--others", "--exclude-standard", "-z"], root).split("\0").filter(Boolean).sort();
573
+ }
574
+ function diffNewFile(path, cwd) {
575
+ try {
576
+ return git(["diff", "--no-color", "-U3", "--no-index", "--", "/dev/null", path], repoRoot(cwd));
577
+ } catch (e) {
578
+ const err = e;
579
+ if (err.status === 1 && typeof err.stdout === "string") return err.stdout;
580
+ throw e;
581
+ }
582
+ }
583
+ function repoRoot(cwd) {
584
+ return git(["rev-parse", "--show-toplevel"], cwd).trim();
585
+ }
586
+ function fileSource(opts = {}) {
587
+ const root = repoRoot(opts.cwd);
588
+ return (path) => {
589
+ try {
590
+ if (opts.head) return git(["show", `${opts.head}:${path}`], root);
591
+ if (opts.staged) return git(["show", `:${path}`], root);
592
+ return readFileSync4(join3(root, path), "utf8");
593
+ } catch {
594
+ return null;
595
+ }
596
+ };
597
+ }
598
+ function isShallow(cwd) {
599
+ try {
600
+ return git(["rev-parse", "--is-shallow-repository"], cwd).trim() === "true";
601
+ } catch {
602
+ return true;
603
+ }
604
+ }
605
+ function fileChurn(paths, days, fixPattern = "\\bfix(es|ed)?\\b|bug|regress", cwd) {
606
+ const out = {};
607
+ for (const p of paths) out[p] = { commits: 0, fixCommits: 0 };
608
+ if (paths.length === 0 || isShallow(cwd)) return out;
609
+ const fixRe = new RegExp(fixPattern, "i");
610
+ let log;
611
+ try {
612
+ log = git(["log", `--since=${days}.days`, "--no-merges", "--name-only", "--format=%x1e%s"], cwd);
613
+ } catch {
614
+ return out;
615
+ }
616
+ for (const entry of log.split("")) {
617
+ if (!entry.trim()) continue;
618
+ const [subject = "", ...files] = entry.split("\n");
619
+ const isFix = fixRe.test(subject);
620
+ for (const f of new Set(files.map((x) => x.trim()).filter(Boolean))) {
621
+ const c = out[f];
622
+ if (!c) continue;
623
+ c.commits++;
624
+ if (isFix) c.fixCommits++;
625
+ }
626
+ }
627
+ return out;
628
+ }
629
+
630
+ // src/types.ts
631
+ import { z as z4 } from "zod";
632
+ var Severity = z4.enum(["critical", "high", "medium", "low", "info"]);
633
+ var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
634
+ var Category2 = z4.enum([
635
+ "bug",
636
+ "security",
637
+ "concurrency",
638
+ "data-loss",
639
+ "performance",
640
+ "api-contract",
641
+ "error-handling",
642
+ "test",
643
+ "maintainability"
644
+ ]);
645
+ var Verdict = z4.enum(["clean", "issues", "unsure"]);
646
+ var ModelFinding = z4.object({
647
+ file: z4.string(),
648
+ start_line: z4.number().int(),
649
+ end_line: z4.number().int(),
650
+ side: z4.enum(["new", "old"]),
651
+ severity: Severity,
652
+ category: Category2,
653
+ title: z4.string(),
654
+ explanation: z4.string(),
655
+ suggestion: z4.string(),
656
+ evidence: z4.string(),
657
+ confidence: z4.number()
658
+ });
659
+ var HunkReview = z4.object({
660
+ hunk_id: z4.string(),
661
+ verdict: Verdict,
662
+ confidence: z4.number(),
663
+ needs_escalation: z4.boolean(),
664
+ escalation_reason: z4.string(),
665
+ refuted_prior: z4.array(z4.string()),
666
+ findings: z4.array(ModelFinding)
667
+ });
668
+ var TierResponse = z4.object({ reviews: z4.array(HunkReview) });
669
+ var Finding = ModelFinding.extend({
670
+ id: z4.string(),
671
+ hunk_id: z4.string(),
672
+ model: z4.string(),
673
+ tier: z4.union([z4.literal(1), z4.literal(2), z4.literal(3)]),
674
+ escalated_from: z4.array(z4.union([z4.literal(1), z4.literal(2)])),
675
+ also_reported_by: z4.array(z4.string())
676
+ });
677
+ var TierReceipt = z4.object({
678
+ tier: z4.union([z4.literal(1), z4.literal(2), z4.literal(3)]),
679
+ model: z4.string(),
680
+ effort: z4.string(),
681
+ hunks: z4.number().int(),
682
+ escalated_in: z4.number().int(),
683
+ requests: z4.number().int(),
684
+ input_tokens: z4.number().int(),
685
+ cache_write_tokens: z4.number().int(),
686
+ cache_read_tokens: z4.number().int(),
687
+ output_tokens: z4.number().int(),
688
+ /** Part of cache_write_tokens written with the 1-hour TTL (Claude Code on a plan). */
689
+ cache_write_1h_tokens: z4.number().int(),
690
+ /** Actual cost: via Claude Code on claude-code (API-equivalent), billed on api. */
691
+ cost_usd: z4.number(),
692
+ /** The same tokens without Claude Code's per-call overhead, at the uncached input rate (= cost_usd on api). */
693
+ direct_api_cost_usd: z4.number()
694
+ });
695
+ var Backend = z4.enum(["claude-code", "api"]);
696
+ var ModelSubstitution = z4.object({
697
+ tier: z4.union([z4.literal(1), z4.literal(2), z4.literal(3)]),
698
+ requested: z4.string(),
699
+ used: z4.string(),
700
+ reason: z4.string()
701
+ });
702
+ var Receipt = z4.object({
703
+ /** Which backend ran the models. */
704
+ backend: Backend,
705
+ /** "billed": API list-price cost of this run. "api_equivalent": claude-code backend; tokens priced at API list prices, not what the plan bills. */
706
+ cost_basis: z4.enum(["billed", "api_equivalent"]),
707
+ /** Model calls made (API requests or `claude -p` invocations), retries included. */
708
+ calls: z4.number().int(),
709
+ model_substitutions: z4.array(ModelSubstitution),
710
+ tiers: z4.array(TierReceipt),
711
+ skipped_hunks: z4.number().int(),
712
+ not_reviewed_hunks: z4.number().int(),
713
+ total_cost_usd: z4.number(),
714
+ total_direct_api_cost_usd: z4.number(),
715
+ /** All-Fable: this run's actual tokens priced at the baseline model's rates (a calculation; PLAN §7). */
716
+ baseline: z4.object({
717
+ model: z4.string(),
718
+ method: z4.literal("actual_tokens_at_baseline_prices"),
719
+ cost_usd: z4.number(),
720
+ direct_api_cost_usd: z4.number()
721
+ }),
722
+ savings_pct: z4.number(),
723
+ budget: z4.object({ max_cost_usd: z4.number().nullable(), degraded: z4.boolean() }),
724
+ warnings: z4.array(z4.string()),
725
+ wall_ms: z4.number().int(),
726
+ prices_as_of: z4.string()
727
+ });
728
+ var Review = z4.object({
729
+ version: z4.literal(1),
730
+ findings: z4.array(Finding),
731
+ refuted: z4.array(Finding),
732
+ not_reviewed: z4.array(z4.object({ hunk_id: z4.string(), reason: z4.string() })),
733
+ routing: z4.array(
734
+ z4.object({
735
+ hunk_id: z4.string(),
736
+ score: z4.number(),
737
+ tier: z4.union([z4.literal(0), z4.literal(1), z4.literal(2), z4.literal(3)]),
738
+ reasons: z4.array(z4.object({ signal: z4.string(), weight: z4.number(), detail: z4.string() }))
739
+ })
740
+ ),
741
+ receipt: Receipt
742
+ });
743
+ var EXIT = { OK: 0, FINDINGS: 1, USAGE: 2, BUDGET: 3 };
744
+
745
+ // src/llm/backend.ts
746
+ var BackendSetupError = class extends Error {
747
+ };
748
+ var ZERO_USAGE = { input_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 0 };
749
+ function addUsage(into, model, u, reportedCostUsd) {
750
+ const cur = into[model] ?? { usage: { ...ZERO_USAGE } };
751
+ const prev1h = cur.usage.cache_creation_1h_input_tokens;
752
+ cur.usage = {
753
+ input_tokens: cur.usage.input_tokens + u.input_tokens,
754
+ cache_creation_input_tokens: cur.usage.cache_creation_input_tokens + u.cache_creation_input_tokens,
755
+ cache_read_input_tokens: cur.usage.cache_read_input_tokens + u.cache_read_input_tokens,
756
+ output_tokens: cur.usage.output_tokens + u.output_tokens
757
+ };
758
+ const oneHour = (prev1h ?? 0) + (u.cache_creation_1h_input_tokens ?? 0);
759
+ if (oneHour) cur.usage.cache_creation_1h_input_tokens = oneHour;
760
+ if (reportedCostUsd !== void 0) cur.reportedCostUsd = (cur.reportedCostUsd ?? 0) + reportedCostUsd;
761
+ into[model] = cur;
762
+ }
763
+ function parseTierResponse(value) {
764
+ const r = TierResponse.safeParse(value);
765
+ return r.success ? r.data : null;
766
+ }
767
+
768
+ // src/llm/claude-code.ts
769
+ import { spawn } from "child_process";
770
+ import { existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync as readFileSync5, rmSync, writeFileSync } from "fs";
771
+ import { homedir, tmpdir } from "os";
772
+ import { dirname as dirname2, join as join4 } from "path";
773
+ import { z as z5 } from "zod";
774
+ var runProcess = (bin, args, stdin, opts) => new Promise((resolve) => {
775
+ const child = spawn(bin, args, { cwd: opts.cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
776
+ let stdout = "";
777
+ let stderr = "";
778
+ let timedOut = false;
779
+ const timer = setTimeout(() => {
780
+ timedOut = true;
781
+ child.kill();
782
+ }, opts.timeoutMs);
783
+ child.stdout.setEncoding("utf8").on("data", (d) => stdout += d);
784
+ child.stderr.setEncoding("utf8").on("data", (d) => stderr += d);
785
+ child.on("error", (e) => {
786
+ clearTimeout(timer);
787
+ resolve({ code: null, stdout, stderr: stderr + String(e), timedOut });
788
+ });
789
+ child.on("close", (code) => {
790
+ clearTimeout(timer);
791
+ resolve({ code, stdout, stderr, timedOut });
792
+ });
793
+ child.stdin.end(stdin, "utf8");
794
+ });
795
+ function resolveClaudeBinary(o = {}) {
796
+ const env = o.env ?? process.env;
797
+ const platform = o.platform ?? process.platform;
798
+ const exists = o.exists ?? existsSync2;
799
+ const explicit = env.TIERVIEW_CLAUDE_BIN || o.configured;
800
+ if (explicit) return exists(explicit) ? explicit : null;
801
+ const name = platform === "win32" ? "claude.exe" : "claude";
802
+ const sep = platform === "win32" ? ";" : ":";
803
+ for (const dir of (env.PATH ?? env.Path ?? "").split(sep).filter(Boolean)) {
804
+ const p = join4(dir, name);
805
+ if (exists(p)) return p;
806
+ }
807
+ const local = join4(o.home ?? homedir(), ".local", "bin", name);
808
+ return exists(local) ? local : null;
809
+ }
810
+ var ModelUsageEntry = z5.object({
811
+ inputTokens: z5.number().default(0),
812
+ outputTokens: z5.number().default(0),
813
+ cacheReadInputTokens: z5.number().default(0),
814
+ cacheCreationInputTokens: z5.number().default(0),
815
+ cacheCreationEphemeral1hInputTokens: z5.number().default(0),
816
+ costUSD: z5.number().optional()
817
+ });
818
+ var CliResult = z5.object({
819
+ type: z5.string().optional(),
820
+ subtype: z5.string().optional(),
821
+ is_error: z5.boolean().optional(),
822
+ result: z5.string().optional(),
823
+ stop_reason: z5.string().nullable().optional(),
824
+ structured_output: z5.unknown().optional(),
825
+ usage: z5.object({
826
+ input_tokens: z5.number().default(0),
827
+ output_tokens: z5.number().default(0),
828
+ cache_creation_input_tokens: z5.number().default(0),
829
+ cache_read_input_tokens: z5.number().default(0)
830
+ }).partial().optional(),
831
+ modelUsage: z5.record(z5.string(), ModelUsageEntry).optional(),
832
+ total_cost_usd: z5.number().optional()
833
+ });
834
+ var normalizeModel = (m) => m.replace(/\[[^\]]*\]$/, "").trim();
835
+ function parseRun(run, requested) {
836
+ const usageByModel = {};
837
+ let json = null;
838
+ const text = run.stdout.trim();
839
+ const last = text.lastIndexOf("\n{");
840
+ for (const candidate of [text, last >= 0 ? text.slice(last + 1) : ""]) {
841
+ if (!candidate) continue;
842
+ try {
843
+ const r = CliResult.safeParse(JSON.parse(candidate));
844
+ if (r.success) {
845
+ json = r.data;
846
+ break;
847
+ }
848
+ } catch {
849
+ }
850
+ }
851
+ if (!json) {
852
+ const why2 = run.timedOut ? "timed out" : `exit ${run.code}: ${(run.stderr || run.stdout).trim().slice(0, 400) || "no output"}`;
853
+ return { ok: false, structured: void 0, refusal: false, error: `claude produced no JSON result (${why2})`, usageByModel, dominant: null };
854
+ }
855
+ if (json.modelUsage && Object.keys(json.modelUsage).length) {
856
+ for (const [m, u] of Object.entries(json.modelUsage)) {
857
+ const usage = { input_tokens: u.inputTokens, output_tokens: u.outputTokens, cache_read_input_tokens: u.cacheReadInputTokens, cache_creation_input_tokens: u.cacheCreationInputTokens, cache_creation_1h_input_tokens: u.cacheCreationEphemeral1hInputTokens };
858
+ addUsage(usageByModel, normalizeModel(m), usage, u.costUSD);
859
+ }
860
+ } else if (json.usage) {
861
+ const u = json.usage;
862
+ addUsage(usageByModel, requested, { input_tokens: u.input_tokens ?? 0, output_tokens: u.output_tokens ?? 0, cache_read_input_tokens: u.cache_read_input_tokens ?? 0, cache_creation_input_tokens: u.cache_creation_input_tokens ?? 0 }, json.total_cost_usd);
863
+ }
864
+ let dominant = null;
865
+ let best = -1;
866
+ for (const [m, u] of Object.entries(usageByModel)) {
867
+ const score = u.usage.output_tokens * 1e6 + u.usage.input_tokens + u.usage.cache_read_input_tokens + u.usage.cache_creation_input_tokens;
868
+ if (score > best) {
869
+ best = score;
870
+ dominant = m;
871
+ }
872
+ }
873
+ const error = json.is_error || json.subtype && json.subtype !== "success" ? `${json.subtype ?? "error"}: ${(json.result ?? "").slice(0, 400)}` : null;
874
+ const refusal = json.stop_reason === "refusal";
875
+ return { ok: !error && json.structured_output !== void 0, structured: json.structured_output, refusal, error, usageByModel, dominant };
876
+ }
877
+ var MODEL_PROBLEM = /model|not available|not found|restricted|usage credits|access/i;
878
+ var CacheFile = z5.object({
879
+ version: z5.literal(1),
880
+ models: z5.record(z5.string(), z5.object({ used: z5.string(), checked: z5.string(), reason: z5.string() }))
881
+ });
882
+ var CACHE_MAX_AGE_DAYS = 7;
883
+ function defaultCachePath(home = homedir()) {
884
+ return join4(home, ".tierview", "claude-code-models.json");
885
+ }
886
+ function readModelCache(path, now = /* @__PURE__ */ new Date()) {
887
+ try {
888
+ const parsed = CacheFile.parse(JSON.parse(readFileSync5(path, "utf8")));
889
+ const fresh = {};
890
+ for (const [k, v] of Object.entries(parsed.models)) {
891
+ if ((now.getTime() - Date.parse(v.checked)) / 864e5 <= CACHE_MAX_AGE_DAYS) fresh[k] = v;
892
+ }
893
+ return fresh;
894
+ } catch {
895
+ return {};
896
+ }
897
+ }
898
+ function writeModelCache(path, models) {
899
+ try {
900
+ mkdirSync(dirname2(path), { recursive: true });
901
+ writeFileSync(path, JSON.stringify({ version: 1, models }, null, 2) + "\n");
902
+ } catch {
903
+ }
904
+ }
905
+ var UNSUPPORTED = /* @__PURE__ */ new Set(["$schema", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength"]);
906
+ function cleanSchema(v) {
907
+ if (Array.isArray(v)) return v.map(cleanSchema);
908
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).filter(([k]) => !UNSUPPORTED.has(k)).map(([k, x]) => [k, cleanSchema(x)]));
909
+ return v;
910
+ }
911
+ var SCHEMA_JSON = JSON.stringify(cleanSchema(z5.toJSONSchema(TierResponse)));
912
+ function buildArgs(req, model, systemFile, fallbackModel, schemaJson = SCHEMA_JSON) {
913
+ const args = [
914
+ "-p",
915
+ "--output-format",
916
+ "json",
917
+ "--json-schema",
918
+ schemaJson,
919
+ "--model",
920
+ model,
921
+ "--effort",
922
+ req.effort,
923
+ "--tools",
924
+ "",
925
+ "--system-prompt-file",
926
+ systemFile,
927
+ "--no-session-persistence",
928
+ "--disable-slash-commands",
929
+ "--strict-mcp-config",
930
+ "--safe-mode"
931
+ ];
932
+ if (fallbackModel && fallbackModel !== model) args.push("--fallback-model", fallbackModel);
933
+ return args;
934
+ }
935
+ async function verifyClaudeBinary(bin, run = runProcess) {
936
+ const r = await run(bin, ["--version"], "", { cwd: tmpdir(), timeoutMs: 3e4 });
937
+ const line = r.stdout.trim().split("\n")[0] ?? "";
938
+ if (r.code !== 0 || !/\(Claude Code\)/.test(line)) {
939
+ throw new BackendSetupError(`${bin} does not look like the official Claude Code CLI (\`--version\` printed "${line || r.stderr.trim()}").`);
940
+ }
941
+ return line;
942
+ }
943
+ var ClaudeCodeBackend = class {
944
+ constructor(opts) {
945
+ this.opts = opts;
946
+ this.run = opts.run ?? runProcess;
947
+ this.timeoutMs = opts.timeoutMs ?? 9e5;
948
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
949
+ this.cache = opts.cachePath ? readModelCache(opts.cachePath, this.now()) : {};
950
+ for (const [requested, v] of Object.entries(this.cache)) if (v.used !== requested) this.resolved.set(requested, v.used);
951
+ }
952
+ opts;
953
+ name = "claude-code";
954
+ concurrency = 1;
955
+ run;
956
+ timeoutMs;
957
+ resolved = /* @__PURE__ */ new Map();
958
+ subs = [];
959
+ cache;
960
+ now;
961
+ substitutions() {
962
+ return [...this.subs];
963
+ }
964
+ note(tier, requested, used, reason, persist) {
965
+ this.resolved.set(requested, used);
966
+ if (!this.subs.some((s) => s.tier === tier && s.requested === requested)) this.subs.push({ tier, requested, used, reason });
967
+ if (persist && this.opts.cachePath) {
968
+ this.cache[requested] = { used, checked: this.now().toISOString(), reason };
969
+ writeModelCache(this.opts.cachePath, this.cache);
970
+ }
971
+ }
972
+ async once(req, model) {
973
+ if (!this.opts.allowFable && (isFable(model) || req.fallbackModel !== void 0 && isFable(req.fallbackModel))) {
974
+ throw new BackendSetupError(`refusing to request ${model} through Claude Code: ${FABLE_NOT_ENABLED} (pass --allow-fable).`);
975
+ }
976
+ const dir = mkdtempSync(join4(tmpdir(), "tierview-cc-"));
977
+ try {
978
+ const systemFile = join4(dir, "system.txt");
979
+ writeFileSync(systemFile, `${req.system}
980
+
981
+ ${req.shared}`);
982
+ const run = await this.run(this.opts.bin, buildArgs(req, model, systemFile, req.fallbackModel), req.user, { cwd: dir, timeoutMs: this.timeoutMs });
983
+ const parsed = parseRun(run, model);
984
+ const debugDir = process.env.TIERVIEW_DEBUG_DIR;
985
+ if (debugDir) {
986
+ mkdirSync(debugDir, { recursive: true });
987
+ const stamp = `${Date.now()}-t${req.tier}`;
988
+ writeFileSync(join4(debugDir, `${stamp}.json`), JSON.stringify({ args: buildArgs(req, model, "<system file>", req.fallbackModel), code: run.code, timedOut: run.timedOut ?? false, stdout: run.stdout, stderr: run.stderr }, null, 2));
989
+ }
990
+ return { parsed, fallbackUsed: !!req.fallbackModel && parsed.dominant === req.fallbackModel && model !== req.fallbackModel };
991
+ } finally {
992
+ rmSync(dir, { recursive: true, force: true });
993
+ }
994
+ }
995
+ async review(req) {
996
+ const usageByModel = {};
997
+ let calls = 0;
998
+ let model = this.resolved.get(req.model) ?? req.model;
999
+ if (!this.opts.allowFable && isFable(model)) {
1000
+ return { ok: false, reason: "error", detail: `${FABLE_NOT_ENABLED}: pass --allow-fable or set allowFable: true`, model, usageByModel, calls };
1001
+ }
1002
+ if (!this.opts.allowFable && req.fallbackModel !== void 0 && isFable(req.fallbackModel)) req = { ...req, fallbackModel: void 0 };
1003
+ const cached2 = this.cache[req.model];
1004
+ if (cached2 && cached2.used !== req.model) this.note(req.tier, req.model, cached2.used, `cached detection from ${cached2.checked.slice(0, 10)}: ${cached2.reason}`, false);
1005
+ for (let attempt = 0; attempt < 2; attempt++) {
1006
+ calls++;
1007
+ const { parsed } = await this.once(req, model);
1008
+ for (const [m, u] of Object.entries(parsed.usageByModel)) addUsage(usageByModel, m, u.usage, u.reportedCostUsd);
1009
+ const used = parsed.dominant ?? model;
1010
+ if (parsed.dominant && parsed.dominant !== model) {
1011
+ this.note(req.tier, req.model, parsed.dominant, `Claude Code ran ${parsed.dominant} when asked for ${model} (not available on this plan or overloaded)`, true);
1012
+ model = parsed.dominant;
1013
+ } else if (parsed.error && req.fallbackModel && model !== req.fallbackModel && MODEL_PROBLEM.test(parsed.error)) {
1014
+ this.note(req.tier, req.model, req.fallbackModel, `${model} failed: ${parsed.error.slice(0, 160)}`, true);
1015
+ model = req.fallbackModel;
1016
+ attempt--;
1017
+ if (calls > 3) break;
1018
+ continue;
1019
+ } else if (!this.cache[req.model] && parsed.dominant === req.model && this.opts.cachePath) {
1020
+ this.cache[req.model] = { used: req.model, checked: this.now().toISOString(), reason: "ran as requested" };
1021
+ writeModelCache(this.opts.cachePath, this.cache);
1022
+ }
1023
+ if (parsed.refusal) return { ok: false, reason: "refusal", detail: "refused", model: used, usageByModel, calls };
1024
+ if (parsed.error) return { ok: false, reason: "error", detail: parsed.error, model: used, usageByModel, calls };
1025
+ const response = parseTierResponse(parsed.structured);
1026
+ if (response) return { ok: true, response, model: used, usageByModel, calls };
1027
+ if (attempt === 1) return { ok: false, reason: "parse", detail: "no valid structured_output in the claude result", model: used, usageByModel, calls };
1028
+ }
1029
+ return { ok: false, reason: "error", detail: "claude call failed", model, usageByModel, calls };
1030
+ }
1031
+ /**
1032
+ * Explicit detection (`tierview models --probe`): one tiny call per model. Records which model actually ran.
1033
+ * Note: on some plans Fable bills usage credits, and `claude -p` does not ask before billing them.
1034
+ */
1035
+ async probe(models) {
1036
+ const out = [];
1037
+ for (const m of models) {
1038
+ if (!this.opts.allowFable && isFable(m)) {
1039
+ out.push({ model: m, used: null, error: `not probed: ${FABLE_NOT_ENABLED} (pass --allow-fable)` });
1040
+ continue;
1041
+ }
1042
+ const dir = mkdtempSync(join4(tmpdir(), "tierview-cc-"));
1043
+ try {
1044
+ const args = ["-p", "--output-format", "json", "--model", m, "--effort", "low", "--tools", "", "--no-session-persistence", "--disable-slash-commands", "--strict-mcp-config", "--safe-mode"];
1045
+ const run = await this.run(this.opts.bin, args, "Reply with the single word: ok", { cwd: dir, timeoutMs: 12e4 });
1046
+ const p = parseRun(run, m);
1047
+ const used = p.dominant;
1048
+ out.push({ model: m, used, error: p.error });
1049
+ if (used && this.opts.cachePath) {
1050
+ this.cache[m] = { used, checked: this.now().toISOString(), reason: used === m ? "probe: available" : `probe: Claude Code ran ${used}` };
1051
+ }
1052
+ } finally {
1053
+ rmSync(dir, { recursive: true, force: true });
1054
+ }
1055
+ }
1056
+ if (this.opts.cachePath) writeModelCache(this.opts.cachePath, this.cache);
1057
+ return out;
1058
+ }
1059
+ };
1060
+
1061
+ // src/output/terminal.ts
1062
+ var usd = (n2) => `$${n2 < 0.01 && n2 > 0 ? n2.toFixed(4) : n2.toFixed(2)}`;
1063
+ function table(rows, right = []) {
1064
+ const widths = rows[0].map((_, c) => Math.max(...rows.map((r) => (r[c] ?? "").length)));
1065
+ return rows.map(
1066
+ (r) => r.map((cell2, c) => right.includes(c) ? cell2.padStart(widths[c]) : c === r.length - 1 ? cell2 : cell2.padEnd(widths[c])).join(" ").trimEnd()
1067
+ );
1068
+ }
1069
+ function why(h) {
1070
+ const parts = h.reasons.filter((r) => r.weight !== 0 || r.signal !== "size").map((r) => r.weight ? `${r.signal} ${r.weight > 0 ? "+" : ""}${r.weight}` : `${r.signal}: ${r.detail}`);
1071
+ return parts.join(", ") || "no signals";
1072
+ }
1073
+ function renderDryRun(v) {
1074
+ const out = [];
1075
+ const { routed, plan } = v;
1076
+ out.push(`tierview dry run: ${routed.length} hunk(s) in ${new Set(routed.map((h) => h.file)).size} file(s). No model calls made.`, "");
1077
+ const order = [...routed].sort((a, b) => (a.tier === 0 ? 1 : 0) - (b.tier === 0 ? 1 : 0) || b.score - a.score || a.id.localeCompare(b.id));
1078
+ out.push("Routing (highest risk first)");
1079
+ out.push(
1080
+ ...table(
1081
+ [["hunk", "+/-", "score", "tier", "why"], ...order.map((h) => [h.id, `+${h.added}/-${h.deleted}`, String(h.score), h.tier === 0 ? "skip" : String(h.tier), h.tier === 0 ? h.reasons.at(-1)?.detail ?? "skipped" : why(h)])],
1082
+ [2]
1083
+ ).map((l) => ` ${l}`)
1084
+ );
1085
+ out.push("", plan.backend === "claude-code" ? "Estimated API-equivalent cost (claude-code backend; requests = claude calls; no caching discount, before escalations)" : "Estimated cost (no caching discount, before escalations)");
1086
+ const rows = [["tier", "model", "effort", "hunks", "requests", "input tok", "output tok", "cost"]];
1087
+ for (const t of plan.tiers) {
1088
+ rows.push([String(t.tier), t.model, t.effort, String(t.hunks), String(t.requests), String(t.input_tokens), String(t.output_tokens), usd(t.cost_usd)]);
1089
+ }
1090
+ out.push(...table(rows, [3, 4, 5, 6, 7]).map((l) => ` ${l}`));
1091
+ out.push("");
1092
+ out.push(` skipped hunks: ${plan.skipped_hunks}`);
1093
+ const cc = plan.backend === "claude-code";
1094
+ out.push(` estimated total: ${usd(plan.total_usd)}${cc ? " via Claude Code" : ""} (+ up to ${usd(plan.reserve_usd)} escalation allowance)`);
1095
+ if (cc) out.push(` direct API: ${usd(plan.total_direct_api_usd)} (without Claude Code's per-call overhead)`);
1096
+ out.push(` all-${plan.baseline.model}: ${usd(plan.baseline.cost_usd)}${cc ? ` via Claude Code, ${usd(plan.baseline.direct_api_cost_usd)} direct API` : ""} (the same estimated tokens at its rates)`);
1097
+ out.push(` estimated savings: ${plan.savings_pct}%`);
1098
+ if (v.maxCost !== null) out.push(` --max-cost: ${usd(v.maxCost)}${plan.total_usd + plan.reserve_usd > v.maxCost ? " (this plan would be degraded to fit)" : ""}`);
1099
+ if (v.warnings.length) out.push("", "Notes", ...v.warnings.map((w) => ` - ${w}`));
1100
+ return out.join("\n") + "\n";
1101
+ }
1102
+ var n = (x) => x.toLocaleString("en-US");
1103
+ function renderReceipt(r) {
1104
+ const apiEq = r.cost_basis === "api_equivalent";
1105
+ const out = [];
1106
+ out.push(apiEq ? `Receipt (claude-code backend: ${r.calls} claude call(s); cost is API-equivalent at list prices as of ${r.prices_as_of}, not what your plan bills)` : `Receipt (api backend: ${r.calls} request(s); list prices as of ${r.prices_as_of})`);
1107
+ const rows = [["tier", "model", "effort", "hunks", "+escalated", apiEq ? "calls" : "requests", "input", "cache write", "cache read", "output", apiEq ? "via Claude Code" : "cost", ...apiEq ? ["direct API"] : []]];
1108
+ for (const t of r.tiers) {
1109
+ rows.push([String(t.tier), t.model, t.effort, String(t.hunks), String(t.escalated_in), String(t.requests), n(t.input_tokens), n(t.cache_write_tokens), n(t.cache_read_tokens), n(t.output_tokens), usd(t.cost_usd), ...apiEq ? [usd(t.direct_api_cost_usd)] : []]);
1110
+ }
1111
+ out.push(...table(rows, [3, 4, 5, 6, 7, 8, 9, 10, 11]).map((l) => ` ${l}`));
1112
+ const tok = r.tiers.reduce((a, t) => a + t.input_tokens + t.cache_write_tokens + t.cache_read_tokens + t.output_tokens, 0);
1113
+ out.push("");
1114
+ out.push(` total: ${usd(r.total_cost_usd)}${apiEq ? ` via Claude Code, ${usd(r.total_direct_api_cost_usd)} direct API (without Claude Code's per-call overhead)` : ""} (${n(tok)} tokens)`);
1115
+ out.push(` all-${r.baseline.model}: ${usd(r.baseline.cost_usd)}${apiEq ? ` via Claude Code, ${usd(r.baseline.direct_api_cost_usd)} direct API` : ""} (the same tokens at its rates) -> ${r.savings_pct}% ${r.savings_pct >= 0 ? "less" : "more"}`);
1116
+ out.push(` skipped hunks: ${r.skipped_hunks} not reviewed: ${r.not_reviewed_hunks} wall time: ${(r.wall_ms / 1e3).toFixed(1)}s`);
1117
+ if (r.budget.max_cost_usd !== null) out.push(` --max-cost: ${usd(r.budget.max_cost_usd)}${r.budget.degraded ? " (plan degraded to fit)" : ""}`);
1118
+ for (const s of r.model_substitutions) out.push(` ${substitutionLine(s)}`);
1119
+ return out;
1120
+ }
1121
+ function renderReview(v) {
1122
+ const out = [];
1123
+ const reviewed = v.routing.filter((h) => h.tier !== 0).length;
1124
+ out.push(`tierview: ${v.findings.length} finding(s) in ${reviewed} reviewed hunk(s).`, "");
1125
+ for (const f of v.findings) {
1126
+ const lines2 = f.start_line === f.end_line ? `${f.start_line}` : `${f.start_line}-${f.end_line}`;
1127
+ out.push(`[${f.severity}] ${f.file}:${lines2}${f.side === "old" ? " (deleted line)" : ""} ${f.title}`);
1128
+ out.push(` ${f.category}, confidence ${f.confidence.toFixed(2)}, tier ${f.tier} ${f.model}${f.escalated_from.length ? ` (escalated from tier ${f.escalated_from.join(", ")})` : ""}`);
1129
+ if (f.explanation) out.push(` ${f.explanation}`);
1130
+ if (f.evidence) out.push(` > ${f.evidence}`);
1131
+ if (f.suggestion) out.push(` fix: ${f.suggestion}`);
1132
+ if (f.also_reported_by.length) out.push(` also reported by: ${f.also_reported_by.join(", ")}`);
1133
+ out.push("");
1134
+ }
1135
+ if (v.refuted.length) out.push(`${v.refuted.length} lower-tier finding(s) refuted by a higher tier (see --json).`, "");
1136
+ if (v.not_reviewed.length) {
1137
+ out.push("Not reviewed");
1138
+ for (const x of v.not_reviewed) out.push(` ${x.hunk_id}: ${x.reason}`);
1139
+ out.push("");
1140
+ }
1141
+ out.push(...renderReceipt(v.receipt));
1142
+ if (v.receipt.warnings.length) out.push("", "Notes", ...v.receipt.warnings.map((w) => ` - ${w}`));
1143
+ return out.join("\n") + "\n";
1144
+ }
1145
+
1146
+ // src/github/pr.ts
1147
+ var GithubError = class extends Error {
1148
+ };
1149
+ function parsePrUrl(url) {
1150
+ const m = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:[/?#].*)?$/.exec(url.trim());
1151
+ if (!m) throw new GithubError(`not a GitHub pull request URL: ${url} (expected https://github.com/<owner>/<repo>/pull/<number>)`);
1152
+ return { owner: m[1], repo: m[2], number: Number(m[3]) };
1153
+ }
1154
+ function apiBase() {
1155
+ return (process.env.GITHUB_API_URL ?? "https://api.github.com").replace(/\/$/, "");
1156
+ }
1157
+ function ghHeaders(token, accept = "application/vnd.github+json") {
1158
+ const h = { Accept: accept, "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "tierview" };
1159
+ if (token) h.Authorization = `Bearer ${token}`;
1160
+ return h;
1161
+ }
1162
+ async function ghRequest(f, url, token, accept, init = {}) {
1163
+ const res = await f(url, { ...init, headers: { ...ghHeaders(token, accept), ...init.body ? { "Content-Type": "application/json" } : {} } });
1164
+ const text = await res.text();
1165
+ if (!res.ok) {
1166
+ const hint = res.status === 404 ? " (not found; for a private repo set GITHUB_TOKEN)" : res.status === 401 || res.status === 403 ? " (check GITHUB_TOKEN and its permissions)" : "";
1167
+ throw new GithubError(`GitHub API ${init.method ?? "GET"} ${url.replace(apiBase(), "")} failed: HTTP ${res.status}${hint}`);
1168
+ }
1169
+ return text;
1170
+ }
1171
+ async function fetchPr(url, token, f = fetch) {
1172
+ const ref = parsePrUrl(url);
1173
+ const base = `${apiBase()}/repos/${ref.owner}/${ref.repo}/pulls/${ref.number}`;
1174
+ const meta = JSON.parse(await ghRequest(f, base, token));
1175
+ const diff = await ghRequest(f, base, token, "application/vnd.github.diff");
1176
+ if (!meta.head?.sha) throw new GithubError("GitHub returned a pull request without a head sha.");
1177
+ return { ref, title: meta.title ?? "", body: meta.body ?? "", headSha: meta.head.sha, diff };
1178
+ }
1179
+ async function prefetchFiles(ref, sha, paths, token, f = fetch, limit = 60) {
1180
+ const cache = /* @__PURE__ */ new Map();
1181
+ const todo = [...new Set(paths)].slice(0, limit);
1182
+ let next = 0;
1183
+ const worker = async () => {
1184
+ while (next < todo.length) {
1185
+ const p = todo[next++];
1186
+ const url = `${apiBase()}/repos/${ref.owner}/${ref.repo}/contents/${p.split("/").map(encodeURIComponent).join("/")}?ref=${sha}`;
1187
+ try {
1188
+ cache.set(p, await ghRequest(f, url, token, "application/vnd.github.raw+json"));
1189
+ } catch {
1190
+ cache.set(p, null);
1191
+ }
1192
+ }
1193
+ };
1194
+ await Promise.all([worker(), worker(), worker(), worker()]);
1195
+ return (p) => cache.get(p) ?? null;
1196
+ }
1197
+
1198
+ // src/github/comment.ts
1199
+ var MARKER = "<!-- tierview-review -->";
1200
+ var MAX_BODY = 6e4;
1201
+ var cell = (s) => s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
1202
+ var indent = (s) => s.replace(/\n/g, "\n ");
1203
+ function renderComment(r) {
1204
+ const rc = r.receipt;
1205
+ const apiEq = rc.cost_basis === "api_equivalent";
1206
+ const out = [MARKER, "## tierview review", ""];
1207
+ out.push(r.findings.length ? `**${r.findings.length} finding(s)**` : "**No findings.**", "");
1208
+ for (const f of r.findings) {
1209
+ const lines2 = f.start_line === f.end_line ? `${f.start_line}` : `${f.start_line}-${f.end_line}`;
1210
+ out.push(`- **${f.severity}** \`${f.file}:${lines2}\`${f.side === "old" ? " (deleted line)" : ""}: ${f.title}`);
1211
+ out.push(` <details><summary>details</summary>
1212
+
1213
+ ${f.category}, confidence ${f.confidence.toFixed(2)}, tier ${f.tier} (${f.model})
1214
+
1215
+ ${indent(f.explanation)}${f.suggestion ? `
1216
+
1217
+ Suggestion: ${indent(f.suggestion)}` : ""}
1218
+ </details>`);
1219
+ }
1220
+ if (r.findings.length) out.push("");
1221
+ if (r.not_reviewed.length) out.push(`${r.not_reviewed.length} hunk(s) not reviewed (${[...new Set(r.not_reviewed.map((x) => x.reason))].join("; ")}).`, "");
1222
+ out.push("### Cost receipt", "");
1223
+ out.push("| tier | model | effort | hunks | calls | cost |", "|---:|---|---|---:|---:|---:|");
1224
+ for (const t of rc.tiers) out.push(`| ${t.tier} | ${cell(t.model)} | ${t.effort} | ${t.hunks + t.escalated_in} | ${t.requests} | ${usd(t.cost_usd)} |`);
1225
+ out.push("");
1226
+ out.push(
1227
+ `**Total ${usd(rc.total_cost_usd)}** (${rc.calls} request(s), ${apiEq ? "API-equivalent" : "list prices"} as of ${rc.prices_as_of}). The same tokens at ${rc.baseline.model} rates would cost ${usd(rc.baseline.cost_usd)} (${rc.savings_pct}% ${rc.savings_pct >= 0 ? "less" : "more"}; calculated, not measured).`
1228
+ );
1229
+ if (rc.budget.max_cost_usd !== null) out.push(`Budget cap: ${usd(rc.budget.max_cost_usd)}${rc.budget.degraded ? " (plan degraded to fit)" : ""}.`);
1230
+ if (rc.warnings.length) out.push("", ...rc.warnings.map((w) => `> ${w}`));
1231
+ out.push("", "<sub>AI review can be wrong; treat findings as leads, not verdicts.</sub>");
1232
+ const body = out.join("\n");
1233
+ return body.length > MAX_BODY ? `${body.slice(0, MAX_BODY)}
1234
+
1235
+ _(truncated)_` : body;
1236
+ }
1237
+ async function upsertComment(ref, body, token, f = fetch) {
1238
+ const base = `${apiBase()}/repos/${ref.owner}/${ref.repo}`;
1239
+ let existing = null;
1240
+ for (let page = 1; page <= 10 && existing === null; page++) {
1241
+ const list = JSON.parse(await ghRequest(f, `${base}/issues/${ref.number}/comments?per_page=100&page=${page}`, token));
1242
+ existing = list.find((c) => c.body?.includes(MARKER))?.id ?? null;
1243
+ if (list.length < 100) break;
1244
+ }
1245
+ const payload = JSON.stringify({ body });
1246
+ const res = existing ? await ghRequest(f, `${base}/issues/comments/${existing}`, token, void 0, { method: "PATCH", body: payload }) : await ghRequest(f, `${base}/issues/${ref.number}/comments`, token, void 0, { method: "POST", body: payload });
1247
+ return { url: JSON.parse(res).html_url ?? "", updated: existing !== null };
1248
+ }
1249
+
1250
+ // src/llm/client.ts
1251
+ import Anthropic from "@anthropic-ai/sdk";
1252
+ import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
1253
+ var SdkErrors = {
1254
+ APIError: Anthropic.APIError,
1255
+ AuthenticationError: Anthropic.AuthenticationError,
1256
+ PermissionDeniedError: Anthropic.PermissionDeniedError,
1257
+ BadRequestError: Anthropic.BadRequestError,
1258
+ RateLimitError: Anthropic.RateLimitError,
1259
+ APIConnectionError: Anthropic.APIConnectionError,
1260
+ AnthropicError: Anthropic.AnthropicError
1261
+ };
1262
+ var toUsage = (u) => ({
1263
+ input_tokens: u.input_tokens ?? 0,
1264
+ cache_creation_input_tokens: u.cache_creation_input_tokens ?? 0,
1265
+ cache_read_input_tokens: u.cache_read_input_tokens ?? 0,
1266
+ output_tokens: u.output_tokens ?? 0
1267
+ });
1268
+ var ApiBackend = class {
1269
+ name = "api";
1270
+ concurrency;
1271
+ client;
1272
+ format = zodOutputFormat(TierResponse);
1273
+ constructor(opts = {}) {
1274
+ this.concurrency = opts.concurrency ?? 4;
1275
+ if (opts.client) {
1276
+ this.client = opts.client;
1277
+ return;
1278
+ }
1279
+ const apiKey = opts.apiKey ?? process.env.ANTHROPIC_API_KEY;
1280
+ if (!apiKey) throw new BackendSetupError("the api backend needs ANTHROPIC_API_KEY. Set it, or use --backend claude-code.");
1281
+ this.client = new Anthropic({ apiKey, maxRetries: opts.maxRetries ?? 2 });
1282
+ }
1283
+ substitutions() {
1284
+ return [];
1285
+ }
1286
+ params(req) {
1287
+ return {
1288
+ model: req.model,
1289
+ max_tokens: req.maxTokens,
1290
+ system: [
1291
+ { type: "text", text: req.system },
1292
+ req.cache ? { type: "text", text: req.shared, cache_control: { type: "ephemeral" } } : { type: "text", text: req.shared }
1293
+ ],
1294
+ messages: [{ role: "user", content: req.user }],
1295
+ output_config: { effort: req.effort, format: this.format }
1296
+ };
1297
+ }
1298
+ async review(req) {
1299
+ const usageByModel = {};
1300
+ let calls = 0;
1301
+ let model = req.model;
1302
+ for (let attempt = 0; attempt < 2; attempt++) {
1303
+ let msg;
1304
+ calls++;
1305
+ try {
1306
+ msg = await this.client.messages.parse(this.params(req));
1307
+ } catch (e) {
1308
+ if (e instanceof Anthropic.AuthenticationError || e instanceof Anthropic.PermissionDeniedError) {
1309
+ throw new BackendSetupError(`Anthropic API rejected the key (${e.status}): ${e.message}`);
1310
+ }
1311
+ if (e instanceof Anthropic.APIError) {
1312
+ return { ok: false, reason: "error", detail: `API error ${e.status ?? "connection"}: ${e.message}`, model, usageByModel, calls };
1313
+ }
1314
+ if (e instanceof Anthropic.AnthropicError && attempt === 0) continue;
1315
+ if (e instanceof Anthropic.AnthropicError) return { ok: false, reason: "parse", detail: e.message, model, usageByModel, calls };
1316
+ throw e;
1317
+ }
1318
+ model = msg.model;
1319
+ addUsage(usageByModel, msg.model, toUsage(msg.usage));
1320
+ if (msg.stop_reason === "refusal") {
1321
+ const why2 = [msg.stop_details?.category, msg.stop_details?.explanation].filter(Boolean).join(": ");
1322
+ return { ok: false, reason: "refusal", detail: why2 || "refused", model, usageByModel, calls };
1323
+ }
1324
+ const parsed = parseTierResponse(msg.parsed_output);
1325
+ if (parsed) return { ok: true, response: parsed, model, usageByModel, calls };
1326
+ if (attempt === 1) {
1327
+ return { ok: false, reason: "parse", detail: `no valid structured output (stop_reason ${msg.stop_reason})`, model, usageByModel, calls };
1328
+ }
1329
+ }
1330
+ return { ok: false, reason: "parse", detail: "no valid structured output", model, usageByModel, calls };
1331
+ }
1332
+ };
1333
+
1334
+ // src/output/sarif.ts
1335
+ var LEVEL = { critical: "error", high: "error", medium: "warning", low: "note", info: "note" };
1336
+ function result(f) {
1337
+ const text = [f.title, f.explanation, f.suggestion ? `Suggestion: ${f.suggestion}` : ""].filter(Boolean).join("\n\n");
1338
+ return {
1339
+ ruleId: f.category,
1340
+ level: LEVEL[f.severity],
1341
+ message: { text },
1342
+ locations: [
1343
+ {
1344
+ physicalLocation: {
1345
+ artifactLocation: { uri: f.file },
1346
+ region: { startLine: Math.max(1, f.start_line), endLine: Math.max(f.start_line, f.end_line, 1) }
1347
+ }
1348
+ }
1349
+ ],
1350
+ partialFingerprints: { tierviewFindingId: f.id },
1351
+ properties: { model: f.model, tier: f.tier, confidence: f.confidence, severity: f.severity, side: f.side }
1352
+ };
1353
+ }
1354
+ function reviewSarif(r, version = "0.0.1") {
1355
+ const rules = [...new Set(r.findings.map((f) => f.category))].sort().map((id) => ({ id, name: id, shortDescription: { text: `tierview: ${id}` } }));
1356
+ const doc = {
1357
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
1358
+ version: "2.1.0",
1359
+ runs: [
1360
+ {
1361
+ tool: { driver: { name: "tierview", version, informationUri: "https://github.com/moelsaka01/tierview", rules } },
1362
+ results: r.findings.map(result)
1363
+ }
1364
+ ]
1365
+ };
1366
+ return `${JSON.stringify(doc, null, 2)}
1367
+ `;
1368
+ }
1369
+
1370
+ // src/output/json.ts
1371
+ function dryRunJson(v) {
1372
+ const { routed, plan } = v;
1373
+ return JSON.stringify(
1374
+ {
1375
+ version: 1,
1376
+ dry_run: true,
1377
+ routing: routed.map((h) => ({ hunk_id: h.id, file_kind: h.fileKind, score: h.score, tier: h.tier, reasons: h.reasons })),
1378
+ estimate: { ...plan, prices_as_of: v.pricesAsOf },
1379
+ max_cost_usd: v.maxCost,
1380
+ warnings: v.warnings
1381
+ },
1382
+ null,
1383
+ 2
1384
+ ) + "\n";
1385
+ }
1386
+ function reviewJson(r) {
1387
+ return `${JSON.stringify(r, null, 2)}
1388
+ `;
1389
+ }
1390
+
1391
+ // src/budget.ts
1392
+ function worstCase(inputTokens, maxTokens, p) {
1393
+ return (inputTokens * p.input + maxTokens * p.output) / 1e6;
1394
+ }
1395
+ var Ledger = class {
1396
+ constructor(cap) {
1397
+ this.cap = cap;
1398
+ }
1399
+ cap;
1400
+ spent = 0;
1401
+ reserved = /* @__PURE__ */ new Map();
1402
+ next = 1;
1403
+ get outstanding() {
1404
+ let s = 0;
1405
+ for (const v of this.reserved.values()) s += v;
1406
+ return s;
1407
+ }
1408
+ /** Returns a ticket, or null when spent + reserved + amount would pass the cap. */
1409
+ reserve(amount) {
1410
+ if (this.cap !== null && this.spent + this.outstanding + amount > this.cap) return null;
1411
+ const t = this.next++;
1412
+ this.reserved.set(t, amount);
1413
+ return t;
1414
+ }
1415
+ settle(ticket, actual) {
1416
+ this.reserved.delete(ticket);
1417
+ this.spent += actual;
1418
+ }
1419
+ };
1420
+ function degradePlan(routed, cfg, prices, est, cap, backend) {
1421
+ const hunks = routed.map((h) => ({ ...h, reasons: [...h.reasons] }));
1422
+ const dropped = [];
1423
+ const moves = [];
1424
+ const fits = () => {
1425
+ const p = estimatePlan(hunks, cfg, prices, est, backend);
1426
+ return p.total_usd + p.reserve_usd <= cap;
1427
+ };
1428
+ while (!fits()) {
1429
+ const lowest = (t) => hunks.filter((h2) => h2.tier === t && !dropped.includes(h2.id)).sort((a, b) => a.score - b.score || a.id.localeCompare(b.id))[0];
1430
+ const h = lowest(3) ?? lowest(2) ?? lowest(1);
1431
+ if (!h) break;
1432
+ if (h.tier === 1) {
1433
+ dropped.push(h.id);
1434
+ h.tier = 0;
1435
+ h.reasons.push({ signal: "budget", weight: 0, detail: "dropped to fit --max-cost" });
1436
+ moves.push(`${h.id}: dropped (budget)`);
1437
+ } else {
1438
+ const to = h.tier === 3 && tiersMerged(cfg) ? 1 : h.tier - 1;
1439
+ h.reasons.push({ signal: "budget", weight: 0, detail: `moved from tier ${h.tier} to ${to} to fit --max-cost` });
1440
+ moves.push(`${h.id}: tier ${h.tier} -> ${to}`);
1441
+ h.tier = to;
1442
+ }
1443
+ }
1444
+ return { routed: hunks, dropped, degraded: moves.length > 0, moves };
1445
+ }
1446
+
1447
+ // src/llm/prompts.ts
1448
+ var COMMON = `You are a code reviewer inside tierview, a tool that reviews a diff one hunk at a time and routes each hunk to a reviewer tier by risk.
1449
+
1450
+ What to report
1451
+ - Only real defects that this change introduces or exposes: bugs, security problems, concurrency errors, data loss, performance regressions, broken API contracts, missing or wrong error handling, and weakened tests.
1452
+ - Do not report style, naming, formatting, or "consider adding a comment". Do not invent problems to look thorough; a clean hunk is a good answer.
1453
+ - Judge the change, not the whole file. A problem in unchanged code counts only when the change makes it reachable or worse.
1454
+
1455
+ How to read the input
1456
+ - Each hunk has an id such as "src/app.ts#2". Diff lines are printed as "<old> <new> <marker> <text>", where the marker is "+" (added), "-" (deleted) or " " (unchanged), and a blank number means the line does not exist on that side.
1457
+ - Context blocks, when present, show the new version of the file with new-file line numbers.
1458
+ - The shared context lists every hunk in the diff with its tier and risk score, so you can see what else changed.
1459
+
1460
+ How to answer
1461
+ - Return exactly one review per hunk id you were given, using the same ids, and no others.
1462
+ - verdict: "clean" when you have no findings, "issues" when you have at least one, "unsure" when you cannot judge without more context. "clean" with findings and "issues" without findings are contradictions; do not produce them.
1463
+ - confidence (0 to 1): your probability that the verdict and findings are right. Be honest; low confidence is useful, false certainty is not.
1464
+ - needs_escalation: true when a stronger reviewer with more context should look at this hunk; give the reason in escalation_reason, else "".
1465
+ - Findings: file is the hunk's file path. start_line and end_line are line numbers inside this hunk. side is "new" for added or unchanged lines (new-file numbers) and "old" for a problem on a deleted line (old-file numbers). title is at most 80 characters. explanation says what goes wrong and when. suggestion is a concrete fix, or "". evidence quotes the offending line exactly. confidence is per finding.
1466
+ - Severity: "critical" = exploitable security hole, data loss or corruption, or a crash on a common path; "high" = wrong behaviour users will hit; "medium" = wrong behaviour in edge cases or a clear performance regression; "low" = minor defect with limited impact; "info" = worth knowing, not a defect.
1467
+ - refuted_prior: ids of prior findings you checked and found wrong; [] when there are none.`;
1468
+ var TIER = {
1469
+ 1: `You are the Tier 1 reviewer: fast, for hunks that scored low risk. You see each hunk with only the diff's own three lines of context. When correctness depends on code you cannot see, do not guess: answer "unsure", set needs_escalation, and say what you would need to see. There are no prior findings at this tier, so refuted_prior is always [].`,
1470
+ 2: `You are the Tier 2 reviewer, for medium-risk hunks and for hunks the Tier 1 reviewer escalated. You see about 30 lines of the new file around each hunk. Some hunks carry prior findings from Tier 1 with ids: verify or refute each one. List the ids you refute in refuted_prior; re-report a finding you confirm in your own findings (fix its line numbers or severity if they were wrong). Escalate when the hunk needs the whole file or the enclosing function to judge.`,
1471
+ 3: `You are the Tier 3 reviewer, the final and most thorough tier, for high-risk hunks and for hunks the lower tiers escalated. You see the whole file when it is short, otherwise about 80 lines around the hunk and the start of the enclosing function. Some hunks carry prior findings from Tiers 1 and 2 with ids: verify or refute each one. List the ids you refute in refuted_prior; re-report a finding you confirm in your own findings. There is no tier above you, so needs_escalation is always false; express doubt through confidence instead.`
1472
+ };
1473
+ var TIER1_NO_CONTEXT = "You see each hunk with only the diff's own three lines of context.";
1474
+ var TIER1_WITH_CONTEXT = "You see each hunk with the same file context as Tier 3: the whole file when it is short, otherwise about 80 lines around the hunk and the start of the enclosing function.";
1475
+ function systemPrompt(tier, tier1Context = "none") {
1476
+ const text = tier === 1 && tier1Context === "tier3" ? TIER[1].replace(TIER1_NO_CONTEXT, TIER1_WITH_CONTEXT) : TIER[tier];
1477
+ return `${COMMON}
1478
+
1479
+ ${text}`;
1480
+ }
1481
+ function sharedContext(routed, pr = {}) {
1482
+ const out = ["# Change under review"];
1483
+ if (pr.title) out.push(`Title: ${pr.title.trim()}`);
1484
+ if (pr.body?.trim()) out.push("Description:", pr.body.trim());
1485
+ const files = /* @__PURE__ */ new Map();
1486
+ for (const h of [...routed].sort((a, b) => a.id.localeCompare(b.id))) {
1487
+ const f = files.get(h.file) ?? { added: 0, deleted: 0, status: h.status };
1488
+ f.added += h.added;
1489
+ f.deleted += h.deleted;
1490
+ files.set(h.file, f);
1491
+ }
1492
+ out.push("", "## Changed files (path, status, +added/-deleted)");
1493
+ for (const [path, f] of [...files.entries()].sort(([a], [b]) => a.localeCompare(b))) out.push(`${path} ${f.status} +${f.added}/-${f.deleted}`);
1494
+ out.push("", "## Hunk map (id, tier, risk score; tier 0 = skipped)");
1495
+ for (const h of [...routed].sort((a, b) => a.id.localeCompare(b.id))) out.push(`${h.id} tier=${h.tier} score=${h.score}`);
1496
+ return out.join("\n");
1497
+ }
1498
+ var num = (n2) => (n2 === void 0 ? "" : String(n2)).padStart(5);
1499
+ function numberedHunk(h) {
1500
+ const out = [`@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@ ${h.header}`.trimEnd()];
1501
+ for (const l of h.lines) out.push(`${num(l.oldNo)} ${num(l.newNo)} ${l.kind === "add" ? "+" : l.kind === "del" ? "-" : " "} ${l.text}`);
1502
+ return out.join("\n");
1503
+ }
1504
+ function hunkBlock(x) {
1505
+ const h = x.hunk;
1506
+ const out = [`### hunk ${h.id}`, `file: ${h.file}${h.oldFile ? ` (renamed from ${h.oldFile})` : ""}, status: ${h.status}, risk score: ${h.score}`, "<diff>", numberedHunk(h), "</diff>"];
1507
+ if (x.context) {
1508
+ out.push(`<context lines="${x.context.start}-${x.context.end}" kind="${x.context.kind}">`);
1509
+ x.context.lines.forEach((l, i) => out.push(`${num(x.context.start + i)} | ${l}`));
1510
+ out.push("</context>");
1511
+ }
1512
+ if (x.prior.length) {
1513
+ out.push("<prior_findings>");
1514
+ for (const f of x.prior) {
1515
+ out.push(
1516
+ JSON.stringify({ id: f.id, tier: f.tier, model: f.model, file: f.file, start_line: f.start_line, end_line: f.end_line, side: f.side, severity: f.severity, category: f.category, title: f.title, explanation: f.explanation, evidence: f.evidence, confidence: f.confidence })
1517
+ );
1518
+ }
1519
+ out.push("</prior_findings>");
1520
+ }
1521
+ return out.join("\n");
1522
+ }
1523
+ function userMessage(blocks, ids) {
1524
+ return [`Review these ${ids.length} hunk(s). Return exactly one review for each of these ids: ${ids.join(", ")}.`, "", ...blocks.flatMap((b) => [b, ""])].join("\n").trimEnd();
1525
+ }
1526
+
1527
+ // src/merge.ts
1528
+ import { createHash } from "crypto";
1529
+ var normTitle = (t) => t.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
1530
+ function findingId(f) {
1531
+ return createHash("sha1").update(`${f.file}|${f.start_line}|${f.end_line}|${f.category}|${normTitle(f.title)}`).digest("hex").slice(0, 12);
1532
+ }
1533
+ function toFinding(f, hunkId, model, tier, escalatedFrom) {
1534
+ return { ...f, id: findingId(f), hunk_id: hunkId, model, tier, escalated_from: [...escalatedFrom], also_reported_by: [] };
1535
+ }
1536
+ var tokens = (s) => new Set(s.toLowerCase().match(/[a-z0-9_]+/g) ?? []);
1537
+ function jaccard(a, b) {
1538
+ const A = tokens(a);
1539
+ const B = tokens(b);
1540
+ if (A.size === 0 && B.size === 0) return 1;
1541
+ let inter = 0;
1542
+ for (const t of A) if (B.has(t)) inter++;
1543
+ return inter / (A.size + B.size - inter);
1544
+ }
1545
+ var DUP = { lineSlack: 3, minJaccard: 0.5 };
1546
+ function isDuplicate(a, b) {
1547
+ if (a.file !== b.file || a.category !== b.category) return false;
1548
+ if (a.start_line > b.end_line + DUP.lineSlack || b.start_line > a.end_line + DUP.lineSlack) return false;
1549
+ return jaccard(`${a.title} ${a.explanation}`, `${b.title} ${b.explanation}`) >= DUP.minJaccard;
1550
+ }
1551
+ function rankFindings(fs) {
1552
+ return [...fs].sort(
1553
+ (a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || b.confidence - a.confidence || b.tier - a.tier || a.file.localeCompare(b.file) || a.start_line - b.start_line
1554
+ );
1555
+ }
1556
+ function mergeFindings(all, refutedBy) {
1557
+ const refuted = [];
1558
+ const live = [];
1559
+ for (const f of all) {
1560
+ const by = refutedBy.get(f.id);
1561
+ if (by !== void 0 && by > f.tier) refuted.push(f);
1562
+ else live.push(f);
1563
+ }
1564
+ const order = [...live].sort((a, b) => b.tier - a.tier || b.confidence - a.confidence);
1565
+ const kept = [];
1566
+ for (const f of order) {
1567
+ const dup = kept.find((k) => isDuplicate(k, f));
1568
+ if (dup) {
1569
+ const who = `${f.model} (tier ${f.tier})`;
1570
+ if (!dup.also_reported_by.includes(who) && (dup.model !== f.model || dup.tier !== f.tier)) dup.also_reported_by.push(who);
1571
+ continue;
1572
+ }
1573
+ kept.push({ ...f, also_reported_by: [...f.also_reported_by] });
1574
+ }
1575
+ return { findings: rankFindings(kept), refuted: rankFindings(refuted) };
1576
+ }
1577
+
1578
+ // src/receipt.ts
1579
+ var key2 = (t) => `tier${t}`;
1580
+ function buildReceipt(x) {
1581
+ const warnings = [...x.warnings];
1582
+ const tiers = [1, 2, 3].map((t) => {
1583
+ const recs = x.records.filter((r) => r.tier === t);
1584
+ const counts = /* @__PURE__ */ new Map();
1585
+ for (const r of recs) counts.set(r.model, (counts.get(r.model) ?? 0) + r.hunkIds.length);
1586
+ const model = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? x.cfg.models[key2(t)].model;
1587
+ const sum2 = { input: 0, cw: 0, cw1h: 0, cr: 0, out: 0 };
1588
+ for (const r of recs) {
1589
+ for (const u of Object.values(r.usageByModel)) {
1590
+ sum2.input += u.usage.input_tokens;
1591
+ sum2.cw += u.usage.cache_creation_input_tokens;
1592
+ sum2.cw1h += u.usage.cache_creation_1h_input_tokens ?? 0;
1593
+ sum2.cr += u.usage.cache_read_input_tokens;
1594
+ sum2.out += u.usage.output_tokens;
1595
+ }
1596
+ }
1597
+ return {
1598
+ tier: t,
1599
+ model,
1600
+ effort: x.cfg.models[key2(t)].effort,
1601
+ hunks: x.routed.filter((h) => h.tier === t).length,
1602
+ escalated_in: x.escalatedIn[t],
1603
+ requests: recs.reduce((a, r) => a + r.calls, 0),
1604
+ input_tokens: sum2.input,
1605
+ cache_write_tokens: sum2.cw,
1606
+ cache_read_tokens: sum2.cr,
1607
+ output_tokens: sum2.out,
1608
+ cache_write_1h_tokens: sum2.cw1h,
1609
+ cost_usd: recs.reduce((a, r) => a + r.cost, 0),
1610
+ direct_api_cost_usd: 0
1611
+ };
1612
+ });
1613
+ const overhead = x.backend === "claude-code" ? x.est.claude_code_overhead_tokens_per_call : 0;
1614
+ for (const t of tiers) t.direct_api_cost_usd = costViews([t], x.cfg.receipt.baseline.model, x.prices, x.backend, overhead).direct_api_usd;
1615
+ const unpriced = /* @__PURE__ */ new Set();
1616
+ for (const r of x.records) for (const m of costOfModels(r.usageByModel, x.prices).unpriced) unpriced.add(m);
1617
+ if (unpriced.size) warnings.push(`no price in config/prices.json for ${[...unpriced].join(", ")}; used the cost the backend reported.`);
1618
+ const v = costViews(tiers, x.cfg.receipt.baseline.model, x.prices, x.backend, overhead);
1619
+ const baseline = { model: x.cfg.receipt.baseline.model, method: "actual_tokens_at_baseline_prices", cost_usd: v.baseline_usd, direct_api_cost_usd: v.baseline_direct_api_usd };
1620
+ for (const t of tiers) {
1621
+ if (t.tier === 3 || x.merged && t.tier === 2) continue;
1622
+ const base = x.routed.filter((h) => h.tier === t.tier).length + t.escalated_in;
1623
+ const out = x.merged && t.tier === 1 ? x.escalatedIn[3] : x.escalatedIn[t.tier + 1];
1624
+ if (base > 0 && out / base > x.cfg.escalation.max_rate) {
1625
+ warnings.push(`calibration: ${out} of ${base} tier ${t.tier} hunk(s) escalated (${Math.round(out / base * 100)}% > ${Math.round(x.cfg.escalation.max_rate * 100)}%).`);
1626
+ }
1627
+ }
1628
+ return {
1629
+ backend: x.backend,
1630
+ cost_basis: x.backend === "claude-code" ? "api_equivalent" : "billed",
1631
+ calls: x.records.reduce((a, r) => a + r.calls, 0),
1632
+ model_substitutions: x.substitutions,
1633
+ tiers,
1634
+ skipped_hunks: x.skipped,
1635
+ not_reviewed_hunks: x.notReviewed,
1636
+ total_cost_usd: v.actual_usd,
1637
+ total_direct_api_cost_usd: v.direct_api_usd,
1638
+ baseline,
1639
+ savings_pct: savingsPct(v.actual_usd, baseline.cost_usd),
1640
+ budget: { max_cost_usd: x.maxCost, degraded: x.degraded },
1641
+ warnings,
1642
+ wall_ms: Math.round(x.wallMs),
1643
+ prices_as_of: x.prices.as_of
1644
+ };
1645
+ }
1646
+
1647
+ // src/tiers/context.ts
1648
+ var CONTEXT = { tier2Radius: 30, tier3WholeFileMax: 400, tier3Radius: 80, maxFunctionLookback: 200 };
1649
+ function splitLines(text) {
1650
+ const lines2 = text.replace(/\r\n/g, "\n").split("\n");
1651
+ if (lines2.length && lines2[lines2.length - 1] === "") lines2.pop();
1652
+ return lines2;
1653
+ }
1654
+ function span(h) {
1655
+ const start = Math.max(1, h.newStart);
1656
+ return [start, Math.max(start, h.newStart + h.newLines - 1)];
1657
+ }
1658
+ function enclosingStart(lines2, h) {
1659
+ const header = h.header.trim();
1660
+ if (!header) return null;
1661
+ const [start] = span(h);
1662
+ for (let i = Math.min(start - 1, lines2.length) - 1; i >= Math.max(0, start - 1 - CONTEXT.maxFunctionLookback); i--) {
1663
+ if (lines2[i].trim() === header) return i + 1;
1664
+ }
1665
+ return null;
1666
+ }
1667
+ function contextFor(h, tier, fileText, tier1Context = "none") {
1668
+ if (tier === 1) {
1669
+ if (tier1Context !== "tier3") return null;
1670
+ tier = 3;
1671
+ }
1672
+ if (fileText === null || h.status === "deleted") return null;
1673
+ const lines2 = splitLines(fileText);
1674
+ if (lines2.length === 0) return null;
1675
+ const [s, e] = span(h);
1676
+ let start;
1677
+ let end;
1678
+ let kind;
1679
+ if (tier === 2) {
1680
+ start = s - CONTEXT.tier2Radius;
1681
+ end = e + CONTEXT.tier2Radius;
1682
+ kind = `\xB1${CONTEXT.tier2Radius} lines`;
1683
+ } else if (lines2.length <= CONTEXT.tier3WholeFileMax) {
1684
+ start = 1;
1685
+ end = lines2.length;
1686
+ kind = "whole file";
1687
+ } else {
1688
+ start = s - CONTEXT.tier3Radius;
1689
+ end = e + CONTEXT.tier3Radius;
1690
+ kind = `\xB1${CONTEXT.tier3Radius} lines`;
1691
+ const fn = enclosingStart(lines2, h);
1692
+ if (fn !== null && fn < start) {
1693
+ start = fn;
1694
+ kind += " + enclosing function";
1695
+ }
1696
+ }
1697
+ start = Math.max(1, start);
1698
+ end = Math.min(lines2.length, end);
1699
+ if (start > end) return null;
1700
+ return { start, end, lines: lines2.slice(start - 1, end), kind };
1701
+ }
1702
+
1703
+ // src/tiers/escalate.ts
1704
+ function ruleFor(from, cfg) {
1705
+ const e = cfg.escalation;
1706
+ const sev = from === 1 ? e.tier1_verify_severity : e.tier2_verify_severity;
1707
+ if (!SEVERITY_ORDER.includes(sev)) throw new Error(`escalation.tier${from}_verify_severity must be one of ${SEVERITY_ORDER.join(", ")}`);
1708
+ return { minConfidence: from === 1 ? e.tier1_min_confidence : e.tier2_min_confidence, verifySeverity: sev };
1709
+ }
1710
+ var rank = (s) => SEVERITY_ORDER.indexOf(s);
1711
+ var atOrAbove = (s, threshold) => rank(s) <= rank(threshold);
1712
+ var clamp01 = (n2) => Number.isFinite(n2) ? Math.min(1, Math.max(0, n2)) : 0;
1713
+ var TITLE_MAX = 80;
1714
+ function sanitizeReview(r) {
1715
+ return {
1716
+ ...r,
1717
+ confidence: clamp01(r.confidence),
1718
+ findings: r.findings.map((f) => ({
1719
+ ...f,
1720
+ confidence: clamp01(f.confidence),
1721
+ title: f.title.length > TITLE_MAX ? `${f.title.slice(0, TITLE_MAX - 1)}\u2026` : f.title,
1722
+ start_line: Math.min(f.start_line, f.end_line),
1723
+ end_line: Math.max(f.start_line, f.end_line)
1724
+ }))
1725
+ };
1726
+ }
1727
+ function hunkRange(h, side, slack) {
1728
+ const start = side === "new" ? h.newStart : h.oldStart;
1729
+ const len = side === "new" ? h.newLines : h.oldLines;
1730
+ return [Math.max(0, start - slack), start + Math.max(len, 1) - 1 + slack];
1731
+ }
1732
+ var overlaps = (a, b) => a.side === b.side && a.start_line <= b.end_line && b.start_line <= a.end_line;
1733
+ function contradictions(r, h, slack = 3) {
1734
+ const out = [];
1735
+ if (r.verdict === "clean" && r.findings.length) out.push("E4a verdict clean but findings reported");
1736
+ if (r.verdict === "issues" && !r.findings.length) out.push("E4a verdict issues but no findings");
1737
+ for (const f of r.findings) {
1738
+ if (f.file !== h.file && f.file !== h.oldFile) {
1739
+ out.push(`E4b finding "${f.title}" cites ${f.file}, outside the hunk`);
1740
+ continue;
1741
+ }
1742
+ const [lo, hi] = hunkRange(h, f.side, slack);
1743
+ if (f.start_line < lo || f.end_line > hi) out.push(`E4b finding "${f.title}" cites lines ${f.start_line}-${f.end_line} (${f.side}), outside the hunk`);
1744
+ }
1745
+ for (let i = 0; i < r.findings.length; i++) {
1746
+ for (let j = i + 1; j < r.findings.length; j++) {
1747
+ const a = r.findings[i];
1748
+ const b = r.findings[j];
1749
+ if (overlaps(a, b) && Math.abs(rank(a.severity) - rank(b.severity)) >= 2) out.push(`E4c overlapping findings with severities ${a.severity} and ${b.severity}`);
1750
+ }
1751
+ }
1752
+ return out;
1753
+ }
1754
+ function decideEscalation(review, h, rule, failure) {
1755
+ if (!review) return { escalate: true, reasons: [`E5 ${failure ?? "missing from the response"}`] };
1756
+ const reasons = [];
1757
+ if (review.confidence < rule.minConfidence) reasons.push(`E1 confidence ${review.confidence.toFixed(2)} < ${rule.minConfidence}`);
1758
+ if (review.needs_escalation) reasons.push(`E2 model asked to escalate${review.escalation_reason ? `: ${review.escalation_reason}` : ""}`);
1759
+ const severe = review.findings.filter((f) => atOrAbove(f.severity, rule.verifySeverity));
1760
+ if (severe.length) reasons.push(`E3 ${severe.length} finding(s) at ${rule.verifySeverity} or above need confirmation`);
1761
+ reasons.push(...contradictions(review, h));
1762
+ return { escalate: reasons.length > 0, reasons };
1763
+ }
1764
+
1765
+ // src/pipeline.ts
1766
+ var key3 = (t) => `tier${t}`;
1767
+ async function mapLimit(items, limit, fn) {
1768
+ const out = new Array(items.length);
1769
+ let i = 0;
1770
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
1771
+ while (i < items.length) {
1772
+ const k = i++;
1773
+ out[k] = await fn(items[k]);
1774
+ }
1775
+ });
1776
+ await Promise.all(workers);
1777
+ return out;
1778
+ }
1779
+ async function runPipeline(x) {
1780
+ const now = x.now ?? (() => performance.now());
1781
+ const t0 = now();
1782
+ const { backend, prices, est } = x;
1783
+ const warnings = [...x.warnings ?? []];
1784
+ const collapsed = collapseTiers(x.cfg, x.routed);
1785
+ const cfg = collapsed.cfg;
1786
+ const merged = collapsed.merged;
1787
+ if (merged && collapsed.routed.some((h, i) => h.tier !== x.routed[i].tier)) {
1788
+ warnings.push(`Tier 2 and Tier 3 both run ${cfg.models.tier3.model}, so they ran as one tier at ${cfg.models.tier3.effort} effort.`);
1789
+ }
1790
+ let routed = collapsed.routed;
1791
+ let degraded = false;
1792
+ const budgetDropped = /* @__PURE__ */ new Set();
1793
+ if (x.maxCost !== null) {
1794
+ const d = degradePlan(routed, cfg, prices, est, x.maxCost, backend.name);
1795
+ routed = d.routed;
1796
+ degraded = d.degraded;
1797
+ for (const id of d.dropped) budgetDropped.add(id);
1798
+ if (d.degraded) warnings.push(`plan degraded to fit --max-cost: ${d.moves.join("; ")}.`);
1799
+ }
1800
+ const ledger = new Ledger(x.maxCost);
1801
+ const shared = sharedContext(routed, x.pr);
1802
+ const state = /* @__PURE__ */ new Map();
1803
+ for (const h of routed) if (h.tier !== 0) state.set(h.id, { hunk: h, path: [], findings: [] });
1804
+ const records = [];
1805
+ const refutedBy = /* @__PURE__ */ new Map();
1806
+ const escalatedIn = { 1: 0, 2: 0, 3: 0 };
1807
+ const fileCache = /* @__PURE__ */ new Map();
1808
+ const fileText = (p) => {
1809
+ if (!fileCache.has(p)) fileCache.set(p, x.files(p));
1810
+ return fileCache.get(p) ?? null;
1811
+ };
1812
+ let budgetStopped = false;
1813
+ let callsUsed = 0;
1814
+ const maxCalls = x.maxCalls ?? null;
1815
+ function planTier(tier, ids) {
1816
+ if (!ids.length) return { packs: 0, worst: 0 };
1817
+ const m = cfg.models[key3(tier)];
1818
+ const blocks = new Map(ids.map((id) => {
1819
+ const s = state.get(id);
1820
+ return [id, hunkBlock({ hunk: s.hunk, context: contextFor(s.hunk, tier, fileText(s.hunk.file), cfg.tier1_context), prior: [] })];
1821
+ }));
1822
+ const packs = packHunks(ids.map((id) => state.get(id).hunk), limitsFor(backend.name, tier, cfg, est), (h) => estimateTokens(blocks.get(h.id), est));
1823
+ const maxTokens = backend.name === "api" ? cfg.backend.api.max_tokens : 32e3;
1824
+ const prefix = estimateTokens(systemPrompt(tier, cfg.tier1_context) + shared, est);
1825
+ const worst = packs.reduce((a, p) => a + worstCase(prefix + p.reduce((b, h) => b + estimateTokens(blocks.get(h.id), est), 0), maxTokens, priceFor(m.model, prices)), 0);
1826
+ return { packs: packs.length, worst };
1827
+ }
1828
+ let heldCalls = 0;
1829
+ async function runTier(tier, ids, escalated) {
1830
+ const results = /* @__PURE__ */ new Map();
1831
+ if (!ids.length) return results;
1832
+ const m = cfg.models[key3(tier)];
1833
+ const system = systemPrompt(tier, cfg.tier1_context);
1834
+ const blocks = /* @__PURE__ */ new Map();
1835
+ for (const id of ids) {
1836
+ const s = state.get(id);
1837
+ blocks.set(id, hunkBlock({ hunk: s.hunk, context: contextFor(s.hunk, tier, fileText(s.hunk.file), cfg.tier1_context), prior: s.findings }));
1838
+ }
1839
+ const hunks = ids.map((id) => state.get(id).hunk);
1840
+ const onlyEscalated = (p) => p.every((h) => escalated.has(h.id)) ? 1 : 0;
1841
+ const packs = packHunks(hunks, limitsFor(backend.name, tier, cfg, est), (h) => estimateTokens(blocks.get(h.id), est)).sort((a, b) => onlyEscalated(a) - onlyEscalated(b));
1842
+ const prefixTokens = estimateTokens(system + shared, est);
1843
+ const cache = backend.name === "api" && packs.length >= 2 && prefixTokens >= 512;
1844
+ const maxTokens = backend.name === "api" ? cfg.backend.api.max_tokens : 32e3;
1845
+ const price = priceFor(m.model, prices);
1846
+ const send = async (pack) => {
1847
+ const packIds = pack.map((h) => h.id);
1848
+ const user = userMessage(packIds.map((id) => blocks.get(id)), packIds);
1849
+ if (maxCalls !== null && callsUsed >= maxCalls - heldCalls) {
1850
+ budgetStopped = true;
1851
+ for (const id of packIds) results.set(id, { review: null, failure: "budget" });
1852
+ return;
1853
+ }
1854
+ const ticket = ledger.reserve(worstCase(prefixTokens + estimateTokens(user, est), maxTokens, price));
1855
+ if (ticket === null) {
1856
+ budgetStopped = true;
1857
+ for (const id of packIds) results.set(id, { review: null, failure: "budget" });
1858
+ return;
1859
+ }
1860
+ const req = {
1861
+ tier,
1862
+ model: m.model,
1863
+ effort: m.effort,
1864
+ system,
1865
+ shared,
1866
+ user,
1867
+ hunkIds: packIds,
1868
+ cache,
1869
+ maxTokens,
1870
+ fallbackModel: backend.name === "claude-code" && tier === 3 ? cfg.models.tier2.model : void 0
1871
+ };
1872
+ let res;
1873
+ try {
1874
+ res = await backend.review(req);
1875
+ } catch (e) {
1876
+ ledger.settle(ticket, 0);
1877
+ throw e;
1878
+ }
1879
+ callsUsed += res.calls;
1880
+ const { cost } = costOfModels(res.usageByModel, prices);
1881
+ ledger.settle(ticket, cost);
1882
+ records.push({ tier, requested: m.model, model: res.model, hunkIds: packIds, usageByModel: res.usageByModel, calls: res.calls, cost, escalation: packIds.some((id) => escalated.has(id)) });
1883
+ if (!res.ok) warnings.push(`tier ${tier} call failed for ${packIds.join(", ")}: ${res.reason}: ${res.detail.slice(0, 300)}`);
1884
+ for (const id of packIds) {
1885
+ if (!res.ok) {
1886
+ results.set(id, { review: null, failure: `${res.reason}: ${res.detail}` });
1887
+ continue;
1888
+ }
1889
+ const raw = res.response.reviews.find((rv) => rv.hunk_id === id);
1890
+ const r = raw ? sanitizeReview(raw) : null;
1891
+ results.set(id, r ? { review: r } : { review: null, failure: "missing from the response" });
1892
+ if (r) {
1893
+ const s = state.get(id);
1894
+ for (const ref of r.refuted_prior) {
1895
+ const prev = refutedBy.get(ref);
1896
+ if (prev === void 0 || prev < tier) refutedBy.set(ref, tier);
1897
+ }
1898
+ s.findings.push(...r.findings.map((f) => toFinding(f, id, res.model, tier, s.path.filter((p) => p < tier))));
1899
+ }
1900
+ }
1901
+ };
1902
+ const [first, ...rest] = packs;
1903
+ if (cache && first) {
1904
+ await send(first);
1905
+ await mapLimit(rest, backend.concurrency, send);
1906
+ } else {
1907
+ await mapLimit(packs, backend.concurrency, send);
1908
+ }
1909
+ for (const id of ids) state.get(id).path.push(tier);
1910
+ return results;
1911
+ }
1912
+ const initial = (t) => routed.filter((h) => h.tier === t).map((h) => h.id);
1913
+ const failures = /* @__PURE__ */ new Map();
1914
+ const collect = (res) => {
1915
+ for (const [id, r] of res) if (!r.review) failures.set(id, r.failure ?? "failed");
1916
+ return res;
1917
+ };
1918
+ const higher = [planTier(2, initial(2)), planTier(3, initial(3))];
1919
+ heldCalls = higher.reduce((a, h) => a + h.packs, 0);
1920
+ const holdCost = higher.reduce((a, h) => a + h.worst, 0);
1921
+ const hold = holdCost > 0 ? ledger.reserve(holdCost) : null;
1922
+ const r1 = collect(await runTier(1, initial(1), /* @__PURE__ */ new Set()));
1923
+ heldCalls = 0;
1924
+ if (hold !== null) ledger.settle(hold, 0);
1925
+ const escalate = (res, from) => {
1926
+ const rule = ruleFor(from, cfg);
1927
+ const up = [];
1928
+ for (const [id, r] of res) {
1929
+ if (r.failure === "budget") continue;
1930
+ if (decideEscalation(r.review, state.get(id).hunk, rule, r.failure).escalate) up.push(id);
1931
+ }
1932
+ return up;
1933
+ };
1934
+ const up1 = escalate(r1, 1);
1935
+ for (const id of up1) failures.delete(id);
1936
+ let r2 = /* @__PURE__ */ new Map();
1937
+ let up2 = [];
1938
+ if (!merged) {
1939
+ escalatedIn[2] = up1.length;
1940
+ const t3 = planTier(3, initial(3));
1941
+ heldCalls = t3.packs;
1942
+ const hold3 = t3.worst > 0 ? ledger.reserve(t3.worst) : null;
1943
+ r2 = collect(await runTier(2, [...initial(2), ...up1], new Set(up1)));
1944
+ heldCalls = 0;
1945
+ if (hold3 !== null) ledger.settle(hold3, 0);
1946
+ up2 = escalate(r2, 2);
1947
+ for (const id of up2) failures.delete(id);
1948
+ }
1949
+ const into3 = merged ? up1 : up2;
1950
+ escalatedIn[3] = into3.length;
1951
+ const r3 = collect(await runTier(3, [...initial(3), ...into3], new Set(into3)));
1952
+ const reviewedOnce = /* @__PURE__ */ new Set();
1953
+ for (const res of [r1, r2, r3]) for (const [id, r] of res) if (r.review) reviewedOnce.add(id);
1954
+ const blocked = [];
1955
+ for (const [id, why2] of failures) {
1956
+ if (why2 === "budget" && reviewedOnce.has(id)) {
1957
+ blocked.push(id);
1958
+ continue;
1959
+ }
1960
+ state.get(id).notReviewed = why2 === "budget" ? "budget" : `tier ${state.get(id).path.at(-1)} ${why2}`;
1961
+ }
1962
+ if (blocked.length) warnings.push(`escalation not sent (budget or --max-calls), lower-tier review kept: ${blocked.sort().join(", ")}.`);
1963
+ const notReviewed = [
1964
+ ...[...budgetDropped].map((id) => ({ hunk_id: id, reason: "budget" })),
1965
+ ...[...state.values()].filter((s) => s.notReviewed).map((s) => ({ hunk_id: s.hunk.id, reason: s.notReviewed }))
1966
+ ].sort((a, b) => a.hunk_id.localeCompare(b.hunk_id));
1967
+ const { findings, refuted } = mergeFindings(
1968
+ [...state.values()].flatMap((s) => s.findings),
1969
+ refutedBy
1970
+ );
1971
+ const subs = [...(x.substitutions ?? []).filter((s) => records.some((r) => r.tier === s.tier)), ...backend.substitutions()];
1972
+ if (backend.name === "claude-code") {
1973
+ warnings.push("claude-code backend: costs are API-equivalent (tokens at API list prices), not what your Claude plan bills.");
1974
+ if (process.env.ANTHROPIC_API_KEY) warnings.push("ANTHROPIC_API_KEY is set, so Claude Code may bill that key instead of your plan.");
1975
+ if (records.some((r) => /fable/i.test(r.model))) warnings.push("Fable ran through Claude Code. On some plans Fable draws on usage credits, and `claude -p` does not ask first.");
1976
+ }
1977
+ const receipt = buildReceipt({
1978
+ backend: backend.name,
1979
+ cfg,
1980
+ prices,
1981
+ est,
1982
+ routed,
1983
+ records,
1984
+ escalatedIn,
1985
+ merged,
1986
+ skipped: routed.filter((h) => h.tier === 0).length - budgetDropped.size,
1987
+ notReviewed: notReviewed.length,
1988
+ maxCost: x.maxCost,
1989
+ degraded,
1990
+ substitutions: subs,
1991
+ warnings,
1992
+ wallMs: now() - t0
1993
+ });
1994
+ const review = {
1995
+ version: 1,
1996
+ findings,
1997
+ refuted,
1998
+ not_reviewed: notReviewed,
1999
+ routing: routed.map((h) => ({ hunk_id: h.id, score: h.score, tier: h.tier, reasons: h.reasons })),
2000
+ receipt
2001
+ };
2002
+ return { review, budgetExhausted: budgetDropped.size > 0 || budgetStopped };
2003
+ }
2004
+
2005
+ // src/tier0/route.ts
2006
+ import picomatch2 from "picomatch";
2007
+
2008
+ // src/tier0/signals.ts
2009
+ import picomatch from "picomatch";
2010
+ var glob = (patterns) => patterns.length ? picomatch(patterns, { dot: true }) : () => false;
2011
+ var regexes = (src) => src.map((s) => new RegExp(s, "i"));
2012
+ function compileRules(cfg) {
2013
+ return {
2014
+ cfg,
2015
+ kinds: {
2016
+ generated: glob(cfg.file_kinds.generated),
2017
+ docs: glob(cfg.file_kinds.docs),
2018
+ test: glob(cfg.file_kinds.test),
2019
+ config: glob(cfg.file_kinds.config)
2020
+ },
2021
+ categories: Object.entries(cfg.categories).map(([name, c]) => ({
2022
+ name,
2023
+ weight: c.weight,
2024
+ path: regexes(c.path),
2025
+ content: regexes(c.content),
2026
+ added: regexes(c.content_added),
2027
+ removed: regexes(c.content_removed),
2028
+ logic: c.logic
2029
+ }))
2030
+ };
2031
+ }
2032
+ function fileKindOf(path, rules) {
2033
+ if (rules.kinds.generated(path)) return "generated";
2034
+ if (rules.kinds.docs(path)) return "docs";
2035
+ if (rules.kinds.test(path)) return "test";
2036
+ if (rules.kinds.config(path)) return "config";
2037
+ return "source";
2038
+ }
2039
+ var lines = (h, kind) => h.lines.filter((l) => l.kind === kind).map((l) => l.text);
2040
+ var count = (xs, re) => xs.filter((x) => re.test(x)).length;
2041
+ var TEST_FN = /^\s*(it|test)\s*\(|\bdef test_|\bfunc Test\w+|@Test\b|#\[test\]|\b(it|test)\.each\b/;
2042
+ var ASSERT = /\bexpect\s*\(|\bassert\w*\b|\.should\b|\bt\.(Error|Fatal)f?\s*\(|\bself\.assert\w*/;
2043
+ var AWAIT = /\b(await|async)\b/;
2044
+ var COND = /^\s*(\}\s*)?(if|else\s+if|elif|while|for|unless)\b/;
2045
+ var BOUNDS = /\s(<=|>=|<|>)\s+[^;{]*?(\s[+-]\s|\b(size|len|length|count|end|limit|max|cap|capacity|bound)\w*)/i;
2046
+ var norm = (t) => t.replace(/\s+/g, "");
2047
+ var CMP = /<=|>=|===|!==|==|!=|=>|->|<<|>>|<|>/g;
2048
+ function comparisons(s) {
2049
+ return (s.match(CMP) ?? []).filter((t) => t !== "=>" && t !== "->" && t !== "<<" && t !== ">>").join(" ");
2050
+ }
2051
+ function brackets(s) {
2052
+ const out = [];
2053
+ for (const m of s.matchAll(/\[([^[\]]*)\]/g)) {
2054
+ const inner = m[1];
2055
+ if (/[+-]|len|length|size/i.test(inner)) out.push(inner.replace(/\s+/g, ""));
2056
+ }
2057
+ return out.join("|");
2058
+ }
2059
+ function modifiedPairs(h) {
2060
+ const pairs = [];
2061
+ let dels = [];
2062
+ let adds = [];
2063
+ const flush = () => {
2064
+ for (let i = 0; i < Math.min(dels.length, adds.length); i++) pairs.push([dels[i], adds[i]]);
2065
+ dels = [];
2066
+ adds = [];
2067
+ };
2068
+ let inAdds = false;
2069
+ for (const l of h.lines) {
2070
+ if (l.kind === "del") {
2071
+ if (inAdds) {
2072
+ flush();
2073
+ inAdds = false;
2074
+ }
2075
+ dels.push(l.text);
2076
+ } else if (l.kind === "add") {
2077
+ inAdds = true;
2078
+ adds.push(l.text);
2079
+ } else {
2080
+ flush();
2081
+ inAdds = false;
2082
+ }
2083
+ }
2084
+ flush();
2085
+ return pairs;
2086
+ }
2087
+ function logicFires(name, h, kind) {
2088
+ const added = lines(h, "add");
2089
+ const removed = lines(h, "del");
2090
+ switch (name) {
2091
+ case "deleted_test_file":
2092
+ return kind === "test" && h.status === "deleted" ? "test file deleted" : null;
2093
+ case "deleted_test_function": {
2094
+ if (kind !== "test") return null;
2095
+ const gone = count(removed, TEST_FN) - count(added, TEST_FN);
2096
+ return gone > 0 ? `${gone} test function(s) removed` : null;
2097
+ }
2098
+ case "test_assertion_count_dropped": {
2099
+ if (kind !== "test") return null;
2100
+ const drop = count(removed, ASSERT) - count(added, ASSERT);
2101
+ return drop > 0 ? `${drop} fewer assertion(s)` : null;
2102
+ }
2103
+ case "await_added_or_removed": {
2104
+ const d = count(added, AWAIT) - count(removed, AWAIT);
2105
+ return d !== 0 ? `async/await ${d > 0 ? "added" : "removed"}` : null;
2106
+ }
2107
+ case "comparison_operator_changed":
2108
+ return modifiedPairs(h).some(([a, b]) => comparisons(a) !== comparisons(b)) ? "comparison operator changed" : null;
2109
+ case "index_arithmetic_changed":
2110
+ return modifiedPairs(h).some(([a, b]) => brackets(a) !== brackets(b)) ? "index arithmetic changed" : null;
2111
+ case "condition_changed":
2112
+ return modifiedPairs(h).some(([a, b]) => COND.test(a) && COND.test(b) && norm(a) !== norm(b)) ? "condition changed" : null;
2113
+ case "bounds_check_added": {
2114
+ const hit = h.lines.find((l) => l.kind === "add" && BOUNDS.test(l.text));
2115
+ return hit ? `bounds check: ${hit.text.trim().slice(0, 50)}` : null;
2116
+ }
2117
+ default:
2118
+ return null;
2119
+ }
2120
+ }
2121
+ function firstMatch(res, texts) {
2122
+ for (const re of res) for (const t of texts) if (re.test(t)) return t.trim().slice(0, 60);
2123
+ return null;
2124
+ }
2125
+ function categorySignals(h, kind, rules) {
2126
+ const added = lines(h, "add");
2127
+ const removed = lines(h, "del");
2128
+ const both = [...added, ...removed];
2129
+ const paths = [h.file, ...h.oldFile ? [h.oldFile] : []];
2130
+ const out = [];
2131
+ for (const c of rules.categories) {
2132
+ let detail = null;
2133
+ const p = firstMatch(c.path, paths);
2134
+ if (p) detail = `path ${p}`;
2135
+ if (!detail) {
2136
+ const m = firstMatch(c.content, both) ?? firstMatch(c.added, added) ?? firstMatch(c.removed, removed);
2137
+ if (m) detail = `\`${m}\``;
2138
+ }
2139
+ if (!detail) {
2140
+ for (const l of c.logic) {
2141
+ const r = logicFires(l, h, kind);
2142
+ if (r) {
2143
+ detail = r;
2144
+ break;
2145
+ }
2146
+ }
2147
+ }
2148
+ if (detail) out.push({ signal: c.name, weight: c.weight, detail });
2149
+ }
2150
+ return out;
2151
+ }
2152
+ var COMMENT = /^\s*(\/\/|#(?!include|define|if|endif|pragma)|\/\*|\*\/?|--|<!--|"""|''')/;
2153
+ var IMPORT = /^\s*(import\s|from\s+\S+\s+import\s|(const|let|var)\s+.*=\s*require\(|#include\s|using\s|use\s+[\w:]+;)/;
2154
+ var ws = (s) => s.replace(/\s+/g, "");
2155
+ function isTrivialHunk(h) {
2156
+ const changed = h.lines.filter((l) => l.kind !== "ctx");
2157
+ if (changed.length === 0) return false;
2158
+ const added = lines(h, "add").map(ws).filter(Boolean).sort();
2159
+ const removed = lines(h, "del").map(ws).filter(Boolean).sort();
2160
+ if (added.length === removed.length && added.every((a2, i) => a2 === removed[i])) return true;
2161
+ const nonTrivial = changed.filter((l) => l.text.trim() !== "" && !COMMENT.test(l.text) && !IMPORT.test(l.text));
2162
+ if (nonTrivial.length > 0) return false;
2163
+ const imp = (kind) => h.lines.filter((l) => l.kind === kind && IMPORT.test(l.text)).map((l) => ws(l.text)).sort();
2164
+ const a = imp("add");
2165
+ const d = imp("del");
2166
+ return a.length === d.length && a.every((x, i) => x === d[i]);
2167
+ }
2168
+ function buildDiffContext(hunks, kinds, weakened, churn) {
2169
+ const files = /* @__PURE__ */ new Set();
2170
+ const dirs = /* @__PURE__ */ new Set();
2171
+ const perFile = /* @__PURE__ */ new Map();
2172
+ let sourceLines = 0;
2173
+ let testTouched = false;
2174
+ for (const h of hunks) {
2175
+ const kind = kinds.get(h.file) ?? "source";
2176
+ perFile.set(h.file, (perFile.get(h.file) ?? 0) + 1);
2177
+ if (kind === "generated") continue;
2178
+ files.add(h.file);
2179
+ dirs.add(h.file.includes("/") ? h.file.split("/")[0] : ".");
2180
+ if (kind === "source") sourceLines += h.added + h.deleted;
2181
+ if (kind === "test") testTouched = true;
2182
+ }
2183
+ return {
2184
+ files: files.size,
2185
+ topDirs: dirs.size,
2186
+ hunksPerFile: perFile,
2187
+ sourceLinesChanged: sourceLines,
2188
+ testFileTouched: testTouched,
2189
+ diffWeakensTests: weakened,
2190
+ churn
2191
+ };
2192
+ }
2193
+ function structureSignals(h, kind, ctx, cfg) {
2194
+ const s = cfg.structure;
2195
+ const out = [];
2196
+ const size = h.added + h.deleted;
2197
+ const bucket = s.size.find(([max]) => size <= max);
2198
+ if (bucket && bucket[1] !== 0) out.push({ signal: "size", weight: bucket[1], detail: `${size} changed lines` });
2199
+ const n2 = ctx.hunksPerFile.get(h.file) ?? 0;
2200
+ if (n2 > s.many_hunks_in_file.more_than) {
2201
+ out.push({ signal: "many_hunks_in_file", weight: s.many_hunks_in_file.points, detail: `${n2} hunks in this file` });
2202
+ }
2203
+ if (h.added === 0 && h.deleted > 0) out.push({ signal: "deletion_only", weight: s.deletion_only.points, detail: "only deletions" });
2204
+ const churn = ctx.churn?.[h.file];
2205
+ if (churn) {
2206
+ if (s.churn.enabled && churn.commits >= s.churn.min_commits) {
2207
+ out.push({ signal: "churn", weight: s.churn.points, detail: `${churn.commits} commits in ${s.churn.days}d` });
2208
+ }
2209
+ if (s.hotspot.enabled && churn.fixCommits >= s.hotspot.min_fix_commits) {
2210
+ out.push({ signal: "hotspot", weight: s.hotspot.points, detail: `${churn.fixCommits} fix commits in ${s.hotspot.days}d` });
2211
+ }
2212
+ }
2213
+ if (kind === "source") {
2214
+ if (ctx.files > s.scatter.max_files || ctx.topDirs > s.scatter.max_top_dirs) {
2215
+ out.push({ signal: "scatter", weight: s.scatter.points, detail: `${ctx.files} files, ${ctx.topDirs} top-level dirs` });
2216
+ }
2217
+ if (ctx.diffWeakensTests) out.push({ signal: "diff_weakens_tests", weight: s.diff_weakens_tests.points, detail: "tests weakened elsewhere in this diff" });
2218
+ if (ctx.sourceLinesChanged > s.no_tests_changed.min_source_lines && !ctx.testFileTouched) {
2219
+ out.push({ signal: "no_tests_changed", weight: s.no_tests_changed.points, detail: `${ctx.sourceLinesChanged} source lines, no test file` });
2220
+ }
2221
+ }
2222
+ return out;
2223
+ }
2224
+
2225
+ // src/tier0/score.ts
2226
+ var sum = (rs) => rs.reduce((a, r) => a + r.weight, 0);
2227
+ var clamp = (n2) => Math.max(0, Math.min(100, n2));
2228
+ function scoreHunk(h, kind, ctx, rules, cats) {
2229
+ const cfg = rules.cfg;
2230
+ if (kind === "generated") {
2231
+ return { ...h, fileKind: kind, score: 0, reasons: [{ signal: "generated", weight: 0, detail: "generated or vendored file, never sent to a model" }] };
2232
+ }
2233
+ const reasons = [...cats ?? categorySignals(h, kind, rules), ...structureSignals(h, kind, ctx, cfg)];
2234
+ let score = sum(reasons);
2235
+ if (kind === "test" && !reasons.some((r) => r.signal === "tests_weakened" || r.signal === "assertions_removed")) {
2236
+ const r = cfg.reductions.test_file_without_test_signal;
2237
+ reasons.push({ signal: "test_file", weight: -r, detail: "test file with no test-weakening signal" });
2238
+ score -= r;
2239
+ }
2240
+ const cap = cfg.reductions.docs_or_trivial_cap;
2241
+ const capReason = kind === "docs" ? "documentation file" : isTrivialHunk(h) ? "only comments, whitespace or import reordering" : null;
2242
+ if (capReason && score > cap) {
2243
+ reasons.push({ signal: "cap", weight: cap - score, detail: `${capReason}: score capped at ${cap}` });
2244
+ score = cap;
2245
+ }
2246
+ return { ...h, fileKind: kind, score: clamp(score), reasons };
2247
+ }
2248
+ function scoreHunks(hunks, rules, churn = null) {
2249
+ const kinds = /* @__PURE__ */ new Map();
2250
+ for (const h of hunks) if (!kinds.has(h.file)) kinds.set(h.file, fileKindOf(h.file, rules));
2251
+ const cats = /* @__PURE__ */ new Map();
2252
+ let weakened = false;
2253
+ for (const h of hunks) {
2254
+ const kind = kinds.get(h.file);
2255
+ if (kind === "generated") continue;
2256
+ const c = categorySignals(h, kind, rules);
2257
+ cats.set(h, c);
2258
+ if (c.some((r) => r.signal === "tests_weakened")) weakened = true;
2259
+ }
2260
+ const ctx = buildDiffContext(hunks, kinds, weakened, churn);
2261
+ return hunks.map((h) => scoreHunk(h, kinds.get(h.file), ctx, rules, cats.get(h)));
2262
+ }
2263
+
2264
+ // src/tier0/route.ts
2265
+ function tierForScore(score, cfg) {
2266
+ return score >= cfg.thresholds.tier3 ? 3 : score >= cfg.thresholds.tier2 ? 2 : 1;
2267
+ }
2268
+ function routeHunks(scored, cfg) {
2269
+ const ignore = cfg.ignore.length ? picomatch2(cfg.ignore, { dot: true }) : () => false;
2270
+ const rules = cfg.rules.map((r) => ({ rule: r, match: picomatch2(r.paths, { dot: true }) }));
2271
+ return scored.map((h) => {
2272
+ if (h.fileKind === "generated") return { ...h, tier: 0 };
2273
+ if (ignore(h.file)) {
2274
+ return { ...h, tier: 0, reasons: [...h.reasons, { signal: "ignore", weight: 0, detail: "matches an `ignore` glob" }] };
2275
+ }
2276
+ const reasons = [...h.reasons];
2277
+ let score = h.score;
2278
+ const matched = rules.filter((r) => r.match(h.file));
2279
+ for (const { rule } of matched) {
2280
+ if (rule.add) {
2281
+ score += rule.add;
2282
+ reasons.push({ signal: "rule", weight: rule.add, detail: `rule ${rule.paths.join(", ")}` });
2283
+ }
2284
+ }
2285
+ score = Math.max(0, Math.min(100, score));
2286
+ let tier = tierForScore(score, cfg);
2287
+ for (const { rule } of matched) {
2288
+ if (rule.min_tier && tier < rule.min_tier) {
2289
+ tier = rule.min_tier;
2290
+ reasons.push({ signal: "rule", weight: 0, detail: `min_tier ${rule.min_tier} (${rule.paths.join(", ")})` });
2291
+ }
2292
+ if (rule.max_tier && tier > rule.max_tier) {
2293
+ tier = rule.max_tier;
2294
+ reasons.push({ signal: "rule", weight: 0, detail: `max_tier ${rule.max_tier} (${rule.paths.join(", ")})` });
2295
+ }
2296
+ }
2297
+ return { ...h, score, tier, reasons };
2298
+ });
2299
+ }
2300
+ function routeDiff(hunks, cfg, churn = null, rules) {
2301
+ const compiled = rules ?? compileRules(cfg);
2302
+ return routeHunks(scoreHunks(hunks, compiled, cfg.structure.churn.enabled || cfg.structure.hotspot.enabled ? churn : null), cfg);
2303
+ }
2304
+
2305
+ // src/cli.ts
2306
+ function pickBackend(opt, cfg) {
2307
+ const b = opt ?? cfg.backend.default;
2308
+ if (b !== "api" && b !== "claude-code") throw new ConfigError(`--backend must be "claude-code" or "api", got "${b}"`);
2309
+ return b;
2310
+ }
2311
+ async function makeBackend(name, cfg, allowFable = false) {
2312
+ if (name === "api") return new ApiBackend({ concurrency: cfg.backend.api.concurrency });
2313
+ const bin = resolveClaudeBinary({ configured: cfg.backend.claude_code.binary });
2314
+ if (!bin) {
2315
+ throw new BackendSetupError(
2316
+ "the claude-code backend needs the official Claude Code CLI. Install it (https://code.claude.com), put `claude` on PATH or set TIERVIEW_CLAUDE_BIN, or use --backend api."
2317
+ );
2318
+ }
2319
+ await verifyClaudeBinary(bin);
2320
+ return new ClaudeCodeBackend({ bin, timeoutMs: cfg.backend.claude_code.timeout_s * 1e3, cachePath: defaultCachePath(), allowFable });
2321
+ }
2322
+ async function runReview(opts, io) {
2323
+ try {
2324
+ if (opts.maxCost !== void 0 && !(opts.maxCost > 0)) {
2325
+ io.err("tierview: --max-cost must be a positive number of USD.\n");
2326
+ return EXIT.USAGE;
2327
+ }
2328
+ if (opts.maxCalls !== void 0 && !(Number.isInteger(opts.maxCalls) && opts.maxCalls > 0)) {
2329
+ io.err("tierview: --max-calls must be a positive integer.\n");
2330
+ return EXIT.USAGE;
2331
+ }
2332
+ if (opts.failOn !== void 0 && !SEVERITY_ORDER.includes(opts.failOn)) {
2333
+ io.err(`tierview: --fail-on must be one of ${SEVERITY_ORDER.join(", ")}.
2334
+ `);
2335
+ return EXIT.USAGE;
2336
+ }
2337
+ const loaded = loadConfig({ cwd: io.cwd, path: opts.config });
2338
+ const backendName = io.backend?.name ?? pickBackend(opts.backend, loaded);
2339
+ const allowFable = !!opts.allowFable || loaded.allowFable;
2340
+ const { cfg, substitutions } = applyFablePolicy(loaded, backendName, allowFable);
2341
+ const diffOpts = { base: opts.base, head: opts.head, staged: opts.staged, includeUntracked: opts.includeUntracked, cwd: io.cwd };
2342
+ const supplied = io.diff ?? (opts.diffFile !== void 0 ? readFileSync6(opts.diffFile, "utf8") : void 0);
2343
+ const diffText = supplied ?? getDiff(diffOpts);
2344
+ const files = parseDiffFiles(diffText);
2345
+ const hunks = files.flatMap((f) => f.hunks);
2346
+ if (files.length === 0) {
2347
+ io.out("No changes to review.\n");
2348
+ return EXIT.OK;
2349
+ }
2350
+ const warnings = [];
2351
+ let churn = null;
2352
+ if (cfg.structure.churn.enabled || cfg.structure.hotspot.enabled) {
2353
+ if (supplied === void 0 && !isShallow(io.cwd)) {
2354
+ churn = fileChurn([...new Set(hunks.map((h) => h.file))], Math.max(cfg.structure.churn.days, cfg.structure.hotspot.days), cfg.structure.hotspot.pattern, io.cwd);
2355
+ } else {
2356
+ warnings.push("git history unavailable (shallow clone or no checkout): churn and hotspot signals contributed 0.");
2357
+ }
2358
+ }
2359
+ const noHunks = files.filter((f) => f.hunks.length === 0);
2360
+ if (noHunks.length) warnings.push(`${noHunks.length} file(s) have no reviewable hunks (binary or pure rename): ${noHunks.map((f) => f.path).join(", ")}.`);
2361
+ const routed = routeDiff(hunks, cfg, churn);
2362
+ const est = loadEstimates();
2363
+ const prices = loadPrices();
2364
+ if (!est.calibrated) warnings.push("token and output estimates are uncalibrated placeholders (config/estimates.json); treat costs as rough.");
2365
+ const maxCost = opts.maxCost ?? cfg.budget.max_cost_usd;
2366
+ const plannedSubs = substitutions.filter((s) => routed.some((h) => h.tier === s.tier));
2367
+ if (opts.dryRun) {
2368
+ const plan = estimatePlan(routed, cfg, prices, est, backendName);
2369
+ const subNotes = plannedSubs.map((s) => `Tier ${s.tier} will run on ${displayName(s.used)} (${FABLE_NOT_ENABLED}; --allow-fable to use ${displayName(s.requested)}).`);
2370
+ if (tiersMerged(cfg) && routed.some((h) => h.tier === 2)) subNotes.push(`Tier 2 and Tier 3 both run ${displayName(cfg.models.tier3.model)}: Tier 2 hunks join the Tier 3 call (one call at the higher effort).`);
2371
+ const view = { routed, plan, warnings: [...subNotes, ...warnings, `prices as of ${prices.as_of}.`], maxCost };
2372
+ io.out(opts.json ? dryRunJson({ ...view, pricesAsOf: prices.as_of }) : renderDryRun(view));
2373
+ return EXIT.OK;
2374
+ }
2375
+ const backend = io.backend ?? await makeBackend(backendName, cfg, allowFable);
2376
+ if (backendName === "claude-code" && allowFable && usesFable(cfg)) io.err(FABLE_WARNING);
2377
+ if (supplied !== void 0 && !io.files) warnings.push("diff supplied without a checkout: Tier 2 and 3 saw no surrounding file context.");
2378
+ const fileSrc = io.files ?? (supplied === void 0 ? fileSource(diffOpts) : () => null);
2379
+ const { review, budgetExhausted } = await runPipeline({ routed, cfg, backend, files: fileSrc, prices, est, maxCost, maxCalls: opts.maxCalls ?? null, substitutions, warnings, pr: io.pr });
2380
+ io.out(opts.json ? reviewJson(review) : renderReview(review));
2381
+ if (opts.sarif) writeFileSync2(opts.sarif, reviewSarif(review));
2382
+ await io.onReview?.(review);
2383
+ if (opts.failOn && review.findings.some((f) => atOrAbove(f.severity, opts.failOn))) return EXIT.FINDINGS;
2384
+ if (budgetExhausted) return EXIT.BUDGET;
2385
+ return EXIT.OK;
2386
+ } catch (e) {
2387
+ if (e instanceof ConfigError || e instanceof PricesError || e instanceof BackendSetupError || e instanceof GithubError) {
2388
+ io.err(`tierview: ${e.message}
2389
+ `);
2390
+ return EXIT.USAGE;
2391
+ }
2392
+ const msg = e.stderr?.trim() || e.message;
2393
+ io.err(`tierview: ${msg}
2394
+ `);
2395
+ return EXIT.USAGE;
2396
+ }
2397
+ }
2398
+ async function runModels(opts, io) {
2399
+ try {
2400
+ const cfg = loadConfig({ cwd: io.cwd, path: opts.config });
2401
+ const allowFable = !!opts.allowFable || cfg.allowFable;
2402
+ const models = [.../* @__PURE__ */ new Set([cfg.models.tier1.model, cfg.models.tier2.model, cfg.models.tier3.model])];
2403
+ const cachePath = defaultCachePath();
2404
+ if (opts.probe) {
2405
+ const bin = resolveClaudeBinary({ configured: cfg.backend.claude_code.binary });
2406
+ if (!bin) throw new BackendSetupError("Claude Code CLI not found (see `tierview review --help`).");
2407
+ const probed = models.filter((m) => allowFable || !isFable(m));
2408
+ io.err(`${await verifyClaudeBinary(bin)}: probing ${probed.length} model(s), one tiny call each.
2409
+ `);
2410
+ if (allowFable && probed.some(isFable)) io.err(FABLE_WARNING);
2411
+ const cc = new ClaudeCodeBackend({ bin, cachePath, allowFable });
2412
+ for (const r of await cc.probe(models)) {
2413
+ io.out(`${r.model}: ${r.used === r.model ? "available" : r.used ? `ran ${r.used} instead` : `unavailable (${r.error ?? "no usage reported"})`}
2414
+ `);
2415
+ }
2416
+ return EXIT.OK;
2417
+ }
2418
+ const cache = readModelCache(cachePath);
2419
+ for (const m of models) {
2420
+ if (!allowFable && isFable(m)) {
2421
+ io.out(`${m}: ${FABLE_NOT_ENABLED} (pass --allow-fable or set allowFable: true; Tier 3 runs on ${displayName(cfg.models.tier2.model)})
2422
+ `);
2423
+ continue;
2424
+ }
2425
+ const c = cache[m];
2426
+ io.out(`${m}: ${c ? `${c.used === m ? "available" : `runs as ${c.used}`} (checked ${c.checked.slice(0, 10)}: ${c.reason})` : "not checked yet (run `tierview models --probe`, or a review will detect it)"}
2427
+ `);
2428
+ }
2429
+ return EXIT.OK;
2430
+ } catch (e) {
2431
+ io.err(`tierview: ${e.message}
2432
+ `);
2433
+ return EXIT.USAGE;
2434
+ }
2435
+ }
2436
+ async function runPr(url, opts, io, f) {
2437
+ try {
2438
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
2439
+ if (opts.comment && !token) {
2440
+ io.err("tierview: --comment needs GITHUB_TOKEN (a token with pull-requests: write).\n");
2441
+ return EXIT.USAGE;
2442
+ }
2443
+ if (opts.comment && opts.dryRun) {
2444
+ io.err("tierview: --comment has nothing to post on a dry run.\n");
2445
+ return EXIT.USAGE;
2446
+ }
2447
+ const pr = await fetchPr(url, token, f);
2448
+ const paths = parseDiffFiles(pr.diff).filter((x) => x.hunks.length > 0).map((x) => x.path);
2449
+ const files = opts.dryRun ? void 0 : await prefetchFiles(pr.ref, pr.headSha, paths, token, f);
2450
+ const onReview = async (review) => {
2451
+ if (!opts.comment) return;
2452
+ const r = await upsertComment(pr.ref, renderComment(review), token, f);
2453
+ io.err(`tierview: ${r.updated ? "updated" : "posted"} the PR comment ${r.url}
2454
+ `);
2455
+ };
2456
+ return await runReview(opts, { ...io, diff: pr.diff, files, pr: { title: pr.title, body: pr.body }, onReview });
2457
+ } catch (e) {
2458
+ io.err(`tierview: ${e.message}
2459
+ `);
2460
+ return EXIT.USAGE;
2461
+ }
2462
+ }
2463
+ var stdio = { out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s) };
2464
+ function addSharedOptions(cmd) {
2465
+ return cmd.option("--dry-run", "show routing and estimated cost; make zero model calls").option("--backend <name>", "claude-code (the official claude CLI, default) or api (ANTHROPIC_API_KEY)").option("--max-cost <usd>", "hard budget cap for this run, in USD (API-equivalent on claude-code)", Number.parseFloat).option("--max-calls <n>", "hard cap on model calls for this run (useful within plan limits)", (v) => Number(v)).option("--json", "print the review as JSON").option("--sarif <file>", "write SARIF 2.1.0 to a file").option("--fail-on <severity>", "exit 1 if a finding is at or above this severity").option("--config <file>", "path to a config file (default: .tierview.yml in the current directory)").option("--allow-fable", "claude-code backend: allow Fable 5.2 (may use paid extra usage on some plans)");
2466
+ }
2467
+ function buildProgram() {
2468
+ const program = new Command().name("tierview").description("AI code review that escalates through Claude model tiers and prints a cost receipt.").version("0.1.0");
2469
+ addSharedOptions(
2470
+ program.command("review").description("review a local git diff").option("--base <ref>", "base ref", "HEAD").option("--head <ref>", "head ref (default: the working tree)").option("--staged", "review staged changes only").option("--include-untracked", "also review new files git does not track yet (working tree only)").option("--diff-file <path>", "review a saved unified diff instead of running git (no file context)")
2471
+ ).action(async (opts) => {
2472
+ process.exitCode = await runReview(opts, stdio);
2473
+ });
2474
+ program.command("models").description("show which tier models Claude Code runs on your plan").option("--probe", "check now with one tiny claude call per model").option("--config <file>", "path to a config file").option("--allow-fable", "also probe Fable 5.2 (may use paid extra usage on some plans)").action(async (opts) => {
2475
+ process.exitCode = await runModels(opts, stdio);
2476
+ });
2477
+ addSharedOptions(
2478
+ program.command("pr").description("review a GitHub pull request").argument("<url>", "pull request URL").option("--comment", "post the review as a PR comment")
2479
+ ).action(async (url, opts) => {
2480
+ process.exitCode = await runPr(url, opts, stdio);
2481
+ });
2482
+ return program;
2483
+ }
2484
+
2485
+ // src/bin.ts
2486
+ buildProgram().parseAsync(process.argv);