costlint 0.3.0__py3-none-any.whl
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.
- costlint/__init__.py +3 -0
- costlint/__main__.py +6 -0
- costlint/cli.py +337 -0
- costlint/estimator.py +193 -0
- costlint/models.py +82 -0
- costlint/patcher.py +326 -0
- costlint/scanner.py +863 -0
- costlint-0.3.0.dist-info/METADATA +282 -0
- costlint-0.3.0.dist-info/RECORD +13 -0
- costlint-0.3.0.dist-info/WHEEL +5 -0
- costlint-0.3.0.dist-info/entry_points.txt +2 -0
- costlint-0.3.0.dist-info/licenses/LICENSE +21 -0
- costlint-0.3.0.dist-info/top_level.txt +1 -0
costlint/__init__.py
ADDED
costlint/__main__.py
ADDED
costlint/cli.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""CLI interface for CostLint scanning and reporting."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .estimator import DEFAULT_ASSUMPTIONS, estimate_costs, load_assumptions
|
|
9
|
+
from .models import ScanReport
|
|
10
|
+
from .patcher import generate_patch
|
|
11
|
+
from .scanner import iter_python_files, scan_path
|
|
12
|
+
|
|
13
|
+
ILLUSTRATIVE_NOTE = "Illustrative estimate based on generic token prices; see docs/COST_MODEL.md."
|
|
14
|
+
TABLE_WIDTH = 100
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _positive_int(value: str) -> int:
|
|
18
|
+
number = int(value)
|
|
19
|
+
if number < 1:
|
|
20
|
+
raise argparse.ArgumentTypeError("must be >= 1")
|
|
21
|
+
return number
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
prog="costlint",
|
|
27
|
+
description="CostLint - Pre-merge AI token cost & loop safety linter",
|
|
28
|
+
)
|
|
29
|
+
subparsers = parser.add_subparsers(dest="command", help="Command to run")
|
|
30
|
+
|
|
31
|
+
scan_parser = subparsers.add_parser("scan", help="Scan Python files for cost leaks")
|
|
32
|
+
scan_parser.add_argument(
|
|
33
|
+
"target_paths",
|
|
34
|
+
nargs="*",
|
|
35
|
+
help="Python file(s) or directory/directories to scan",
|
|
36
|
+
)
|
|
37
|
+
scan_parser.add_argument(
|
|
38
|
+
"--files-from",
|
|
39
|
+
metavar="FILE",
|
|
40
|
+
help="Read paths to scan from FILE (NUL- or newline-separated; '-' for stdin)",
|
|
41
|
+
)
|
|
42
|
+
scan_parser.add_argument(
|
|
43
|
+
"--runs",
|
|
44
|
+
type=_positive_int,
|
|
45
|
+
default=25_000,
|
|
46
|
+
help="Estimated runs per month (default: 25000)",
|
|
47
|
+
)
|
|
48
|
+
scan_parser.add_argument(
|
|
49
|
+
"--pricing",
|
|
50
|
+
metavar="JSON",
|
|
51
|
+
help="JSON file overriding cost-model assumptions (see docs/COST_MODEL.md)",
|
|
52
|
+
)
|
|
53
|
+
scan_parser.add_argument(
|
|
54
|
+
"--no-ai",
|
|
55
|
+
action="store_true",
|
|
56
|
+
help="Scan only, no AI refactoring (0 credits, dry-run mode)",
|
|
57
|
+
)
|
|
58
|
+
scan_parser.add_argument(
|
|
59
|
+
"--model",
|
|
60
|
+
type=str,
|
|
61
|
+
help="Copilot model to use for patching (default: claude-haiku-4.5 or $COSTLINT_MODEL)",
|
|
62
|
+
)
|
|
63
|
+
scan_parser.add_argument(
|
|
64
|
+
"--out",
|
|
65
|
+
type=str,
|
|
66
|
+
default="./costlint_out",
|
|
67
|
+
help="Output directory for reports and patches (default: ./costlint_out)",
|
|
68
|
+
)
|
|
69
|
+
scan_parser.add_argument(
|
|
70
|
+
"--fail-on-high",
|
|
71
|
+
action="store_true",
|
|
72
|
+
help="Exit with code 1 if any high-severity findings exist",
|
|
73
|
+
)
|
|
74
|
+
return parser
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _make_console_safe() -> None:
|
|
78
|
+
"""Never crash on characters the console can't encode (e.g. cp1252 on Windows)."""
|
|
79
|
+
for stream in (sys.stdout, sys.stderr):
|
|
80
|
+
try:
|
|
81
|
+
stream.reconfigure(errors="replace")
|
|
82
|
+
except (AttributeError, ValueError):
|
|
83
|
+
pass # not a TextIOWrapper (e.g. captured in tests)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main(argv: list[str] | None = None):
|
|
87
|
+
"""Main CLI entry point."""
|
|
88
|
+
_make_console_safe()
|
|
89
|
+
parser = build_parser()
|
|
90
|
+
args = parser.parse_args(argv)
|
|
91
|
+
|
|
92
|
+
if not args.command:
|
|
93
|
+
parser.print_help()
|
|
94
|
+
sys.exit(0)
|
|
95
|
+
|
|
96
|
+
if args.command == "scan":
|
|
97
|
+
if not args.target_paths and not args.files_from:
|
|
98
|
+
parser.error("scan: give at least one path or --files-from")
|
|
99
|
+
sys.exit(_handle_scan(args))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _read_files_from(source: str) -> list[str]:
|
|
103
|
+
data = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8")
|
|
104
|
+
separator = "\0" if "\0" in data else "\n"
|
|
105
|
+
return [p.strip("\r\n") for p in data.split(separator) if p.strip()]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _handle_scan(args) -> int:
|
|
109
|
+
"""Handle the scan command."""
|
|
110
|
+
raw_paths = list(args.target_paths or [])
|
|
111
|
+
if getattr(args, "files_from", None):
|
|
112
|
+
try:
|
|
113
|
+
raw_paths += _read_files_from(args.files_from)
|
|
114
|
+
except OSError as e:
|
|
115
|
+
print(f"Error: cannot read --files-from: {e}", file=sys.stderr)
|
|
116
|
+
return 1
|
|
117
|
+
if not raw_paths:
|
|
118
|
+
print("No paths to scan.")
|
|
119
|
+
target_paths = [Path(p) for p in raw_paths]
|
|
120
|
+
|
|
121
|
+
for target_path in target_paths:
|
|
122
|
+
if not target_path.exists():
|
|
123
|
+
print(f"Error: Path does not exist: {target_path}", file=sys.stderr)
|
|
124
|
+
return 1
|
|
125
|
+
|
|
126
|
+
assumptions = DEFAULT_ASSUMPTIONS
|
|
127
|
+
if getattr(args, "pricing", None):
|
|
128
|
+
try:
|
|
129
|
+
assumptions = load_assumptions(args.pricing)
|
|
130
|
+
except (OSError, ValueError) as e:
|
|
131
|
+
print(f"Error: invalid --pricing file: {e}", file=sys.stderr)
|
|
132
|
+
return 1
|
|
133
|
+
|
|
134
|
+
out_dir = Path(args.out)
|
|
135
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
|
|
137
|
+
if len(target_paths) <= 5:
|
|
138
|
+
print(f"Scanning: {', '.join(str(p) for p in target_paths)}")
|
|
139
|
+
else:
|
|
140
|
+
print(f"Scanning: {len(target_paths)} paths")
|
|
141
|
+
print(f"Estimated runs/month: {args.runs:,}")
|
|
142
|
+
print()
|
|
143
|
+
|
|
144
|
+
# Display paths are relative to the scanned directory (single dir) or the CWD.
|
|
145
|
+
if len(target_paths) == 1 and target_paths[0].is_dir():
|
|
146
|
+
scan_root = target_paths[0]
|
|
147
|
+
else:
|
|
148
|
+
scan_root = Path.cwd()
|
|
149
|
+
|
|
150
|
+
all_findings = []
|
|
151
|
+
for target_path in target_paths:
|
|
152
|
+
all_findings.extend(scan_path(str(target_path)))
|
|
153
|
+
|
|
154
|
+
print(f"Found {len(all_findings)} cost leak findings")
|
|
155
|
+
|
|
156
|
+
# Group by the real on-disk path *before* file_path is rewritten for display,
|
|
157
|
+
# so the patcher can still open the source file (CLI-2).
|
|
158
|
+
findings_by_source: dict[str, list] = {}
|
|
159
|
+
for finding in all_findings:
|
|
160
|
+
findings_by_source.setdefault(finding.file_path, []).append(finding)
|
|
161
|
+
|
|
162
|
+
for finding in all_findings:
|
|
163
|
+
try:
|
|
164
|
+
finding.file_path = Path(finding.file_path).resolve().relative_to(scan_root.resolve()).as_posix()
|
|
165
|
+
except ValueError:
|
|
166
|
+
pass # outside scan_root: keep as given
|
|
167
|
+
|
|
168
|
+
findings, cost_summary = estimate_costs(all_findings, runs_per_month=args.runs, assumptions=assumptions)
|
|
169
|
+
|
|
170
|
+
patches = []
|
|
171
|
+
if not args.no_ai and findings:
|
|
172
|
+
print("Generating AI refactored patches...")
|
|
173
|
+
patches = asyncio.run(_generate_patches_async(findings_by_source, args.model))
|
|
174
|
+
print(f"Generated {len(patches)} patches")
|
|
175
|
+
|
|
176
|
+
scanned_files = len({p.resolve() for t in target_paths for p in iter_python_files(t)})
|
|
177
|
+
report = ScanReport(
|
|
178
|
+
scanned_files=scanned_files,
|
|
179
|
+
findings=findings,
|
|
180
|
+
cost_summary=cost_summary,
|
|
181
|
+
patches=patches,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
_print_summary_table(report)
|
|
185
|
+
_write_report_files(report, out_dir)
|
|
186
|
+
|
|
187
|
+
if args.fail_on_high:
|
|
188
|
+
high_findings = [f for f in findings if f.severity == "high"]
|
|
189
|
+
if high_findings:
|
|
190
|
+
print()
|
|
191
|
+
print(f"FAIL: {len(high_findings)} high-severity findings detected")
|
|
192
|
+
return 1
|
|
193
|
+
|
|
194
|
+
print()
|
|
195
|
+
print(f"Reports written to: {out_dir}")
|
|
196
|
+
return 0
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
async def _generate_patches_async(findings_by_source: dict[str, list], model: str | None):
|
|
200
|
+
"""Generate one patch per file (CLI-1).
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
findings_by_source: maps the real on-disk path to that file's findings. The
|
|
204
|
+
findings' own ``file_path`` is the display path used in reports.
|
|
205
|
+
"""
|
|
206
|
+
patches = []
|
|
207
|
+
for source_path, file_findings in findings_by_source.items():
|
|
208
|
+
display_path = file_findings[0].file_path
|
|
209
|
+
try:
|
|
210
|
+
with open(source_path, "r", encoding="utf-8") as file:
|
|
211
|
+
source_code = file.read()
|
|
212
|
+
|
|
213
|
+
patch = await generate_patch(
|
|
214
|
+
display_path,
|
|
215
|
+
source_code,
|
|
216
|
+
file_findings,
|
|
217
|
+
model=model,
|
|
218
|
+
dry_run=False, # Live mode
|
|
219
|
+
)
|
|
220
|
+
patches.append(patch)
|
|
221
|
+
except Exception as e:
|
|
222
|
+
print(f"WARNING: Error generating patch for {display_path}: {e}", file=sys.stderr)
|
|
223
|
+
|
|
224
|
+
return patches
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _patch_output_stem(display_path: str) -> str:
|
|
228
|
+
"""Turn a display path into a unique flat file stem: pkg/a/agent.py -> pkg__a__agent."""
|
|
229
|
+
path = Path(display_path)
|
|
230
|
+
parts = [p for p in path.with_suffix("").parts if p not in ("", ".", "..", path.anchor)]
|
|
231
|
+
return "__".join(parts) or "patch"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _print_summary_table(report: ScanReport):
|
|
235
|
+
"""Print a readable summary table to console."""
|
|
236
|
+
print("=" * TABLE_WIDTH)
|
|
237
|
+
print("COSTLINT SCAN RESULTS")
|
|
238
|
+
print("=" * TABLE_WIDTH)
|
|
239
|
+
print()
|
|
240
|
+
print(f"Scanned Files: {report.scanned_files}")
|
|
241
|
+
print(f"Findings: {len(report.findings)}")
|
|
242
|
+
print()
|
|
243
|
+
|
|
244
|
+
if not report.findings:
|
|
245
|
+
print("No cost leaks detected!")
|
|
246
|
+
print()
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
file_width = min(max(max(len(f.file_path) for f in report.findings), 15), 40)
|
|
250
|
+
print("COST LEAK FINDINGS:")
|
|
251
|
+
print("-" * TABLE_WIDTH)
|
|
252
|
+
print(f"{'Rule':<7} {'Severity':<8} {'Line':<6} {'File':<{file_width}} {'Title':<28} {'Waste/mo':>10}")
|
|
253
|
+
print("-" * TABLE_WIDTH)
|
|
254
|
+
|
|
255
|
+
badges = {"high": "[HIGH]", "medium": "[MED]", "low": "[LOW]"}
|
|
256
|
+
for f in report.findings:
|
|
257
|
+
file_path = f.file_path if len(f.file_path) <= file_width else "..." + f.file_path[-(file_width - 3):]
|
|
258
|
+
print(
|
|
259
|
+
f"{f.rule_id:<7} {badges.get(f.severity, '[?]'):<8} {f.line_number:<6} "
|
|
260
|
+
f"{file_path:<{file_width}} {f.title[:28]:<28} ${f.estimated_monthly_waste_usd:>9.2f}"
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
s = report.cost_summary
|
|
264
|
+
print()
|
|
265
|
+
print("=" * TABLE_WIDTH)
|
|
266
|
+
print("ESTIMATED COST OF DETECTED LEAKS (per month)")
|
|
267
|
+
print("=" * TABLE_WIDTH)
|
|
268
|
+
print(f"Estimated waste: ${s.estimated_monthly_waste_usd:>10.2f}")
|
|
269
|
+
print(f"Recoverable with fixes: ${s.estimated_monthly_recoverable_usd:>10.2f} ({s.recoverable_percentage:.1f}%)")
|
|
270
|
+
print(f"Remaining after fixes: ${s.estimated_monthly_residual_usd:>10.2f}")
|
|
271
|
+
print(ILLUSTRATIVE_NOTE)
|
|
272
|
+
print("=" * TABLE_WIDTH)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _write_report_files(report: ScanReport, out_dir: Path, target_paths: list | None = None):
|
|
276
|
+
"""Write report files (JSON, markdown, patches)."""
|
|
277
|
+
with open(out_dir / "report.json", "w", encoding="utf-8") as f:
|
|
278
|
+
f.write(report.model_dump_json(indent=2))
|
|
279
|
+
|
|
280
|
+
with open(out_dir / "pr_comment.md", "w", encoding="utf-8") as f:
|
|
281
|
+
f.write(_generate_pr_comment(report))
|
|
282
|
+
|
|
283
|
+
for patch in report.patches:
|
|
284
|
+
stem = _patch_output_stem(patch.file_path)
|
|
285
|
+
with open(out_dir / (stem + ".patch"), "w", encoding="utf-8") as f:
|
|
286
|
+
f.write(patch.unified_diff)
|
|
287
|
+
with open(out_dir / (stem + "_patched.py"), "w", encoding="utf-8") as f:
|
|
288
|
+
f.write(patch.patched_code)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _md_cell(text: str) -> str:
|
|
292
|
+
"""Make text safe for a Markdown table cell."""
|
|
293
|
+
return str(text).replace("\\", "\\\\").replace("|", "\\|").replace("\r", " ").replace("\n", " ")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _generate_pr_comment(report: ScanReport) -> str:
|
|
297
|
+
"""Generate a GitHub PR comment in markdown."""
|
|
298
|
+
comment = "## CostLint Analysis Results\n\n"
|
|
299
|
+
|
|
300
|
+
if not report.findings:
|
|
301
|
+
comment += f"✓ No cost leaks detected in {report.scanned_files} scanned file(s).\n"
|
|
302
|
+
return comment
|
|
303
|
+
|
|
304
|
+
s = report.cost_summary
|
|
305
|
+
comment += f"**Findings:** {len(report.findings)} cost leak(s) detected\n\n"
|
|
306
|
+
|
|
307
|
+
comment += "### Estimated Cost of Detected Leaks\n\n"
|
|
308
|
+
comment += "| Metric | Per month |\n"
|
|
309
|
+
comment += "|--------|-----------|\n"
|
|
310
|
+
comment += f"| Estimated waste | ${s.estimated_monthly_waste_usd:,.2f} |\n"
|
|
311
|
+
comment += f"| Recoverable with fixes | ${s.estimated_monthly_recoverable_usd:,.2f} ({s.recoverable_percentage:.1f}%) |\n"
|
|
312
|
+
comment += f"| Remaining after fixes | ${s.estimated_monthly_residual_usd:,.2f} |\n"
|
|
313
|
+
comment += f"\n<sub>{ILLUSTRATIVE_NOTE} Assumes {s.runs_per_month:,} runs/month.</sub>\n\n"
|
|
314
|
+
|
|
315
|
+
comment += "### Detected Issues\n\n"
|
|
316
|
+
comment += "| File | Rule | Severity | Line | Title | Waste/mo | Fix |\n"
|
|
317
|
+
comment += "|------|------|----------|------|-------|----------|-----|\n"
|
|
318
|
+
severity_label = {"high": "HIGH", "medium": "MED", "low": "LOW"}
|
|
319
|
+
for f in report.findings:
|
|
320
|
+
comment += (
|
|
321
|
+
f"| `{_md_cell(f.file_path)}` | {f.rule_id} | {severity_label.get(f.severity, '?')} | "
|
|
322
|
+
f"{f.line_number} | {_md_cell(f.title)} | ${f.estimated_monthly_waste_usd:,.2f} | "
|
|
323
|
+
f"{_md_cell(f.recommended_fix)} |\n"
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
comment += "\n### Recommendations\n\n"
|
|
327
|
+
for f in report.findings:
|
|
328
|
+
comment += f"- **{f.rule_id}** (`{f.file_path}`, line {f.line_number}): {f.explanation}\n"
|
|
329
|
+
comment += f" - Fix: {f.recommended_fix}\n"
|
|
330
|
+
|
|
331
|
+
comment += "\n---\n"
|
|
332
|
+
comment += "*CostLint — Pre-merge AI token cost & loop safety linter*\n"
|
|
333
|
+
return comment
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
if __name__ == "__main__":
|
|
337
|
+
main()
|
costlint/estimator.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Illustrative monthly cost model for CostLint findings.
|
|
2
|
+
|
|
3
|
+
Every number used here lives in DEFAULT_ASSUMPTIONS and can be overridden with a JSON
|
|
4
|
+
file (``costlint scan --pricing my_pricing.json``). See docs/COST_MODEL.md for the
|
|
5
|
+
formula behind each rule.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .models import CostSummary, Finding
|
|
14
|
+
|
|
15
|
+
DEFAULT_ASSUMPTIONS: dict[str, Any] = {
|
|
16
|
+
# USD per 1M tokens for three generic tiers (not specific vendor prices).
|
|
17
|
+
"pricing_per_million_tokens": {
|
|
18
|
+
"flagship": {"input": 4.00, "output": 20.00},
|
|
19
|
+
"standard": {"input": 2.00, "output": 10.00},
|
|
20
|
+
"lightweight": {"input": 0.10, "output": 0.50},
|
|
21
|
+
},
|
|
22
|
+
"rules": {
|
|
23
|
+
# A share of runs hit a long retry spiral; a turn cap removes most of it.
|
|
24
|
+
"CL001": {
|
|
25
|
+
"tier": "standard",
|
|
26
|
+
"incident_rate": 0.01,
|
|
27
|
+
"input_tokens_per_incident": 30_000,
|
|
28
|
+
"output_tokens_per_incident": 3_000,
|
|
29
|
+
"recoverable_fraction": 0.70,
|
|
30
|
+
},
|
|
31
|
+
# The static prompt is re-billed at full price instead of the cached rate.
|
|
32
|
+
"CL002": {
|
|
33
|
+
"tier": "standard",
|
|
34
|
+
"static_prompt_tokens": 3_500,
|
|
35
|
+
"cache_discount": 0.85,
|
|
36
|
+
},
|
|
37
|
+
# Average uncapped output vs. the recommended cap; the excess is removed by the cap.
|
|
38
|
+
"CL003": {
|
|
39
|
+
"tier": "standard",
|
|
40
|
+
"uncapped_output_tokens": 900,
|
|
41
|
+
"capped_output_tokens": 250,
|
|
42
|
+
},
|
|
43
|
+
# Same call on a flagship vs. a lightweight model.
|
|
44
|
+
"CL004": {
|
|
45
|
+
"from_tier": "flagship",
|
|
46
|
+
"to_tier": "lightweight",
|
|
47
|
+
"input_tokens": 1_500,
|
|
48
|
+
"output_tokens": 300,
|
|
49
|
+
},
|
|
50
|
+
# Browser MCP page snapshots vs. plain HTTP fetch, on the runs that browse.
|
|
51
|
+
"CL005": {
|
|
52
|
+
"tier": "standard",
|
|
53
|
+
"incident_rate": 0.10,
|
|
54
|
+
"browser_tokens": 110_000,
|
|
55
|
+
"http_tokens": 25_000,
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# Backwards-compatible alias (0.1.x).
|
|
61
|
+
PRICING_TIERS = DEFAULT_ASSUMPTIONS["pricing_per_million_tokens"]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def load_assumptions(path: str | Path) -> dict[str, Any]:
|
|
65
|
+
"""Load a JSON override and deep-merge it over DEFAULT_ASSUMPTIONS.
|
|
66
|
+
|
|
67
|
+
Only keys that exist in the defaults may be overridden, so typos fail loudly.
|
|
68
|
+
"""
|
|
69
|
+
with open(path, encoding="utf-8") as f:
|
|
70
|
+
override = json.load(f)
|
|
71
|
+
merged = copy.deepcopy(DEFAULT_ASSUMPTIONS)
|
|
72
|
+
_merge(merged, override, path_prefix="")
|
|
73
|
+
tiers = merged["pricing_per_million_tokens"]
|
|
74
|
+
for name, tier in tiers.items():
|
|
75
|
+
if not {"input", "output"} <= set(tier):
|
|
76
|
+
raise ValueError(f"Pricing tier '{name}' needs 'input' and 'output' prices")
|
|
77
|
+
for rule_id, rule in merged["rules"].items():
|
|
78
|
+
for key in ("tier", "from_tier", "to_tier"):
|
|
79
|
+
if key in rule and rule[key] not in tiers:
|
|
80
|
+
raise ValueError(f"rules.{rule_id}.{key} refers to unknown tier '{rule[key]}'")
|
|
81
|
+
return merged
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _merge(base: dict, override: dict, path_prefix: str) -> None:
|
|
85
|
+
if not isinstance(override, dict):
|
|
86
|
+
raise ValueError(f"Expected an object at '{path_prefix or '<root>'}'")
|
|
87
|
+
for key, value in override.items():
|
|
88
|
+
where = f"{path_prefix}.{key}" if path_prefix else key
|
|
89
|
+
if key not in base:
|
|
90
|
+
# New pricing tiers are allowed; anything else must already exist.
|
|
91
|
+
if path_prefix == "pricing_per_million_tokens" and isinstance(value, dict):
|
|
92
|
+
base[key] = value
|
|
93
|
+
continue
|
|
94
|
+
raise ValueError(f"Unknown assumption '{where}'")
|
|
95
|
+
if isinstance(base[key], dict):
|
|
96
|
+
_merge(base[key], value, where)
|
|
97
|
+
elif isinstance(base[key], str):
|
|
98
|
+
if not isinstance(value, str):
|
|
99
|
+
raise ValueError(f"Assumption '{where}' must be a string")
|
|
100
|
+
base[key] = value
|
|
101
|
+
else:
|
|
102
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool) or value < 0:
|
|
103
|
+
raise ValueError(f"Assumption '{where}' must be a non-negative number")
|
|
104
|
+
base[key] = value
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def estimate_costs(
|
|
108
|
+
findings: list[Finding],
|
|
109
|
+
runs_per_month: int = 25_000,
|
|
110
|
+
assumptions: dict[str, Any] | None = None,
|
|
111
|
+
) -> tuple[list[Finding], CostSummary]:
|
|
112
|
+
"""Attach monthly waste/recoverable estimates to findings and summarise them.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
findings: Detected cost leaks (updated in place).
|
|
116
|
+
runs_per_month: Estimated LLM invocations per month.
|
|
117
|
+
assumptions: Cost model; defaults to DEFAULT_ASSUMPTIONS.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
(findings, CostSummary)
|
|
121
|
+
"""
|
|
122
|
+
model = assumptions or DEFAULT_ASSUMPTIONS
|
|
123
|
+
for finding in findings:
|
|
124
|
+
waste, recoverable = _estimate_rule_impact(finding.rule_id, runs_per_month, model)
|
|
125
|
+
finding.estimated_monthly_waste_usd = waste
|
|
126
|
+
finding.estimated_monthly_savings_usd = recoverable
|
|
127
|
+
|
|
128
|
+
total_waste = sum(f.estimated_monthly_waste_usd for f in findings)
|
|
129
|
+
total_recoverable = sum(f.estimated_monthly_savings_usd for f in findings)
|
|
130
|
+
pct = (total_recoverable / total_waste * 100) if total_waste > 0 else 0.0
|
|
131
|
+
|
|
132
|
+
summary = CostSummary(
|
|
133
|
+
runs_per_month=runs_per_month,
|
|
134
|
+
estimated_monthly_waste_usd=total_waste,
|
|
135
|
+
estimated_monthly_recoverable_usd=total_recoverable,
|
|
136
|
+
estimated_monthly_residual_usd=max(0.0, total_waste - total_recoverable),
|
|
137
|
+
recoverable_percentage=min(100.0, pct),
|
|
138
|
+
)
|
|
139
|
+
return findings, summary
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _cost(tokens: float, tier: dict[str, float], kind: str) -> float:
|
|
143
|
+
return tokens * tier[kind] / 1_000_000
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _estimate_rule_impact(
|
|
147
|
+
rule_id: str, runs_per_month: int, model: dict[str, Any] | None = None
|
|
148
|
+
) -> tuple[float, float]:
|
|
149
|
+
"""Return (monthly_waste_usd, monthly_recoverable_usd) for one finding."""
|
|
150
|
+
model = model or DEFAULT_ASSUMPTIONS
|
|
151
|
+
prices = model["pricing_per_million_tokens"]
|
|
152
|
+
rule = model["rules"].get(rule_id)
|
|
153
|
+
if rule is None:
|
|
154
|
+
return 0.0, 0.0
|
|
155
|
+
|
|
156
|
+
if rule_id == "CL001":
|
|
157
|
+
tier = prices[rule["tier"]]
|
|
158
|
+
incidents = runs_per_month * rule["incident_rate"]
|
|
159
|
+
per_incident = _cost(rule["input_tokens_per_incident"], tier, "input") + _cost(
|
|
160
|
+
rule["output_tokens_per_incident"], tier, "output"
|
|
161
|
+
)
|
|
162
|
+
waste = per_incident * incidents
|
|
163
|
+
return waste, waste * rule["recoverable_fraction"]
|
|
164
|
+
|
|
165
|
+
if rule_id == "CL002":
|
|
166
|
+
tier = prices[rule["tier"]]
|
|
167
|
+
waste = _cost(rule["static_prompt_tokens"], tier, "input") * runs_per_month
|
|
168
|
+
return waste, waste * rule["cache_discount"]
|
|
169
|
+
|
|
170
|
+
if rule_id == "CL003":
|
|
171
|
+
tier = prices[rule["tier"]]
|
|
172
|
+
excess = max(0, rule["uncapped_output_tokens"] - rule["capped_output_tokens"])
|
|
173
|
+
waste = _cost(excess, tier, "output") * runs_per_month
|
|
174
|
+
return waste, waste # the cap removes exactly the excess tokens
|
|
175
|
+
|
|
176
|
+
if rule_id == "CL004":
|
|
177
|
+
expensive, cheap = prices[rule["from_tier"]], prices[rule["to_tier"]]
|
|
178
|
+
|
|
179
|
+
def per_run(tier: dict[str, float]) -> float:
|
|
180
|
+
return _cost(rule["input_tokens"], tier, "input") + _cost(rule["output_tokens"], tier, "output")
|
|
181
|
+
|
|
182
|
+
waste = per_run(expensive) * runs_per_month
|
|
183
|
+
recoverable = max(0.0, per_run(expensive) - per_run(cheap)) * runs_per_month
|
|
184
|
+
return waste, recoverable
|
|
185
|
+
|
|
186
|
+
if rule_id == "CL005":
|
|
187
|
+
tier = prices[rule["tier"]]
|
|
188
|
+
incidents = runs_per_month * rule["incident_rate"]
|
|
189
|
+
excess = max(0, rule["browser_tokens"] - rule["http_tokens"])
|
|
190
|
+
waste = _cost(excess, tier, "input") * incidents
|
|
191
|
+
return waste, waste # switching to HTTP fetch removes the excess
|
|
192
|
+
|
|
193
|
+
return 0.0, 0.0
|
costlint/models.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Pydantic v2 schemas for CostLint findings, cost breakdown, and patches."""
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
from pydantic import BaseModel, Field, computed_field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Finding(BaseModel):
|
|
8
|
+
"""Represents a single cost leak finding."""
|
|
9
|
+
|
|
10
|
+
rule_id: Literal["CL001", "CL002", "CL003", "CL004", "CL005"]
|
|
11
|
+
title: str
|
|
12
|
+
severity: Literal["high", "medium", "low"]
|
|
13
|
+
file_path: str
|
|
14
|
+
line_number: int
|
|
15
|
+
end_line_number: int
|
|
16
|
+
function_name: str | None = None
|
|
17
|
+
snippet: str
|
|
18
|
+
explanation: str
|
|
19
|
+
recommended_fix: str
|
|
20
|
+
estimated_monthly_waste_usd: float = Field(default=0.0, ge=0.0)
|
|
21
|
+
estimated_monthly_savings_usd: float = Field(default=0.0, ge=0.0)
|
|
22
|
+
# Rule-specific facts the patcher can use, e.g. {"model": "claude-opus-5.5"} for CL004.
|
|
23
|
+
metadata: dict[str, str] = Field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CostSummary(BaseModel):
|
|
27
|
+
"""Aggregated, illustrative cost of the detected leaks (not total API spend).
|
|
28
|
+
|
|
29
|
+
- waste: estimated monthly cost attributable to the findings
|
|
30
|
+
- recoverable: the part of that waste the recommended fixes remove
|
|
31
|
+
- residual: waste that remains after the fixes (waste - recoverable)
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
runs_per_month: int = Field(ge=1)
|
|
35
|
+
estimated_monthly_waste_usd: float = Field(ge=0.0)
|
|
36
|
+
estimated_monthly_recoverable_usd: float = Field(ge=0.0)
|
|
37
|
+
estimated_monthly_residual_usd: float = Field(ge=0.0)
|
|
38
|
+
recoverable_percentage: float = Field(ge=0.0, le=100.0)
|
|
39
|
+
|
|
40
|
+
# Deprecated names from 0.1.x, still emitted in JSON for one release so existing
|
|
41
|
+
# readers of report.json keep working. They were mislabelled: "current spend" was
|
|
42
|
+
# always total waste, not real spend.
|
|
43
|
+
@computed_field(description="Deprecated alias of estimated_monthly_waste_usd")
|
|
44
|
+
@property
|
|
45
|
+
def estimated_current_monthly_usd(self) -> float:
|
|
46
|
+
return self.estimated_monthly_waste_usd
|
|
47
|
+
|
|
48
|
+
@computed_field(description="Deprecated alias of estimated_monthly_residual_usd")
|
|
49
|
+
@property
|
|
50
|
+
def estimated_optimized_monthly_usd(self) -> float:
|
|
51
|
+
return self.estimated_monthly_residual_usd
|
|
52
|
+
|
|
53
|
+
@computed_field(description="Deprecated alias of estimated_monthly_recoverable_usd")
|
|
54
|
+
@property
|
|
55
|
+
def estimated_monthly_savings_usd(self) -> float:
|
|
56
|
+
return self.estimated_monthly_recoverable_usd
|
|
57
|
+
|
|
58
|
+
@computed_field(description="Deprecated alias of recoverable_percentage")
|
|
59
|
+
@property
|
|
60
|
+
def savings_percentage(self) -> float:
|
|
61
|
+
return self.recoverable_percentage
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PatchResult(BaseModel):
|
|
65
|
+
"""Result of AI-powered or dry-run code patching."""
|
|
66
|
+
|
|
67
|
+
mode: Literal["copilot_sdk", "dry_run", "error"]
|
|
68
|
+
file_path: str
|
|
69
|
+
original_code: str
|
|
70
|
+
patched_code: str
|
|
71
|
+
unified_diff: str
|
|
72
|
+
syntax_valid: bool
|
|
73
|
+
agent_notes: str = ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ScanReport(BaseModel):
|
|
77
|
+
"""Complete scan report with findings, costs, and patches."""
|
|
78
|
+
|
|
79
|
+
scanned_files: int = Field(ge=0)
|
|
80
|
+
findings: list[Finding] = Field(default_factory=list)
|
|
81
|
+
cost_summary: CostSummary
|
|
82
|
+
patches: list[PatchResult] = Field(default_factory=list)
|