costlint 0.3.0__tar.gz

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-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Suri Madhav
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,282 @@
1
+ Metadata-Version: 2.4
2
+ Name: costlint
3
+ Version: 0.3.0
4
+ Summary: CostLint — Pre-merge AI token cost & loop safety linter for Python
5
+ Author: Madhav
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Appemout/costLint
8
+ Project-URL: Documentation, https://github.com/Appemout/costLint#readme
9
+ Project-URL: Changelog, https://github.com/Appemout/costLint/blob/main/CHANGELOG.md
10
+ Project-URL: Repository, https://github.com/Appemout/costLint.git
11
+ Project-URL: Issues, https://github.com/Appemout/costLint/issues
12
+ Keywords: ai,llm,cost,tokens,linter,static-analysis,openai,anthropic,copilot,agents
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: pydantic>=2.7.0
28
+ Provides-Extra: ai
29
+ Requires-Dist: microsoft-copilot-sdk<3,>=2.0.4; python_version >= "3.11" and extra == "ai"
30
+ Provides-Extra: ui
31
+ Requires-Dist: streamlit>=1.38.0; extra == "ui"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
34
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
35
+ Provides-Extra: all
36
+ Requires-Dist: microsoft-copilot-sdk<3,>=2.0.4; python_version >= "3.11" and extra == "all"
37
+ Requires-Dist: streamlit>=1.38.0; extra == "all"
38
+ Requires-Dist: pytest>=8.0.0; extra == "all"
39
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == "all"
40
+ Dynamic: license-file
41
+
42
+ # CostLint — Pre-Merge AI Cost & Loop Safety Linter
43
+
44
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue)](https://www.python.org/downloads/)
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/Appemout/costLint/blob/main/LICENSE)
46
+ [![Tests](https://github.com/Appemout/costLint/actions/workflows/tests.yml/badge.svg)](https://github.com/Appemout/costLint/actions/workflows/tests.yml)
47
+
48
+ **CostLint** finds code patterns that inflate LLM API bills, such as runaway agent loops, broken prompt caches, uncapped output and oversized models, in Python code **before it's merged**.
49
+
50
+ - **Static and free.** The scanner uses Python's `ast` module. No code leaves your machine and no AI credits are spent (`--no-ai`).
51
+ - **Ranked by cost.** Each finding gets an illustrative monthly cost estimate, and every assumption can be overridden ([cost model](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md)).
52
+ - **CI-ready.** A GitHub Actions workflow scans only the files a PR changes, posts a comment, and fails the check on high-severity findings.
53
+ - **Optional auto-fix.** A Copilot SDK patcher proposes a refactor, validates it with `ast.parse()`, and falls back to TODO comments when it can't.
54
+
55
+ ---
56
+
57
+ ## Detection rules
58
+
59
+ | Rule | Severity | Flags | Recommended fix |
60
+ |------|----------|-------|-----------------|
61
+ | **CL001** | 🔴 High | A loop that calls an LLM/agent and can run forever: `while True`/`while 1`, `while not done` where `done` is never updated, or `for` over `itertools.count()`/`cycle()`, with no `max_turns`-style guard and either no `break`/`return`/`raise` or an `except` that swallows errors and retries (`except: continue`). Loops that wait on `input()`, a websocket or a work queue are human/work-paced and skipped | Bound the loop with a turn/attempt counter |
62
+ | **CL002** | 🔴 High | A system prompt **built inside a function** (so per call) with per-request values (`datetime.now()`, `uuid4()`, `session_id`, …) in its **first 250 characters**: a `*system*`/`*instructions*` variable, a `system=`/`instructions=`/`system_instruction=` argument, or a `{"role": "system"}` message. This changes the cacheable prefix on every call. Module-level prompts (built once at import) and date-only values (`%Y-%m-%d`, `date.today()`, changing once a day) are not flagged | Keep the prompt prefix static; move dynamic values to the end or into the user message |
63
+ | **CL003** | 🟡 Medium | Completion calls without `max_tokens`, `max_output_tokens`, `max_completion_tokens`, a `config=`/`generation_config=` object or `**kwargs`: OpenAI (`chat.completions.create`/`.parse`, `responses.create`, legacy `ChatCompletion.create`), Anthropic (`messages.create`), Gemini (`generate_content`), instructor, and LiteLLM (`completion`/`acompletion`) | Add an output limit sized to the expected reply |
64
+ | **CL004** | 🟡 Medium | A flagship model (`opus`, `fable`, `o1`, `o3`, `gpt-4.5`, `gpt-5-pro`) in a lightweight function: one whose name says classify/route/tag/extract/parse/…, or one that is short (≤15 lines) with a single LLM call and no loops | Use a lightweight model (e.g. `claude-haiku-4.5`, `gpt-4o-mini`) |
65
+ | **CL005** | 🟢 Low | A browser-automation MCP server package or command (e.g. `@playwright/mcp`, `puppeteer-mcp-server`, `@modelcontextprotocol/server-puppeteer`, `chrome-devtools-mcp`), reported once per file. Informational: it can't tell whether the agent only reads pages | If pages are only read, use a plain HTTP fetch tool |
66
+
67
+ All rules are heuristics. They are tuned to avoid noise, but they will sometimes miss leaks or flag intended code. See [real-world testing](https://github.com/Appemout/costLint/blob/main/docs/REAL_WORLD_TESTING.md) for results on 33 open-source agent repos (16,000+ files): about 60% precision on code it hadn't seen before, with every false alarm found fixed and covered by a regression test.
68
+
69
+ ---
70
+
71
+ ## Quick start
72
+
73
+ Requires Python 3.10+ (live auto-patching with the Copilot SDK needs 3.11+).
74
+
75
+ ```bash
76
+ pip install costlint # scanner + CLI
77
+ pip install "costlint[ui,ai]" # + Streamlit UI and Copilot patcher
78
+ ```
79
+
80
+ Or from a clone, for development:
81
+
82
+ ```bash
83
+ git clone https://github.com/Appemout/costLint && cd costLint
84
+ python -m venv .venv
85
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
86
+ pip install -e ".[ui,ai,dev]"
87
+ ```
88
+
89
+ ### Scan (no AI, free)
90
+
91
+ ```bash
92
+ costlint scan samples/bad_support_agent.py --no-ai
93
+ costlint scan . --no-ai --out ./report
94
+ costlint scan src/ --runs 50000 --pricing pricing.json --no-ai
95
+ ```
96
+
97
+ Output for the bundled leaky sample:
98
+
99
+ ```
100
+ COST LEAK FINDINGS:
101
+ ----------------------------------------------------------------------------------------------------
102
+ Rule Severity Line File Title Waste/mo
103
+ ----------------------------------------------------------------------------------------------------
104
+ CL002 [HIGH] 25 samples/bad_support_agent.py Broken Prompt Cache Prefix $ 175.00
105
+ CL003 [MED] 31 samples/bad_support_agent.py Missing Output Token Limit $ 162.50
106
+ CL004 [MED] 32 samples/bad_support_agent.py Over-Provisioned Flagship Mo $ 300.00
107
+ CL001 [HIGH] 55 samples/bad_support_agent.py Unbounded Agent / Tool Retry $ 22.50
108
+
109
+ ====================================================================================================
110
+ ESTIMATED COST OF DETECTED LEAKS (per month)
111
+ ====================================================================================================
112
+ Estimated waste: $ 660.00
113
+ Recoverable with fixes: $ 619.50 (93.9%)
114
+ Remaining after fixes: $ 40.50
115
+ Illustrative estimate based on generic token prices; see docs/COST_MODEL.md.
116
+ ```
117
+
118
+ These dollar figures estimate what the **detected leaks** cost at the assumed volume. They are not your total API spend. See [docs/COST_MODEL.md](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md) for each formula and how to plug in your own prices.
119
+
120
+ ### `costlint scan` options
121
+
122
+ | Option | Default | Description |
123
+ |--------|---------|-------------|
124
+ | `PATH ...` | | Files and/or directories. Directories skip `tests/`, `test_*.py`, virtualenvs, `build/`, etc. |
125
+ | `--files-from FILE` | | Read paths from a file (NUL- or newline-separated, `-` for stdin) |
126
+ | `--runs N` | `25000` | LLM runs per month used for cost estimates |
127
+ | `--pricing JSON` | | Override cost-model assumptions ([format](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md#overriding-assumptions)) |
128
+ | `--no-ai` | off | Scan and report only; don't call Copilot |
129
+ | `--model NAME` | `$COSTLINT_MODEL` or `claude-haiku-4.5` | Model for live patching |
130
+ | `--out DIR` | `./costlint_out` | Where reports and patches are written |
131
+ | `--fail-on-high` | off | Exit 1 if any high-severity finding exists |
132
+
133
+ Files written to `--out`:
134
+ - `report.json`: every finding plus the cost summary.
135
+ - `pr_comment.md`: the Markdown used for PR comments.
136
+ - In live mode, `<name>.patch` and `<name>_patched.py` for each patched file. `<name>` is the file's path with `/` replaced by `__`, so `src/agent.py` becomes `src__agent.patch`.
137
+
138
+ ---
139
+
140
+ ## Live auto-patching (optional)
141
+
142
+ Without `--no-ai`, CostLint sends each affected file to a [Copilot SDK](https://pypi.org/project/microsoft-copilot-sdk/) session (requires Python 3.11+, `pip install -e ".[ai]"`, a Copilot subscription and `copilot login`):
143
+
144
+ ```bash
145
+ costlint scan samples/bad_support_agent.py --out ./report
146
+ COSTLINT_MODEL=claude-haiku-5.5 costlint scan src/ --out ./report
147
+ ```
148
+
149
+ - **Targeted prompt.** The model is told only about the findings in that file, including the line, function and detected model.
150
+ - **Size limit.** Files over 250 lines are not sent; they get TODO comments instead.
151
+ - **No tools.** Every tool or permission request the model makes is refused.
152
+ - **Validated output.** The reply must pass `ast.parse()`. CostLint asks once for a repair. If the reply is still invalid, or the SDK, auth or model is unavailable, you get a dry-run patch with TODO comments and a note explaining why.
153
+ - **Model fallback.** If the requested model isn't available, CostLint retries once with `model="auto"`.
154
+
155
+ Always review the generated patch before applying it.
156
+
157
+ ---
158
+
159
+ ## Streamlit UI
160
+
161
+ ```bash
162
+ streamlit run app.py
163
+ ```
164
+
165
+ You can paste code (the leaky sample is pre-loaded) or scan a local folder or file. The UI shows each finding and its cost, and lets you preview and download the patch and diff. **Dry-run mode** is on by default and spends no AI credits.
166
+
167
+ On public deployments (Streamlit Community Cloud, or `COSTLINT_CLOUD_MODE=1`), folder scanning and live AI patching are turned off, and pasted code is limited to 100,000 characters. Pasted code is processed in memory and not stored. For private code, run the CLI locally instead.
168
+
169
+ ---
170
+
171
+ ## GitHub Actions
172
+
173
+ Two workflows ship in [.github/workflows/](https://github.com/Appemout/costLint/tree/main/.github/workflows):
174
+
175
+ - **[`costlint.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint.yml)**: on every PR (PRs without Python changes pass immediately), it:
176
+ - scans the added or modified files, leaving out `tests/` and `samples/`;
177
+ - posts the report as a PR comment;
178
+ - **fails the check if there are high-severity findings**.
179
+
180
+ To actually block merging, mark the `costlint` check as **required** in your branch protection rules.
181
+ - **[`costlint-comment.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint-comment.yml)**: posts the comment for PRs from forks, whose token is read-only. It runs in the base repo, never executes fork code, and only comments if the PR's head commit matches the commit that was scanned. It takes effect once it's on the default branch.
182
+
183
+ [`tests.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/tests.yml) runs the test suite on Python 3.10–3.13.
184
+
185
+ ### Use CostLint in your own repository
186
+
187
+ The `costlint.yml` above installs CostLint from this repository's own checkout. In your repo, add `.github/workflows/costlint.yml`:
188
+
189
+ ```yaml
190
+ name: CostLint
191
+ on: pull_request
192
+ permissions:
193
+ contents: read
194
+
195
+ jobs:
196
+ costlint:
197
+ runs-on: ubuntu-latest
198
+ steps:
199
+ - uses: actions/checkout@v7
200
+ with:
201
+ fetch-depth: 0
202
+ - uses: actions/setup-python@v7
203
+ with:
204
+ python-version: '3.12'
205
+ - run: pip install "costlint==0.3.0" # pin the version for reproducible builds
206
+ - name: Scan changed Python files
207
+ env:
208
+ BASE_REF: ${{ github.base_ref }}
209
+ run: |
210
+ git diff -z --name-only --diff-filter=AM "origin/${BASE_REF}...HEAD" -- '*.py' > changed_files.txt
211
+ if [ -s changed_files.txt ]; then
212
+ costlint scan --files-from changed_files.txt --no-ai --fail-on-high
213
+ else
214
+ echo "No Python files changed"
215
+ fi
216
+ ```
217
+
218
+ The check fails when there are high-severity findings. To post the report as a PR comment, copy the comment steps from this repo's [`costlint.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint.yml) and [`costlint-comment.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint-comment.yml).
219
+
220
+ ---
221
+
222
+ ## Python API
223
+
224
+ ```python
225
+ import asyncio
226
+ from costlint.scanner import scan_source, scan_path
227
+ from costlint.estimator import estimate_costs, load_assumptions
228
+ from costlint.patcher import generate_patch
229
+
230
+ findings = scan_path("src/") # or scan_source(code, "file.py")
231
+ findings, summary = estimate_costs(findings, runs_per_month=25_000)
232
+ print(summary.estimated_monthly_waste_usd, summary.estimated_monthly_recoverable_usd)
233
+
234
+ # Custom assumptions
235
+ findings, summary = estimate_costs(findings, assumptions=load_assumptions("pricing.json"))
236
+
237
+ # Patch one file (dry_run=True: TODO comments only, no AI)
238
+ source = open("src/agent.py", encoding="utf-8").read()
239
+ file_findings = [f for f in findings if f.file_path.endswith("agent.py")]
240
+ patch = asyncio.run(generate_patch("src/agent.py", source, file_findings, dry_run=True))
241
+ print(patch.unified_diff)
242
+ ```
243
+
244
+ > `CostSummary` field names changed in 0.2.0. The old names (`estimated_current_monthly_usd`, `estimated_optimized_monthly_usd`, `estimated_monthly_savings_usd`, `savings_percentage`) still work as deprecated aliases.
245
+
246
+ ---
247
+
248
+ ## Development
249
+
250
+ ```bash
251
+ pip install -e ".[dev]"
252
+ pytest -q # 193 tests, all offline (the Copilot SDK is faked)
253
+ python -m py_compile app.py
254
+ ```
255
+
256
+ ```
257
+ costLint/
258
+ ├── src/costlint/
259
+ │ ├── scanner.py # AST rules CL001–CL005
260
+ │ ├── estimator.py # cost model + --pricing overrides
261
+ │ ├── patcher.py # dry-run and Copilot SDK patching
262
+ │ ├── cli.py # `costlint scan` (also `python -m costlint`)
263
+ │ └── models.py # Pydantic v2 schemas
264
+ ├── app.py # Streamlit UI
265
+ ├── samples/ # leaky and clean example agents
266
+ ├── tests/
267
+ └── docs/
268
+ ├── COST_MODEL.md # formulas and assumptions
269
+ ├── REAL_WORLD_TESTING.md # results on 33 public agent repos
270
+ ├── RELEASING.md # how to publish to PyPI
271
+ ├── KNOWN_ISSUES.md # issue register and resolutions
272
+ ├── FIX_PLAN.md
273
+ └── archive/ # original spec and build logs (historical)
274
+ ```
275
+
276
+ ---
277
+
278
+ ## License
279
+
280
+ MIT, see [LICENSE](https://github.com/Appemout/costLint/blob/main/LICENSE).
281
+
282
+ Issues and discussion: [github.com/Appemout/costLint/issues](https://github.com/Appemout/costLint/issues)
@@ -0,0 +1,241 @@
1
+ # CostLint — Pre-Merge AI Cost & Loop Safety Linter
2
+
3
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue)](https://www.python.org/downloads/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/Appemout/costLint/blob/main/LICENSE)
5
+ [![Tests](https://github.com/Appemout/costLint/actions/workflows/tests.yml/badge.svg)](https://github.com/Appemout/costLint/actions/workflows/tests.yml)
6
+
7
+ **CostLint** finds code patterns that inflate LLM API bills, such as runaway agent loops, broken prompt caches, uncapped output and oversized models, in Python code **before it's merged**.
8
+
9
+ - **Static and free.** The scanner uses Python's `ast` module. No code leaves your machine and no AI credits are spent (`--no-ai`).
10
+ - **Ranked by cost.** Each finding gets an illustrative monthly cost estimate, and every assumption can be overridden ([cost model](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md)).
11
+ - **CI-ready.** A GitHub Actions workflow scans only the files a PR changes, posts a comment, and fails the check on high-severity findings.
12
+ - **Optional auto-fix.** A Copilot SDK patcher proposes a refactor, validates it with `ast.parse()`, and falls back to TODO comments when it can't.
13
+
14
+ ---
15
+
16
+ ## Detection rules
17
+
18
+ | Rule | Severity | Flags | Recommended fix |
19
+ |------|----------|-------|-----------------|
20
+ | **CL001** | 🔴 High | A loop that calls an LLM/agent and can run forever: `while True`/`while 1`, `while not done` where `done` is never updated, or `for` over `itertools.count()`/`cycle()`, with no `max_turns`-style guard and either no `break`/`return`/`raise` or an `except` that swallows errors and retries (`except: continue`). Loops that wait on `input()`, a websocket or a work queue are human/work-paced and skipped | Bound the loop with a turn/attempt counter |
21
+ | **CL002** | 🔴 High | A system prompt **built inside a function** (so per call) with per-request values (`datetime.now()`, `uuid4()`, `session_id`, …) in its **first 250 characters**: a `*system*`/`*instructions*` variable, a `system=`/`instructions=`/`system_instruction=` argument, or a `{"role": "system"}` message. This changes the cacheable prefix on every call. Module-level prompts (built once at import) and date-only values (`%Y-%m-%d`, `date.today()`, changing once a day) are not flagged | Keep the prompt prefix static; move dynamic values to the end or into the user message |
22
+ | **CL003** | 🟡 Medium | Completion calls without `max_tokens`, `max_output_tokens`, `max_completion_tokens`, a `config=`/`generation_config=` object or `**kwargs`: OpenAI (`chat.completions.create`/`.parse`, `responses.create`, legacy `ChatCompletion.create`), Anthropic (`messages.create`), Gemini (`generate_content`), instructor, and LiteLLM (`completion`/`acompletion`) | Add an output limit sized to the expected reply |
23
+ | **CL004** | 🟡 Medium | A flagship model (`opus`, `fable`, `o1`, `o3`, `gpt-4.5`, `gpt-5-pro`) in a lightweight function: one whose name says classify/route/tag/extract/parse/…, or one that is short (≤15 lines) with a single LLM call and no loops | Use a lightweight model (e.g. `claude-haiku-4.5`, `gpt-4o-mini`) |
24
+ | **CL005** | 🟢 Low | A browser-automation MCP server package or command (e.g. `@playwright/mcp`, `puppeteer-mcp-server`, `@modelcontextprotocol/server-puppeteer`, `chrome-devtools-mcp`), reported once per file. Informational: it can't tell whether the agent only reads pages | If pages are only read, use a plain HTTP fetch tool |
25
+
26
+ All rules are heuristics. They are tuned to avoid noise, but they will sometimes miss leaks or flag intended code. See [real-world testing](https://github.com/Appemout/costLint/blob/main/docs/REAL_WORLD_TESTING.md) for results on 33 open-source agent repos (16,000+ files): about 60% precision on code it hadn't seen before, with every false alarm found fixed and covered by a regression test.
27
+
28
+ ---
29
+
30
+ ## Quick start
31
+
32
+ Requires Python 3.10+ (live auto-patching with the Copilot SDK needs 3.11+).
33
+
34
+ ```bash
35
+ pip install costlint # scanner + CLI
36
+ pip install "costlint[ui,ai]" # + Streamlit UI and Copilot patcher
37
+ ```
38
+
39
+ Or from a clone, for development:
40
+
41
+ ```bash
42
+ git clone https://github.com/Appemout/costLint && cd costLint
43
+ python -m venv .venv
44
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
45
+ pip install -e ".[ui,ai,dev]"
46
+ ```
47
+
48
+ ### Scan (no AI, free)
49
+
50
+ ```bash
51
+ costlint scan samples/bad_support_agent.py --no-ai
52
+ costlint scan . --no-ai --out ./report
53
+ costlint scan src/ --runs 50000 --pricing pricing.json --no-ai
54
+ ```
55
+
56
+ Output for the bundled leaky sample:
57
+
58
+ ```
59
+ COST LEAK FINDINGS:
60
+ ----------------------------------------------------------------------------------------------------
61
+ Rule Severity Line File Title Waste/mo
62
+ ----------------------------------------------------------------------------------------------------
63
+ CL002 [HIGH] 25 samples/bad_support_agent.py Broken Prompt Cache Prefix $ 175.00
64
+ CL003 [MED] 31 samples/bad_support_agent.py Missing Output Token Limit $ 162.50
65
+ CL004 [MED] 32 samples/bad_support_agent.py Over-Provisioned Flagship Mo $ 300.00
66
+ CL001 [HIGH] 55 samples/bad_support_agent.py Unbounded Agent / Tool Retry $ 22.50
67
+
68
+ ====================================================================================================
69
+ ESTIMATED COST OF DETECTED LEAKS (per month)
70
+ ====================================================================================================
71
+ Estimated waste: $ 660.00
72
+ Recoverable with fixes: $ 619.50 (93.9%)
73
+ Remaining after fixes: $ 40.50
74
+ Illustrative estimate based on generic token prices; see docs/COST_MODEL.md.
75
+ ```
76
+
77
+ These dollar figures estimate what the **detected leaks** cost at the assumed volume. They are not your total API spend. See [docs/COST_MODEL.md](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md) for each formula and how to plug in your own prices.
78
+
79
+ ### `costlint scan` options
80
+
81
+ | Option | Default | Description |
82
+ |--------|---------|-------------|
83
+ | `PATH ...` | | Files and/or directories. Directories skip `tests/`, `test_*.py`, virtualenvs, `build/`, etc. |
84
+ | `--files-from FILE` | | Read paths from a file (NUL- or newline-separated, `-` for stdin) |
85
+ | `--runs N` | `25000` | LLM runs per month used for cost estimates |
86
+ | `--pricing JSON` | | Override cost-model assumptions ([format](https://github.com/Appemout/costLint/blob/main/docs/COST_MODEL.md#overriding-assumptions)) |
87
+ | `--no-ai` | off | Scan and report only; don't call Copilot |
88
+ | `--model NAME` | `$COSTLINT_MODEL` or `claude-haiku-4.5` | Model for live patching |
89
+ | `--out DIR` | `./costlint_out` | Where reports and patches are written |
90
+ | `--fail-on-high` | off | Exit 1 if any high-severity finding exists |
91
+
92
+ Files written to `--out`:
93
+ - `report.json`: every finding plus the cost summary.
94
+ - `pr_comment.md`: the Markdown used for PR comments.
95
+ - In live mode, `<name>.patch` and `<name>_patched.py` for each patched file. `<name>` is the file's path with `/` replaced by `__`, so `src/agent.py` becomes `src__agent.patch`.
96
+
97
+ ---
98
+
99
+ ## Live auto-patching (optional)
100
+
101
+ Without `--no-ai`, CostLint sends each affected file to a [Copilot SDK](https://pypi.org/project/microsoft-copilot-sdk/) session (requires Python 3.11+, `pip install -e ".[ai]"`, a Copilot subscription and `copilot login`):
102
+
103
+ ```bash
104
+ costlint scan samples/bad_support_agent.py --out ./report
105
+ COSTLINT_MODEL=claude-haiku-5.5 costlint scan src/ --out ./report
106
+ ```
107
+
108
+ - **Targeted prompt.** The model is told only about the findings in that file, including the line, function and detected model.
109
+ - **Size limit.** Files over 250 lines are not sent; they get TODO comments instead.
110
+ - **No tools.** Every tool or permission request the model makes is refused.
111
+ - **Validated output.** The reply must pass `ast.parse()`. CostLint asks once for a repair. If the reply is still invalid, or the SDK, auth or model is unavailable, you get a dry-run patch with TODO comments and a note explaining why.
112
+ - **Model fallback.** If the requested model isn't available, CostLint retries once with `model="auto"`.
113
+
114
+ Always review the generated patch before applying it.
115
+
116
+ ---
117
+
118
+ ## Streamlit UI
119
+
120
+ ```bash
121
+ streamlit run app.py
122
+ ```
123
+
124
+ You can paste code (the leaky sample is pre-loaded) or scan a local folder or file. The UI shows each finding and its cost, and lets you preview and download the patch and diff. **Dry-run mode** is on by default and spends no AI credits.
125
+
126
+ On public deployments (Streamlit Community Cloud, or `COSTLINT_CLOUD_MODE=1`), folder scanning and live AI patching are turned off, and pasted code is limited to 100,000 characters. Pasted code is processed in memory and not stored. For private code, run the CLI locally instead.
127
+
128
+ ---
129
+
130
+ ## GitHub Actions
131
+
132
+ Two workflows ship in [.github/workflows/](https://github.com/Appemout/costLint/tree/main/.github/workflows):
133
+
134
+ - **[`costlint.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint.yml)**: on every PR (PRs without Python changes pass immediately), it:
135
+ - scans the added or modified files, leaving out `tests/` and `samples/`;
136
+ - posts the report as a PR comment;
137
+ - **fails the check if there are high-severity findings**.
138
+
139
+ To actually block merging, mark the `costlint` check as **required** in your branch protection rules.
140
+ - **[`costlint-comment.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint-comment.yml)**: posts the comment for PRs from forks, whose token is read-only. It runs in the base repo, never executes fork code, and only comments if the PR's head commit matches the commit that was scanned. It takes effect once it's on the default branch.
141
+
142
+ [`tests.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/tests.yml) runs the test suite on Python 3.10–3.13.
143
+
144
+ ### Use CostLint in your own repository
145
+
146
+ The `costlint.yml` above installs CostLint from this repository's own checkout. In your repo, add `.github/workflows/costlint.yml`:
147
+
148
+ ```yaml
149
+ name: CostLint
150
+ on: pull_request
151
+ permissions:
152
+ contents: read
153
+
154
+ jobs:
155
+ costlint:
156
+ runs-on: ubuntu-latest
157
+ steps:
158
+ - uses: actions/checkout@v7
159
+ with:
160
+ fetch-depth: 0
161
+ - uses: actions/setup-python@v7
162
+ with:
163
+ python-version: '3.12'
164
+ - run: pip install "costlint==0.3.0" # pin the version for reproducible builds
165
+ - name: Scan changed Python files
166
+ env:
167
+ BASE_REF: ${{ github.base_ref }}
168
+ run: |
169
+ git diff -z --name-only --diff-filter=AM "origin/${BASE_REF}...HEAD" -- '*.py' > changed_files.txt
170
+ if [ -s changed_files.txt ]; then
171
+ costlint scan --files-from changed_files.txt --no-ai --fail-on-high
172
+ else
173
+ echo "No Python files changed"
174
+ fi
175
+ ```
176
+
177
+ The check fails when there are high-severity findings. To post the report as a PR comment, copy the comment steps from this repo's [`costlint.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint.yml) and [`costlint-comment.yml`](https://github.com/Appemout/costLint/blob/main/.github/workflows/costlint-comment.yml).
178
+
179
+ ---
180
+
181
+ ## Python API
182
+
183
+ ```python
184
+ import asyncio
185
+ from costlint.scanner import scan_source, scan_path
186
+ from costlint.estimator import estimate_costs, load_assumptions
187
+ from costlint.patcher import generate_patch
188
+
189
+ findings = scan_path("src/") # or scan_source(code, "file.py")
190
+ findings, summary = estimate_costs(findings, runs_per_month=25_000)
191
+ print(summary.estimated_monthly_waste_usd, summary.estimated_monthly_recoverable_usd)
192
+
193
+ # Custom assumptions
194
+ findings, summary = estimate_costs(findings, assumptions=load_assumptions("pricing.json"))
195
+
196
+ # Patch one file (dry_run=True: TODO comments only, no AI)
197
+ source = open("src/agent.py", encoding="utf-8").read()
198
+ file_findings = [f for f in findings if f.file_path.endswith("agent.py")]
199
+ patch = asyncio.run(generate_patch("src/agent.py", source, file_findings, dry_run=True))
200
+ print(patch.unified_diff)
201
+ ```
202
+
203
+ > `CostSummary` field names changed in 0.2.0. The old names (`estimated_current_monthly_usd`, `estimated_optimized_monthly_usd`, `estimated_monthly_savings_usd`, `savings_percentage`) still work as deprecated aliases.
204
+
205
+ ---
206
+
207
+ ## Development
208
+
209
+ ```bash
210
+ pip install -e ".[dev]"
211
+ pytest -q # 193 tests, all offline (the Copilot SDK is faked)
212
+ python -m py_compile app.py
213
+ ```
214
+
215
+ ```
216
+ costLint/
217
+ ├── src/costlint/
218
+ │ ├── scanner.py # AST rules CL001–CL005
219
+ │ ├── estimator.py # cost model + --pricing overrides
220
+ │ ├── patcher.py # dry-run and Copilot SDK patching
221
+ │ ├── cli.py # `costlint scan` (also `python -m costlint`)
222
+ │ └── models.py # Pydantic v2 schemas
223
+ ├── app.py # Streamlit UI
224
+ ├── samples/ # leaky and clean example agents
225
+ ├── tests/
226
+ └── docs/
227
+ ├── COST_MODEL.md # formulas and assumptions
228
+ ├── REAL_WORLD_TESTING.md # results on 33 public agent repos
229
+ ├── RELEASING.md # how to publish to PyPI
230
+ ├── KNOWN_ISSUES.md # issue register and resolutions
231
+ ├── FIX_PLAN.md
232
+ └── archive/ # original spec and build logs (historical)
233
+ ```
234
+
235
+ ---
236
+
237
+ ## License
238
+
239
+ MIT, see [LICENSE](https://github.com/Appemout/costLint/blob/main/LICENSE).
240
+
241
+ Issues and discussion: [github.com/Appemout/costLint/issues](https://github.com/Appemout/costLint/issues)
@@ -0,0 +1,69 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "costlint"
7
+ version = "0.3.0"
8
+ description = "CostLint — Pre-merge AI token cost & loop safety linter for Python"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ {name = "Madhav"}
15
+ ]
16
+ keywords = ["ai", "llm", "cost", "tokens", "linter", "static-analysis", "openai", "anthropic", "copilot", "agents"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Software Development :: Libraries",
28
+ "Topic :: Software Development :: Quality Assurance",
29
+ ]
30
+
31
+ dependencies = [
32
+ "pydantic>=2.7.0",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ # The Copilot SDK supports Python 3.11+; on 3.10 live patching falls back to TODO comments.
37
+ ai = ["microsoft-copilot-sdk>=2.0.4,<3; python_version >= '3.11'"]
38
+ ui = ["streamlit>=1.38.0"]
39
+ dev = [
40
+ "pytest>=8.0.0",
41
+ "pytest-asyncio>=0.24.0",
42
+ ]
43
+ all = [
44
+ "microsoft-copilot-sdk>=2.0.4,<3; python_version >= '3.11'",
45
+ "streamlit>=1.38.0",
46
+ "pytest>=8.0.0",
47
+ "pytest-asyncio>=0.24.0",
48
+ ]
49
+
50
+ [project.scripts]
51
+ costlint = "costlint.cli:main"
52
+
53
+ [project.urls]
54
+ Homepage = "https://github.com/Appemout/costLint"
55
+ Documentation = "https://github.com/Appemout/costLint#readme"
56
+ Changelog = "https://github.com/Appemout/costLint/blob/main/CHANGELOG.md"
57
+ Repository = "https://github.com/Appemout/costLint.git"
58
+ Issues = "https://github.com/Appemout/costLint/issues"
59
+
60
+ [tool.setuptools]
61
+ packages = ["costlint"]
62
+ package-dir = {"" = "src"}
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests"]
66
+ python_files = "test_*.py"
67
+ python_classes = "Test*"
68
+ python_functions = "test_*"
69
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """CostLint — Pre-Merge AI Token Cost & Loop Safety Linter."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,6 @@
1
+ """CLI entry point for CostLint."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()