ukaf-cli 0.1.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.
- ukaf/__init__.py +8 -0
- ukaf/__main__.py +4 -0
- ukaf/cli.py +88 -0
- ukaf/data/cursor.toml +148 -0
- ukaf/delivery.py +268 -0
- ukaf/dora.py +62 -0
- ukaf/github_api.py +286 -0
- ukaf/i18n.py +119 -0
- ukaf/mcp_server.py +70 -0
- ukaf/money.py +34 -0
- ukaf/pricing.py +172 -0
- ukaf/recommend.py +357 -0
- ukaf/reconcile.py +185 -0
- ukaf/render_html.py +584 -0
- ukaf/reporting.py +50 -0
- ukaf/serialize.py +340 -0
- ukaf/story.py +459 -0
- ukaf/timeutil.py +65 -0
- ukaf/usage.py +150 -0
- ukaf_cli-0.1.0.dist-info/METADATA +213 -0
- ukaf_cli-0.1.0.dist-info/RECORD +25 -0
- ukaf_cli-0.1.0.dist-info/WHEEL +5 -0
- ukaf_cli-0.1.0.dist-info/entry_points.txt +3 -0
- ukaf_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- ukaf_cli-0.1.0.dist-info/top_level.txt +1 -0
ukaf/github_api.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Fetch pull requests from the GitHub REST API and normalize them.
|
|
2
|
+
|
|
3
|
+
Offline runs use a JSON fixture instead. This module is only on the live path.
|
|
4
|
+
The token is read from the environment and is never written into the report.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
|
|
16
|
+
from ukaf.delivery import Pull, pull_from_dict
|
|
17
|
+
|
|
18
|
+
API = "https://api.github.com"
|
|
19
|
+
LINK_RE = re.compile(r'<([^>]+)>;\s*rel="([^"]+)"')
|
|
20
|
+
AGENT_HINT = re.compile(r"\b(?:bc-[0-9a-fA-F-]{8,}|agent-[a-z0-9][a-z0-9-]*)\b")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GitHubError(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def fetch_pulls(
|
|
28
|
+
repos: list[str],
|
|
29
|
+
*,
|
|
30
|
+
token: str | None = None,
|
|
31
|
+
since: str | None = None,
|
|
32
|
+
until: str | None = None,
|
|
33
|
+
max_pulls: int = 30,
|
|
34
|
+
timeout: float = 30,
|
|
35
|
+
) -> list[Pull]:
|
|
36
|
+
auth = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
|
37
|
+
if not auth:
|
|
38
|
+
raise GitHubError("Set GITHUB_TOKEN or GH_TOKEN, or pass --github-fixture for an offline run.")
|
|
39
|
+
pulls: list[Pull] = []
|
|
40
|
+
for repo in repos:
|
|
41
|
+
pulls.extend(_repo_pulls(repo, auth, since=since, until=until, max_pulls=max_pulls, timeout=timeout))
|
|
42
|
+
return pulls
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _repo_pulls(
|
|
46
|
+
repo: str,
|
|
47
|
+
token: str,
|
|
48
|
+
*,
|
|
49
|
+
since: str | None,
|
|
50
|
+
until: str | None,
|
|
51
|
+
max_pulls: int,
|
|
52
|
+
timeout: float,
|
|
53
|
+
) -> list[Pull]:
|
|
54
|
+
owner_repo = repo.strip().removeprefix("https://github.com/").strip("/")
|
|
55
|
+
if owner_repo.count("/") != 1:
|
|
56
|
+
raise GitHubError(f"expected owner/name, got {repo!r}")
|
|
57
|
+
collected: list[Pull] = []
|
|
58
|
+
url = f"{API}/repos/{owner_repo}/pulls?state=closed&sort=updated&direction=desc&per_page=50"
|
|
59
|
+
while url and len(collected) < max_pulls:
|
|
60
|
+
payload, next_url = _get_json(url, token, timeout)
|
|
61
|
+
if not isinstance(payload, list):
|
|
62
|
+
raise GitHubError(f"unexpected pulls payload for {owner_repo}")
|
|
63
|
+
for item in payload:
|
|
64
|
+
if len(collected) >= max_pulls:
|
|
65
|
+
break
|
|
66
|
+
merged = item.get("merged_at")
|
|
67
|
+
created = item.get("created_at") or ""
|
|
68
|
+
if since and (merged or created) < since:
|
|
69
|
+
# Updated-desc means once we are past the window we can stop.
|
|
70
|
+
if (item.get("updated_at") or "") < since:
|
|
71
|
+
url = ""
|
|
72
|
+
break
|
|
73
|
+
continue
|
|
74
|
+
if until and created > until:
|
|
75
|
+
continue
|
|
76
|
+
if not merged and not item.get("closed_at"):
|
|
77
|
+
continue
|
|
78
|
+
number = int(item["number"])
|
|
79
|
+
detail = _as_dict(_get_json(f"{API}/repos/{owner_repo}/pulls/{number}", token, timeout)[0])
|
|
80
|
+
commits = _as_list(
|
|
81
|
+
_get_json(
|
|
82
|
+
f"{API}/repos/{owner_repo}/pulls/{number}/commits?per_page=100",
|
|
83
|
+
token,
|
|
84
|
+
timeout,
|
|
85
|
+
)[0]
|
|
86
|
+
)
|
|
87
|
+
files = _as_list(
|
|
88
|
+
_get_json(
|
|
89
|
+
f"{API}/repos/{owner_repo}/pulls/{number}/files?per_page=100",
|
|
90
|
+
token,
|
|
91
|
+
timeout,
|
|
92
|
+
)[0]
|
|
93
|
+
)
|
|
94
|
+
head = ((detail.get("head") or {}) if isinstance(detail.get("head"), dict) else {}).get("sha")
|
|
95
|
+
checks: list[dict] = []
|
|
96
|
+
if head:
|
|
97
|
+
check_doc = _as_dict(
|
|
98
|
+
_get_json(
|
|
99
|
+
f"{API}/repos/{owner_repo}/commits/{head}/check-runs?per_page=100",
|
|
100
|
+
token,
|
|
101
|
+
timeout,
|
|
102
|
+
)[0]
|
|
103
|
+
)
|
|
104
|
+
checks = [row for row in _as_list(check_doc.get("check_runs")) if isinstance(row, dict)]
|
|
105
|
+
deployments = _deployments_for(owner_repo, head, token, timeout) if head else []
|
|
106
|
+
issue_created = _linked_issue_created(owner_repo, detail, token, timeout)
|
|
107
|
+
collected.append(
|
|
108
|
+
pull_from_dict(
|
|
109
|
+
owner_repo,
|
|
110
|
+
_to_fixture(detail, commits, files, checks, deployments, issue_created),
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
url = next_url if url else ""
|
|
114
|
+
return collected
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _deployments_for(repo: str, sha: str, token: str, timeout: float) -> list[dict]:
|
|
118
|
+
listing = _as_list(_get_json(f"{API}/repos/{repo}/deployments?sha={sha}&per_page=20", token, timeout)[0])
|
|
119
|
+
rows: list[dict] = []
|
|
120
|
+
for deploy in listing:
|
|
121
|
+
if not isinstance(deploy, dict):
|
|
122
|
+
continue
|
|
123
|
+
statuses = _as_list(
|
|
124
|
+
_get_json(
|
|
125
|
+
f"{API}/repos/{repo}/deployments/{deploy['id']}/statuses?per_page=10",
|
|
126
|
+
token,
|
|
127
|
+
timeout,
|
|
128
|
+
)[0]
|
|
129
|
+
)
|
|
130
|
+
state = "pending"
|
|
131
|
+
updated = deploy.get("updated_at") or deploy.get("created_at")
|
|
132
|
+
for status in statuses:
|
|
133
|
+
if isinstance(status, dict):
|
|
134
|
+
state = str(status.get("state") or state)
|
|
135
|
+
updated = status.get("created_at") or updated
|
|
136
|
+
break
|
|
137
|
+
rows.append(
|
|
138
|
+
{
|
|
139
|
+
"environment": deploy.get("environment") or "production",
|
|
140
|
+
"state": state,
|
|
141
|
+
"created_at": deploy.get("created_at"),
|
|
142
|
+
"updated_at": updated,
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
return rows
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _linked_issue_created(repo: str, pull: dict, token: str, timeout: float) -> str | None:
|
|
149
|
+
body = str(pull.get("body") or "")
|
|
150
|
+
match = re.search(r"(?:fix(?:es|ed)?|clos(?:es|ed)|resolv(?:es|ed))\s+#(\d+)", body, re.I)
|
|
151
|
+
if not match:
|
|
152
|
+
return None
|
|
153
|
+
number = match.group(1)
|
|
154
|
+
try:
|
|
155
|
+
issue = _as_dict(_get_json(f"{API}/repos/{repo}/issues/{number}", token, timeout)[0])
|
|
156
|
+
except GitHubError:
|
|
157
|
+
return None
|
|
158
|
+
if "pull_request" in issue:
|
|
159
|
+
return None
|
|
160
|
+
created = issue.get("created_at")
|
|
161
|
+
return str(created) if created else None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _to_fixture(
|
|
165
|
+
pull: dict,
|
|
166
|
+
commits: list,
|
|
167
|
+
files: list,
|
|
168
|
+
checks: list,
|
|
169
|
+
deployments: list,
|
|
170
|
+
issue_created: str | None,
|
|
171
|
+
) -> dict:
|
|
172
|
+
user = pull.get("user") or {}
|
|
173
|
+
author = user.get("login") if isinstance(user, dict) else "unknown"
|
|
174
|
+
base = pull.get("base") or {}
|
|
175
|
+
messages = []
|
|
176
|
+
commit_rows = []
|
|
177
|
+
for commit in commits:
|
|
178
|
+
if not isinstance(commit, dict):
|
|
179
|
+
continue
|
|
180
|
+
commit_info = commit.get("commit") or {}
|
|
181
|
+
message = ""
|
|
182
|
+
if isinstance(commit_info, dict):
|
|
183
|
+
message = str(commit_info.get("message") or "")
|
|
184
|
+
author_block = commit_info.get("author") or {}
|
|
185
|
+
when = author_block.get("date") if isinstance(author_block, dict) else None
|
|
186
|
+
else:
|
|
187
|
+
when = None
|
|
188
|
+
messages.append(message)
|
|
189
|
+
if when:
|
|
190
|
+
commit_rows.append({"committed_at": when, "message": message})
|
|
191
|
+
blob = "\n".join([str(pull.get("body") or ""), *messages])
|
|
192
|
+
agent_ids = sorted(set(AGENT_HINT.findall(blob)))
|
|
193
|
+
file_rows = []
|
|
194
|
+
for item in files:
|
|
195
|
+
if not isinstance(item, dict):
|
|
196
|
+
continue
|
|
197
|
+
file_rows.append(
|
|
198
|
+
{
|
|
199
|
+
"filename": item.get("filename"),
|
|
200
|
+
"additions": item.get("additions") or 0,
|
|
201
|
+
"deletions": item.get("deletions") or 0,
|
|
202
|
+
"status": item.get("status") or "modified",
|
|
203
|
+
}
|
|
204
|
+
)
|
|
205
|
+
check_rows = []
|
|
206
|
+
for item in checks:
|
|
207
|
+
if not isinstance(item, dict):
|
|
208
|
+
continue
|
|
209
|
+
check_rows.append(
|
|
210
|
+
{
|
|
211
|
+
"name": item.get("name"),
|
|
212
|
+
"conclusion": item.get("conclusion"),
|
|
213
|
+
"started_at": item.get("started_at"),
|
|
214
|
+
"completed_at": item.get("completed_at"),
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
return {
|
|
218
|
+
"number": pull.get("number"),
|
|
219
|
+
"title": pull.get("title"),
|
|
220
|
+
"url": pull.get("html_url"),
|
|
221
|
+
"author": author,
|
|
222
|
+
"created_at": pull.get("created_at"),
|
|
223
|
+
"merged_at": pull.get("merged_at"),
|
|
224
|
+
"closed_at": pull.get("closed_at"),
|
|
225
|
+
"base_ref": base.get("ref") if isinstance(base, dict) else "main",
|
|
226
|
+
"issue_created_at": issue_created,
|
|
227
|
+
"body": pull.get("body") or "",
|
|
228
|
+
"agent_ids": agent_ids,
|
|
229
|
+
"reverted": _looks_reverted(str(pull.get("title") or "")),
|
|
230
|
+
"commits": commit_rows,
|
|
231
|
+
"check_runs": check_rows,
|
|
232
|
+
"deployments": deployments,
|
|
233
|
+
"files": file_rows,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _looks_reverted(title: str) -> bool:
|
|
238
|
+
return bool(re.match(r"revert\b", title.strip(), re.I))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _get_json(url: str, token: str, timeout: float) -> tuple[object, str]:
|
|
242
|
+
request = urllib.request.Request(
|
|
243
|
+
url,
|
|
244
|
+
headers={
|
|
245
|
+
"Accept": "application/vnd.github+json",
|
|
246
|
+
"Authorization": f"Bearer {token}",
|
|
247
|
+
"User-Agent": "ukaf-cli",
|
|
248
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
249
|
+
},
|
|
250
|
+
)
|
|
251
|
+
try:
|
|
252
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
253
|
+
link = response.headers.get("Link") or ""
|
|
254
|
+
body = response.read().decode("utf-8")
|
|
255
|
+
except urllib.error.HTTPError as exc:
|
|
256
|
+
detail = exc.read().decode("utf-8", errors="replace")[:300]
|
|
257
|
+
raise GitHubError(f"GitHub {exc.code} for {url.split('?')[0]}: {detail}") from exc
|
|
258
|
+
except urllib.error.URLError as exc:
|
|
259
|
+
raise GitHubError(f"GitHub request failed: {exc.reason}") from exc
|
|
260
|
+
next_url = ""
|
|
261
|
+
for target, rel in LINK_RE.findall(link):
|
|
262
|
+
if rel == "next":
|
|
263
|
+
next_url = target
|
|
264
|
+
return json.loads(body), next_url
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _as_dict(value: object) -> dict:
|
|
268
|
+
if isinstance(value, dict):
|
|
269
|
+
return value
|
|
270
|
+
raise GitHubError("expected a JSON object from GitHub")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _as_list(value: object) -> list:
|
|
274
|
+
if isinstance(value, list):
|
|
275
|
+
return value
|
|
276
|
+
return []
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def redact_token(text: str) -> str:
|
|
280
|
+
"""Drop anything that looks like a token before it reaches a report or log."""
|
|
281
|
+
return re.sub(r"gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+", "[token]", text)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def iter_repos(values: list[str]) -> Iterator[str]:
|
|
285
|
+
for value in values:
|
|
286
|
+
yield value.strip()
|
ukaf/i18n.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""English by default, Hebrew when --lang he. Numbers stay in Western digits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
STRINGS: dict[str, dict[str, str]] = {
|
|
6
|
+
"en": {
|
|
7
|
+
"checks": "checks",
|
|
8
|
+
"hero_first": "What the agents spent",
|
|
9
|
+
"hero_last": "and what shipped",
|
|
10
|
+
"export_list": "Export list price",
|
|
11
|
+
"export_billed": "Export billed",
|
|
12
|
+
"per_feature": "List per feature",
|
|
13
|
+
"stage_story": "Stages that add up",
|
|
14
|
+
"stage_caption": "List-price spend builds from planning through fixes. Add overhead to reach the full export total.",
|
|
15
|
+
"tier_story": "What does each size of change cost?",
|
|
16
|
+
"priciest_day": "What drove the priciest day?",
|
|
17
|
+
"daily_caption": "Daily list-price spend on dates with usage (UTC).",
|
|
18
|
+
"daily_details": "Daily spend details",
|
|
19
|
+
"daily_baseline": "Median active day",
|
|
20
|
+
"standard_spend": "Other list-price spend",
|
|
21
|
+
"fast_on_peak": "Fast at list price",
|
|
22
|
+
"no_daily": "No daily usage data available.",
|
|
23
|
+
"report_details": "Explore the report details",
|
|
24
|
+
"dir": "ltr",
|
|
25
|
+
"lang": "en",
|
|
26
|
+
"title": "What the agents spent, and what shipped",
|
|
27
|
+
"kicker": "ukaf",
|
|
28
|
+
"planning": "Planning / spec",
|
|
29
|
+
"development": "Development",
|
|
30
|
+
"testing": "Testing / CI",
|
|
31
|
+
"deploy": "Deploy + acceptance",
|
|
32
|
+
"fixes": "Fixes",
|
|
33
|
+
"overhead": "Overhead / unattributed",
|
|
34
|
+
"list": "List price",
|
|
35
|
+
"billed": "Billed",
|
|
36
|
+
"tokens": "Tokens",
|
|
37
|
+
"events": "Events",
|
|
38
|
+
"duration": "Duration",
|
|
39
|
+
"stage": "Stage",
|
|
40
|
+
"feature": "Feature",
|
|
41
|
+
"total": "Total",
|
|
42
|
+
"reconciliation": "Reconciliation",
|
|
43
|
+
"pass": "PASS",
|
|
44
|
+
"fail": "FAIL",
|
|
45
|
+
"recommendations": "What to change",
|
|
46
|
+
"action": "Action",
|
|
47
|
+
"evidence": "Evidence",
|
|
48
|
+
"impact": "Impact",
|
|
49
|
+
"dora": "Delivery (DORA)",
|
|
50
|
+
"tiers": "Cost by complexity",
|
|
51
|
+
"models": "The same total, split by model",
|
|
52
|
+
"sponsor": "Sponsor the work",
|
|
53
|
+
"assumptions": "How the numbers were made",
|
|
54
|
+
"features_heading": "Features",
|
|
55
|
+
"waterfall": "Adding up to the export",
|
|
56
|
+
"rubric": "Complexity rubric",
|
|
57
|
+
},
|
|
58
|
+
"he": {
|
|
59
|
+
"checks": "בדיקות",
|
|
60
|
+
"hero_first": "מה הסוכנים הוציאו",
|
|
61
|
+
"hero_last": "ומה נמסר",
|
|
62
|
+
"export_list": "מחירון לייצוא",
|
|
63
|
+
"export_billed": "חיוב לייצוא",
|
|
64
|
+
"per_feature": "מחירון לפיצ׳ר",
|
|
65
|
+
"stage_story": "שלבים שמתחברים לסכום",
|
|
66
|
+
"stage_caption": "ההוצאה במחיר מחירון מצטברת מתכנון ועד תיקונים. התקורה משלימה לסכום הייצוא.",
|
|
67
|
+
"tier_story": "כמה עולה שינוי בכל גודל?",
|
|
68
|
+
"priciest_day": "מה עלה הכי הרבה ביום היקר ביותר?",
|
|
69
|
+
"daily_caption": "הוצאה יומית במחיר מחירון בימים עם שימוש (UTC).",
|
|
70
|
+
"daily_details": "פירוט הוצאה יומית",
|
|
71
|
+
"daily_baseline": "חציון ימי שימוש",
|
|
72
|
+
"standard_spend": "יתר ההוצאה במחיר מחירון",
|
|
73
|
+
"fast_on_peak": "Fast במחיר מחירון",
|
|
74
|
+
"no_daily": "אין נתוני שימוש יומיים.",
|
|
75
|
+
"report_details": "פרטי הדוח",
|
|
76
|
+
"dir": "rtl",
|
|
77
|
+
"lang": "he",
|
|
78
|
+
"title": "מה הסוכנים הוציאו, ומה נמסר",
|
|
79
|
+
"kicker": "ukaf",
|
|
80
|
+
"planning": "תכנון ומפרט",
|
|
81
|
+
"development": "פיתוח",
|
|
82
|
+
"testing": "בדיקות ו-CI",
|
|
83
|
+
"deploy": "פריסה וקבלה",
|
|
84
|
+
"fixes": "תיקונים",
|
|
85
|
+
"overhead": "תקורה לא משויכת",
|
|
86
|
+
"list": "מחיר מחירון",
|
|
87
|
+
"billed": "חויב בפועל",
|
|
88
|
+
"tokens": "טוקנים",
|
|
89
|
+
"events": "אירועים",
|
|
90
|
+
"duration": "משך",
|
|
91
|
+
"stage": "שלב",
|
|
92
|
+
"feature": "פיצ'ר",
|
|
93
|
+
"total": "סה״כ",
|
|
94
|
+
"reconciliation": "בדיקת התאמה",
|
|
95
|
+
"pass": "עבר",
|
|
96
|
+
"fail": "נכשל",
|
|
97
|
+
"recommendations": "מה לשנות",
|
|
98
|
+
"action": "פעולה",
|
|
99
|
+
"evidence": "ראיה",
|
|
100
|
+
"impact": "השפעה",
|
|
101
|
+
"dora": "מסירה (DORA)",
|
|
102
|
+
"tiers": "עלות לפי מורכבות",
|
|
103
|
+
"models": "אותו סה״כ, בחלוקה לפי מודל",
|
|
104
|
+
"sponsor": "תמכו בעבודה",
|
|
105
|
+
"assumptions": "איך המספרים חושבו",
|
|
106
|
+
"features_heading": "פיצ'רים",
|
|
107
|
+
"waterfall": "החיבור עד לייצוא",
|
|
108
|
+
"rubric": "מחוון מורכבות",
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def t(lang: str, key: str) -> str:
|
|
114
|
+
table = STRINGS.get(lang) or STRINGS["en"]
|
|
115
|
+
return table.get(key) or STRINGS["en"][key]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def stage_label(lang: str, name: str) -> str:
|
|
119
|
+
return t(lang, name)
|
ukaf/mcp_server.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Local stdio tools for coding-agent spend and delivery metrics."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated, Literal
|
|
5
|
+
|
|
6
|
+
from mcp.server.mcpserver import MCPServer
|
|
7
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
8
|
+
from pydantic import Field
|
|
9
|
+
|
|
10
|
+
from ukaf import __version__
|
|
11
|
+
from ukaf.delivery import load_fixture
|
|
12
|
+
from ukaf.reporting import Analysis, analyze, load_events, write_report
|
|
13
|
+
|
|
14
|
+
server = MCPServer("ukaf", version=__version__)
|
|
15
|
+
|
|
16
|
+
UsageCSV = Annotated[str, Field(description="Local path to the Cursor usage CSV export.")]
|
|
17
|
+
GitHubFixture = Annotated[str, Field(description="Local path to the GitHub pull-request JSON fixture.")]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _analyze(usage_csv: str, github_fixture: str | None, pricing: str | None = None) -> Analysis:
|
|
21
|
+
try:
|
|
22
|
+
events = load_events(Path(usage_csv), Path(pricing) if pricing is not None else None)
|
|
23
|
+
pulls = load_fixture(Path(github_fixture)) if github_fixture is not None else []
|
|
24
|
+
return analyze(events, pulls)
|
|
25
|
+
except (OSError, ValueError, AttributeError, KeyError, TypeError) as exc:
|
|
26
|
+
raise ToolError(f"Could not analyze usage and pull requests: {exc}") from exc
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@server.tool(structured_output=True)
|
|
30
|
+
def build_report(
|
|
31
|
+
usage_csv: UsageCSV,
|
|
32
|
+
out_dir: Annotated[str, Field(description="Local directory for report.html, report.json, and report.md.")],
|
|
33
|
+
github_fixture: GitHubFixture | None = None,
|
|
34
|
+
lang: Literal["en", "he"] = "en",
|
|
35
|
+
pricing: Annotated[
|
|
36
|
+
str | None, Field(description="Local pricing TOML path. Defaults to the bundled rate card.")
|
|
37
|
+
] = None,
|
|
38
|
+
) -> dict[str, object]:
|
|
39
|
+
"""Write an HTML, JSON, and Markdown report and return their paths and totals.
|
|
40
|
+
|
|
41
|
+
Without a GitHub fixture, all usage is reported as overhead.
|
|
42
|
+
"""
|
|
43
|
+
analysis = _analyze(usage_csv, github_fixture, pricing)
|
|
44
|
+
try:
|
|
45
|
+
paths, document = write_report(analysis, Path(out_dir), lang=lang)
|
|
46
|
+
except (OSError, ValueError) as exc:
|
|
47
|
+
raise ToolError(f"Could not write report: {exc}") from exc
|
|
48
|
+
return {"paths": {extension: str(path) for extension, path in paths.items()}, "totals": document["totals"]}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@server.tool(structured_output=True)
|
|
52
|
+
def cost_per_feature(usage_csv: UsageCSV, github_fixture: GitHubFixture) -> list[dict[str, object]]:
|
|
53
|
+
"""Return each PR's list and billed cost, additive stage split, and complexity tier."""
|
|
54
|
+
return _analyze(usage_csv, github_fixture).document(lang="en")["features"]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@server.tool(structured_output=True)
|
|
58
|
+
def recommendations(usage_csv: UsageCSV, github_fixture: GitHubFixture) -> list[dict[str, object]]:
|
|
59
|
+
"""Return ranked recommendations with evidence and estimated monthly impact."""
|
|
60
|
+
return _analyze(usage_csv, github_fixture).document(lang="en")["recommendations"]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@server.tool(structured_output=True)
|
|
64
|
+
def dora_summary(usage_csv: UsageCSV, github_fixture: GitHubFixture) -> dict[str, object]:
|
|
65
|
+
"""Return deployment frequency, median lead time, change failure rate, and time to restore."""
|
|
66
|
+
return _analyze(usage_csv, github_fixture).document(lang="en")["dora"]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def run() -> None:
|
|
70
|
+
server.run(transport="stdio")
|
ukaf/money.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Integer micro-dollars so partitioned costs add up with no float residue."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import ROUND_HALF_EVEN, Decimal
|
|
6
|
+
|
|
7
|
+
MICRO = 1_000_000
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def usd_to_micro(amount: Decimal) -> int:
|
|
11
|
+
"""Round half-even to the nearest 1e-6 dollar."""
|
|
12
|
+
return int((amount * Decimal(MICRO)).quantize(Decimal("1"), rounding=ROUND_HALF_EVEN))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def money(micro: int) -> str:
|
|
16
|
+
"""Format micro-dollars as $W.FFFFFF (exact, six fractional digits)."""
|
|
17
|
+
sign = "-" if micro < 0 else ""
|
|
18
|
+
micro = abs(micro)
|
|
19
|
+
whole, frac = divmod(micro, MICRO)
|
|
20
|
+
return f"{sign}${whole}.{frac:06d}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def mul_div_half_even(numer_a: int, numer_b: int, denom: int) -> int:
|
|
24
|
+
"""Return numer_a * numer_b / denom, rounded half-even to an integer."""
|
|
25
|
+
if denom <= 0:
|
|
26
|
+
raise ZeroDivisionError("denom")
|
|
27
|
+
num = numer_a * numer_b
|
|
28
|
+
negative = num < 0
|
|
29
|
+
num = abs(num)
|
|
30
|
+
q, r = divmod(num, denom)
|
|
31
|
+
twice = r * 2
|
|
32
|
+
if twice > denom or (twice == denom and q % 2 == 1):
|
|
33
|
+
q += 1
|
|
34
|
+
return -q if negative else q
|
ukaf/pricing.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""List-price a usage row from the pricing table. Billed cost stays on the row."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ukaf.money import usd_to_micro
|
|
11
|
+
|
|
12
|
+
PACKAGE_PRICING = Path(__file__).resolve().parent / "data" / "cursor.toml"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Rates:
|
|
17
|
+
"""USD per million tokens."""
|
|
18
|
+
|
|
19
|
+
input: Decimal
|
|
20
|
+
cache_write: Decimal
|
|
21
|
+
cache_read: Decimal
|
|
22
|
+
output: Decimal
|
|
23
|
+
fast: bool
|
|
24
|
+
non_fast: str | None
|
|
25
|
+
priced_as: str
|
|
26
|
+
note: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class PriceCard:
|
|
31
|
+
models: dict[str, dict]
|
|
32
|
+
aliases: dict[str, str]
|
|
33
|
+
default: dict
|
|
34
|
+
token_rate_per_mtok: Decimal
|
|
35
|
+
token_rate_exempt: frozenset[str]
|
|
36
|
+
native_prefixes: tuple[str, ...]
|
|
37
|
+
|
|
38
|
+
def resolve(self, model: str) -> Rates:
|
|
39
|
+
seen: list[str] = []
|
|
40
|
+
name = model
|
|
41
|
+
for _ in range(4):
|
|
42
|
+
if name in self.models:
|
|
43
|
+
raw = self.models[name]
|
|
44
|
+
non_fast = raw.get("non_fast")
|
|
45
|
+
return Rates(
|
|
46
|
+
input=_dec(raw["input"]),
|
|
47
|
+
cache_write=_dec(raw.get("cache_write", raw["input"])),
|
|
48
|
+
cache_read=_dec(raw["cache_read"]),
|
|
49
|
+
output=_dec(raw["output"]),
|
|
50
|
+
fast=bool(raw.get("fast", False)),
|
|
51
|
+
non_fast=str(non_fast) if non_fast else None,
|
|
52
|
+
priced_as=name,
|
|
53
|
+
note=str(raw.get("note") or ""),
|
|
54
|
+
)
|
|
55
|
+
if name in seen:
|
|
56
|
+
break
|
|
57
|
+
seen.append(name)
|
|
58
|
+
aliased = self.aliases.get(name)
|
|
59
|
+
if not aliased:
|
|
60
|
+
break
|
|
61
|
+
name = aliased
|
|
62
|
+
raw = self.default
|
|
63
|
+
return Rates(
|
|
64
|
+
input=_dec(raw["input"]),
|
|
65
|
+
cache_write=_dec(raw.get("cache_write", raw["input"])),
|
|
66
|
+
cache_read=_dec(raw["cache_read"]),
|
|
67
|
+
output=_dec(raw["output"]),
|
|
68
|
+
fast=bool(raw.get("fast", False)) or _looks_fast(model),
|
|
69
|
+
non_fast=None,
|
|
70
|
+
priced_as="default",
|
|
71
|
+
note=str(raw.get("note") or ""),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def eligible_for_token_rate(self, model: str, priced_as: str) -> bool:
|
|
75
|
+
if priced_as in self.token_rate_exempt or model in self.token_rate_exempt:
|
|
76
|
+
return False
|
|
77
|
+
for prefix in self.native_prefixes:
|
|
78
|
+
if model.startswith(prefix) or priced_as.startswith(prefix):
|
|
79
|
+
return False
|
|
80
|
+
return True
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def default_pricing_path() -> Path:
|
|
84
|
+
return PACKAGE_PRICING
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def load_pricing(path: Path | None = None) -> PriceCard:
|
|
88
|
+
file = path or PACKAGE_PRICING
|
|
89
|
+
with file.open("rb") as handle:
|
|
90
|
+
doc = tomllib.load(handle)
|
|
91
|
+
rate = doc.get("token_rate") or {}
|
|
92
|
+
exempt = rate.get("exempt") or []
|
|
93
|
+
prefixes = rate.get("native_prefixes") or []
|
|
94
|
+
return PriceCard(
|
|
95
|
+
models=dict(doc.get("models") or {}),
|
|
96
|
+
aliases={str(k): str(v) for k, v in (doc.get("aliases") or {}).items()},
|
|
97
|
+
default=dict(doc["default"]),
|
|
98
|
+
token_rate_per_mtok=_dec(rate.get("usd_per_mtok", "0")),
|
|
99
|
+
token_rate_exempt=frozenset(str(x) for x in exempt),
|
|
100
|
+
native_prefixes=tuple(str(x) for x in prefixes),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class Priced:
|
|
106
|
+
list_micro: int
|
|
107
|
+
non_fast_list_micro: int
|
|
108
|
+
fast: bool
|
|
109
|
+
priced_as: str
|
|
110
|
+
used_default: bool
|
|
111
|
+
note: str
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def price_tokens(
|
|
115
|
+
card: PriceCard,
|
|
116
|
+
model: str,
|
|
117
|
+
*,
|
|
118
|
+
cache_write: int,
|
|
119
|
+
input_tokens: int,
|
|
120
|
+
cache_read: int,
|
|
121
|
+
output_tokens: int,
|
|
122
|
+
max_mode: bool,
|
|
123
|
+
team_token_rate: bool,
|
|
124
|
+
) -> Priced:
|
|
125
|
+
rates = card.resolve(model)
|
|
126
|
+
listed = _tokens_usd(rates, cache_write, input_tokens, cache_read, output_tokens)
|
|
127
|
+
if rates.fast and rates.non_fast:
|
|
128
|
+
base = card.resolve(rates.non_fast)
|
|
129
|
+
counter = _tokens_usd(base, cache_write, input_tokens, cache_read, output_tokens)
|
|
130
|
+
else:
|
|
131
|
+
counter = listed
|
|
132
|
+
if max_mode:
|
|
133
|
+
listed *= Decimal("1.2")
|
|
134
|
+
counter *= Decimal("1.2")
|
|
135
|
+
if team_token_rate and card.eligible_for_token_rate(model, rates.priced_as):
|
|
136
|
+
volume = Decimal(cache_write + input_tokens + cache_read + output_tokens)
|
|
137
|
+
extra = volume * card.token_rate_per_mtok / Decimal(1_000_000)
|
|
138
|
+
listed += extra
|
|
139
|
+
counter += extra
|
|
140
|
+
return Priced(
|
|
141
|
+
list_micro=usd_to_micro(listed),
|
|
142
|
+
non_fast_list_micro=usd_to_micro(counter),
|
|
143
|
+
fast=rates.fast,
|
|
144
|
+
priced_as=rates.priced_as,
|
|
145
|
+
used_default=rates.priced_as == "default",
|
|
146
|
+
note=rates.note,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _tokens_usd(
|
|
151
|
+
rates: Rates,
|
|
152
|
+
cache_write: int,
|
|
153
|
+
input_tokens: int,
|
|
154
|
+
cache_read: int,
|
|
155
|
+
output_tokens: int,
|
|
156
|
+
) -> Decimal:
|
|
157
|
+
million = Decimal(1_000_000)
|
|
158
|
+
return (
|
|
159
|
+
Decimal(cache_write) * rates.cache_write
|
|
160
|
+
+ Decimal(input_tokens) * rates.input
|
|
161
|
+
+ Decimal(cache_read) * rates.cache_read
|
|
162
|
+
+ Decimal(output_tokens) * rates.output
|
|
163
|
+
) / million
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _dec(value: object) -> Decimal:
|
|
167
|
+
return Decimal(str(value))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _looks_fast(model: str) -> bool:
|
|
171
|
+
name = model.lower()
|
|
172
|
+
return "-fast" in name or name.endswith("fast")
|