diff --git a/.github/workflows/email-report.yml b/.github/workflows/email-report.yml index 8b751c3..02511ef 100644 --- a/.github/workflows/email-report.yml +++ b/.github/workflows/email-report.yml @@ -99,7 +99,7 @@ jobs: if [ "${{ inputs.only_private }}" = "true" ]; then args+=(--only-private) fi - profile_args=(--max-repos 50 --email-format html --warn-over 25 --warn-over 80%) + profile_args=(--max-repos 100 --email-format html --warn-over 25 --warn-over 80%) if [ ${#profile_args[@]} -gt 0 ]; then args+=("${profile_args[@]}") fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 99ad94f..967d36a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema ### Fixed +- **Artifact storage partial failures:** a per-repo artifact API error no longer blanks the whole Actions Artifact Storage section — successfully scanned repos still render, and failed repos are listed as skipped in the text/HTML email and PDF exports. - **Email Actions section:** plain-text and HTML emails show **private-repo quota** against the 2,000 min / 500 MB free tier (with public usage labeled free) instead of comparing combined account totals to the private quota. When no visibility split is available, the report says so explicitly rather than implying the total is all quota-counted. - **Copilot AI credits:** email report data now reads GitHub's `…/billing/ai_credit/usage` endpoint (preferred over legacy premium-request usage after Copilot's 2026 metering change) and labels the email Copilot section and forecast row accordingly; org-licensed Copilot without personal usage gets an explanatory note. Usage displays **credit quantities** (`grossQuantity`) rather than dollar `netAmount`, which is often zero on included allowance. Failed usage API calls surface as report errors or notes instead of looking like zero usage. Forecast exports (CSV/XLSX/PDF/legacy) use the same Copilot metric label as email. - **Security CI (`pip-audit`):** bump locked `pypdf` to 6.21.4+ (CVE-2026-119203–209) so the weekly `Security` workflow passes again. @@ -36,6 +37,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema ### Changed +- **Email report repo cap in GitHub Actions:** raised the scheduled workflow's `--max-repos` from 50 to 100 so repo-level sections cover more of the account (aligning with the CLI/config default). Repos beyond the previous cap were excluded from the private/public Actions split and top-repository rankings; the cap still applies above 100 repos, and repo-level sections now make roughly twice as many REST calls (about 210 of the 5,000/hr core quota with consumers + artifact storage). - **Shorter README:** focused the landing page on getting started and scheduled delivery; moved setup, email configuration, report/export reference, runs/drift, and development details into linked user guides under `docs/`. - **README positioning and quick start:** refreshed the project overview around automated reporting, cost visibility, actionable repository detail, and flexible outputs. Added a scheduled-email quick start; clarified the independent GitHub Actions and local macOS launchd delivery paths, token permissions, platform scope, and planned work; and aligned the package description with this positioning. diff --git a/TO_DO.md b/TO_DO.md index 36d6817..fa05a35 100644 --- a/TO_DO.md +++ b/TO_DO.md @@ -14,6 +14,7 @@ ## Email Report Follow-Ups - [ ] Add cached or persisted artifact/release storage snapshots so monthly email reports can compare storage details over time. +- [ ] Surface per-repo artifact scan errors in CSV/XLSX exports and the "Unavailable Data" sections (currently only the text/HTML email and PDF list skipped repos), and add per-repo error handling to `get_release_asset_details` (one repo failure still aborts that whole section via `_try_section`). ## Actions / Local Full Report @@ -30,6 +31,7 @@ - [ ] Rename internal `legacy_*` modules/symbols to “local full report” naming (`legacy_report_data` → e.g. `local_report_data`, cache `kind="legacy"`, CLI/TUI internals, tests). User-facing copy already says “local full report”; this is the code rename. Keep a thin `legacy` compatibility shim if external imports still need it. - [ ] Add tests to raise overall src coverage from the current ~76% to 80%. Update `scripts/coverage-check` default from `COVERAGE_TOTAL_MIN=75` to `80` once achieved. +- [ ] Port the manual `pip install -e .` comment + `# NOSONAR` in `.github/workflows/email-report.yml` into `email-report.yml.template` so the next setup regeneration does not silently drop the Sonar suppression. ## Configuration & Setup diff --git a/docs/superpowers/plans/2026-11-09-api-call-tracking.md b/docs/superpowers/plans/2026-11-09-api-call-tracking.md new file mode 100644 index 0000000..3c8df25 --- /dev/null +++ b/docs/superpowers/plans/2026-11-09-api-call-tracking.md @@ -0,0 +1,434 @@ +> **Status:** IN PROGRESS + +> Line numbers cited below are accurate as of 2026-11-09; relocate by anchor (function / section title / dict key) if they drift. +> +> **Terminology:** user-facing name is **local full report** (CLI/TUI). Code modules still use `legacy_*` until the rename tracked in `TO_DO.md`. +> +> **Implementation log:** (none yet) + +# Track GitHub REST API Calls and Report Usage + +## Goal + +Count the GitHub REST API requests a report actually makes, and surface +actual-vs-estimated usage in every report surface: the email report (text and +HTML), the legacy terminal report, and all file exports (JSON, CSV, XLSX, PDF, +text). Keep the existing pre-fetch estimate for the quota guard. + +## Non-goals + +- Counting GraphQL calls (this project only uses REST). +- Re-architecting the report data model. The change should extend the existing + `api_estimate` dict, not introduce a parallel structure. +- Changing the email report's quota-guard behavior. +- Fixing the unrelated "50 of 51" truncation-message lower bound (see + Related follow-ups). + +## Current state + +- `GitHubAPI` (`src/github_usage/api.py`) has `request()` and `request_raw()`; + `get_all_pages()` calls `request_raw()` once per page. Neither counts calls. +- `http_retry.request_with_retries()` (`src/github_usage/http_retry.py`) hides + retry attempts from the caller. +- `report_data.build_report_data()` computes `estimate_api_request_count()` + before fetching (`report_optional.py:125`) and stores it as + `report["api_estimate"]`. It never measures actual usage. +- `legacy_report_data.build_legacy_report_data()` does the same with + `estimate_legacy_api_request_count()` (`legacy_report_data.py:141`). +- The email renderers only print `api_estimate["notes"]` + (`email_report_text.py:445`, `email_report_html.py:491`). The numeric fields + (`estimated_incremental_requests`, `core_remaining`, + `estimated_percent_of_remaining`) are not rendered. +- Exports serialize `data` as-is: JSON includes `api_estimate`; CSV/XLSX/PDF + have explicit section lists and currently omit it; text delegates to the + email formatter. +- `report_cache.CACHE_VERSION` is 3. Cached reports are reused without + re-fetching, so a cache hit makes 0 new API calls but still carries the + original fetch's `api_estimate`. + +## Design + +### 1. Counting layer + +Add a small request counter to `GitHubAPI` (`src/github_usage/api.py`): + +- `self.request_count: int = 0` — logical API calls (each `request()` and + `request_raw()` invocation, including each page of `get_all_pages()`). +- `self.request_log: list[dict[str, object]]` — always populated; bounded by + the report's own request count (worst case ~600-700 entries at + `max_repos=100` with all sections, tens of KB). Each entry: + `{"method": "GET", "path": "/user/repos", "status": 200}`. Record the entry + in a `finally` block with the status captured (or `None` on failure) so + failed calls stay in both the total and the breakdown. +- `self.http_attempts: int = 0` — optional stretch goal for retry attempts + (see Open questions). If deferred, label the rendered number "requests + issued (retries excluded)". +- `get_request_stats() -> dict[str, object]` — returns + `{"actual_requests": int, "actual_requests_by_resource": dict}`. + Resource categories are derived from the path with ordered matching + (billing before user, because `/users/.../billing/...` starts with `/user`): + - `billing`: `/users/{u}/settings/billing/...` (`billing.py:24,92,139,176`) + - `user`: `/user`, `/user/repos` (`report_data.py:179`) + - `rate_limit`: `/rate_limit` (`report_data.py:259`) + - `actions`: `/repos/{o}/{n}/actions/...` (`report_optional.py:70`, + `storage.py:138`, `report_workflow_minutes.py:28,38`) + - `repos`: `/repos/{o}/{n}/releases` and other repo paths + (`report_optional.py:99`, `storage.py:156`) + - `other`: anything else + Assert in tests that `sum(actual_requests_by_resource.values()) == + actual_requests`. + +Increment at the top of `request()` and `request_raw()` so failed calls are +counted too (they generally consume quota). Do not count the internal +`/rate_limit` fetch differently; it is a normal API call. `request_log` must +never enter the report dict: raw paths would bypass `redact.py`'s key-based +username/repo masking (`redact.py:31-42,72-81`) and leak the username into +file exports. + +Thread safety: no threads in `src`; GUI `@work(thread=True)` workers each +build their own client (`gui_backend.py:361`). A plain `int` is sufficient; +note the assumption in a comment. If a client is ever shared across threads, +add a `threading.Lock` then. + +### 2. Report data integration + +Add a helper in `report_data.py`: + +```python +def _api_request_stats(api) -> dict[str, object]: + stats = getattr(api, "get_request_stats", None) + if callable(stats): + return stats() + return {"actual_requests": int(getattr(api, "request_count", 0) or 0), + "actual_requests_by_resource": {}} +``` + +This keeps the `GitHubAPIClient` Protocol (`report_data.py:22`) unchanged and +avoids breaking test fakes that do not implement the new method. + +**Baseline and variance.** `estimated_incremental_requests` covers only the +optional repo-level sections for the email builder +(`report_optional.py:137-143`), and for the legacy builder the optional +sections plus `account_level = 10` +(`legacy_report_data.py:141-161`) — while the client's raw count includes +every call made before and during the builder (e.g. `/user`, `_limited_repos`, +`_rate_limit`, and for the legacy CLI path the pre-builder `check_user_scope` / +`fetch_account_info` / `fetch_rate_limits` in `legacy_report.py:94-101`). +Comparing the raw total to the estimate is apples-to-oranges. Instead, define +one matching window per estimate and subtract a full stats snapshot: + +- The **baseline is the full `get_request_stats()` snapshot** (total + + per-resource), captured before the first call the estimate covers. +- `total_requests = current_total` — the raw client total, used for + original-fetch messages (not comparable to the estimate). +- `actual_requests` must cover exactly the calls the estimate covers — no + more. Snapshot the counter immediately around each repo-level getter and + sum the per-getter deltas field-by-field + (`actual_requests_by_resource[res] = sum(after[res] - before[res])`). + The resource deltas must reconcile: assert in tests that + `sum(actual_requests_by_resource.values()) == actual_requests`. +- `estimate_variance = actual_requests - estimated_incremental_requests`. +- Document the window in the report dict (e.g. `estimate_scope`). + +Matching windows (baseline capture points): + +- `build_report_data`: capture a `window_baseline` **in-builder, immediately + after `_rate_limit(api)`** (`report_data.py:374`) for `total_requests` + context. But the email estimate covers only the optional repo-level + sections, while the window also contains account-level section fetches + (`get_actions_usage`, `get_copilot_usage`, `get_gitlfs_usage`, + `get_monthly_costs` — e.g. an LFS-only report estimates 0 while making ≥4 + calls there). So `actual_requests` comes only from snapshots taken around + the repo-level getters (`get_repo_consumers`, + `get_artifact_storage_details`, `get_release_asset_details`, + `workflow_breakdown_for_top_private`, and the + `fetch_repo_actions_table` fallback at `report_data.py:435`), summed as + above. The quota guard still uses the pre-fetch estimate vs + `core_remaining`, unchanged. The caller must not pass an earlier snapshot + here. +- `build_legacy_report_data`: the legacy estimate's `account_level = 10` + covers account-level calls including `/user` and `/rate_limit`, which in the + CLI path happen **before** the builder is invoked + (`fetch_account_info` / `fetch_rate_limits`, `legacy_report.py:99-101`). + A builder-entry baseline would miss them while the estimate counts them. + So: add an optional `baseline_stats: dict | None = None` parameter; + `run_legacy_report_session` captures the snapshot before its first + API-calling operation (`check_user_scope`, which GETs `/user` when no user + payload is passed) and passes it in. The GUI path + (`gui_backend.run_legacy_report_data`, `gui_backend.py:361-368`) shares + `_init_github_api`, which issues its own pre-builder `GET /user` on the + fresh client (`cli_email_report.py:83`) — so a builder-entry default + snapshot would exclude that call while the CLI window includes its + pre-builder calls. The GUI caller must therefore supply a baseline + captured before initialization (a fresh-client zero snapshot is + equivalent), never the entry default, preserving comparable counts with + the CLI. When `baseline_stats` is None (direct builder use), the builder + snapshots at entry and records the narrower scope (`estimate_scope`) so + the variance stays honest. + Carve `_limited_repos()` out of `actual_requests`: snapshot the counter + around that call (`legacy_report_data.py:234`) and subtract those + repository-listing page fetches from the delta — including from + `actual_requests_by_resource`, in whichever bucket(s) the listing pages + were recorded in, so the reconciliation assertion still holds. Neither + estimate models listing pagination, so a second `/user/repos` page at + 101+ repos must not move the variance. (The email builder needs no + carve-out: its baseline is already post-listing, and its `actual_requests` + is a sum of per-repo-getter deltas rather than a window delta.) + +Merge points (must be after the last fetch): +- `build_report_data`: immediately before + `report["insights"] = get_key_insights(report)` (`report_data.py:441`) — + after the `fetch_repo_actions_table(api, repos)` fallback at line 435. +- `build_legacy_report_data`: at the end, before line 360 — after + `copilot_premium` / `copilot_billing` / `lfs_billing` (lines 345-358). + +Add derived fields to `api_estimate`: + +- `actual_requests`: measured delta over the estimate's matching window — + repo-level-only for the email builder, account-level-inclusive for the + legacy builder (each matching what its estimate covers). The only figure + compared against the estimate; `estimate_scope` says which window applies, + so renderers must never label legacy measurements as repo-level-only. +- `total_requests`: raw client total for original-fetch messages (not + comparable to the estimate). +- `actual_requests_by_resource`: per-resource repo-level deltas over the same + window (must sum to `actual_requests`). +- `estimate_scope`: which window the numbers cover + (e.g. `"repo-sections-only"` vs `"full-report-including-account-level"`). +- `estimate_variance`: `actual_requests - estimated_incremental_requests`. +- `core_remaining_before`: already present as `core_remaining`. +- `core_remaining_after`: optional; only if a post-fetch `/rate_limit` call is + made (see Open questions). If made, exclude that probe from + `actual_requests` or label it. +- `from_cache`: set by the cache-hit path (see section 3). + +Keep `estimated_incremental_requests` as the pre-fetch estimate. The email and +exports can then show both numbers. + +### 3. Cache interaction + +A cache hit must not claim the original fetch's API usage as new usage, and +must not destroy the cached measurement either. + +- Add a small `annotate_cache_hit(data)` helper (e.g. in `report_cache.py`) + that sets `data["api_estimate"]["from_cache"] = True`. Leave both counts + intact; renderers print `total_requests` as the original-fetch total, e.g. + "0 new API requests (M total during the original fetch; N in estimate + scope)". Never present the window delta as the full-fetch total. +- Call it from all three cache-hit sites: + 1. `cli_email_report._load_or_fetch_email_data()` + 2. `legacy_report.run_legacy_report_session()` + 3. `gui_backend.run_legacy_report_data()` (`gui_backend.py:358`) — currently + returns cached data unannotated, so the GUI legacy table would label a + cache hit as a live fetch. +- Do not put the annotation inside `load_cached_report`: `test_report_cache.py:65` + asserts `loaded == data`. +- Bump `report_cache.CACHE_VERSION` from 3 to 4. Reason: the report shape + changes, and v3 snapshots would otherwise render as live fetches with 0 + actuals. `test_report_cache.py:131` already covers `CACHE_VERSION - 1` + rejection. + +### 4. Reporting surfaces + +Add a shared formatter module `src/github_usage/report_api_usage.py` with one +pure lines function plus a shared rows adapter, matching the existing +`email_actions_table_rows` convention (`_email_report_common.py:30-39`): + +- `api_usage_lines(estimate: dict) -> list[str]` +- `api_usage_rows(estimate: dict) -> list[tuple[str, str]]` derived from the + lines (label/value pairs for HTML tables, CSV, XLSX, PDF). + +Suggested content (compact): + +``` +REST API Usage +- Requests in estimate scope: 123 (estimated 120) +- Total requests this fetch: 130 +- Core quota remaining before: 4,877 / 5,000 +- Core rate limit: 5,000 requests/hour (authenticated) — https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api +- By resource (estimate scope): billing 20, repos 1, actions 100, rate_limit 1, other 1 +- Source: live fetch +``` + +The scope label comes from `estimate_scope`: email renderers qualify it as +repo-level scope (`Repo-level requests in estimate scope:`), legacy renderers +as account-level-inclusive scope. + +On a cache hit: `- Source: cached report (0 new API requests; 130 total during the original fetch)`. + +Surface-by-surface: + +- **Email text** (`email_report_text.py`): do NOT add a new + `_SECTION_FORMATTERS` entry — the quota notes are rendered after the loop + (`email_report_text.py:445-448`). Extend the existing "REST API Quota + Notes" block to include the usage lines above the notes. +- **Email HTML** (`email_report_html.py`): likewise extend + `_html_api_notes_block()` (`email_report_html.py:434-442`) rather than + adding a new `_SECTION_HTML_FORMATTERS` entry. Render the usage rows in the + existing `