Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/email-report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ jobs:
- uses: actions/setup-python@v7
with:
python-version: '3.12'
# Editable install of this repo's own package. pip does not read uv.lock;
# the core package currently declares no runtime dependencies, so nothing
# else is resolved here.
# Editable install of this repo's own package. It declares no runtime
# dependencies, but pip still resolves the setuptools>=77.0.3 build
# backend in an isolated env (not from uv.lock).
- run: pip install -e . # NOSONAR
- name: Send email report
env:
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/email-report.yml.template
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ jobs:
- uses: actions/setup-python@v7
with:
python-version: '3.12'
- run: pip install -e .
# Editable install of this repo's own package. It declares no runtime
# dependencies, but pip still resolves the setuptools>=77.0.3 build
# backend in an isolated env (not from uv.lock).
- run: pip install -e . # NOSONAR
- name: Send email report
env:
GH_USAGE_TOKEN: ${{ secrets.GH_USAGE_TOKEN }}
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ This project follows the structure from Keep a Changelog and intends to use Sema

### Added

- **Measured REST API usage in reports** ([plan](docs/superpowers/plans/archived/2026-11-09-api-call-tracking.md)): email quota blocks, terminal output, CSV/XLSX/PDF exports, and TUI detail rows report measured-vs-estimated GitHub REST API requests — scope requests vs the pre-fetch estimate, total requests issued (retries excluded), core quota remaining at report start, the core rate limit with a docs link, a per-resource breakdown, and the live/cached source (JSON `api_estimate` carries the same measured data; the 5,000/hour fallback and documentation link are added by the rendered sections only). Report cache version bumped to 4 (stale v3 snapshots rejected).
- **Known-vulnerable Actions check:** new `vulnerable-actions` job in the `Security` workflow runs zizmor's `known-vulnerable-actions` audit on every PR, push to `main`, and the weekly schedule, failing on any action reference with a GitHub security advisory. Covers SHA-pinned actions (e.g. `gitleaks-action`), which Dependabot alerts never flag; fails loudly if the audit itself errors or `GH_TOKEN` is empty.
- **Coverage, complexity, and module-size gates:** `scripts/coverage-check` runs the unittest suite under `coverage` (scoped to `src/github_usage`). Overall src coverage must stay ≥ `COVERAGE_TOTAL_MIN` (default 75; current ~76%). Any **new** `src` file (not in the committed tree) must meet `COVERAGE_FILE_MIN` (default 82%) so coverage cannot erode one file at a time; existing files are protected by the overall gate only. `scripts/check-complexity` fails if the worst cyclomatic complexity exceeds `MAX_CC` (default 28; current worst) and warns at `WARN_LINES`=575 / blocks at `BLOCK_LINES`=650 for module size (current largest 562). Both scripts are wired into `scripts/check`, added as pre-push hooks in `.pre-commit-config.yaml`, and coverage runs as its own `coverage` job in `ci.yml`. `coverage` and `radon` added to the `dev` extra; `uv.lock` regenerated.
- **Private-repo top consumers** ([plan](docs/superpowers/plans/archived/2026-07-31-private-top-consumers.md)): local full report (terminal + TUI), email text/HTML, and JSON exports gain private-only top lists for Actions minutes and billed storage alongside existing overall rankings; overall top-by-storage (billed avg MB) and artifact-scan private lists where they add signal. Shared `repo_consumers.py` helper with `private_list_is_redundant` guards; report cache version bumped to 3. HTML table helpers extracted to `_email_report_html_tables.py`.
Expand Down
2 changes: 1 addition & 1 deletion TO_DO.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@

- [ ] Refactor `src/github_usage/setup_config.py` (507 lines, over the 500-line limit per `scripts/check-sizes`). Extract a focused submodule — e.g. profile schema/loading (`load_report_profiles`, `find_profile`, `ensure_profiles`, `_default_profile`) and/or the TOML writer helpers (`_emit_*_block`, `write_config`) — to bring the file back under the threshold. Also watch `setup_wizard.py` (461 lines) and the `_manage_profiles()`/`_run_email_report()` functions, which are approaching their limits.
- [ ] 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.
- [ ] Extract the remaining API-usage tracking orchestration from the report builders (`report_data.py` 487 lines, `legacy_report_data.py` 395 lines — both at/over the early-extraction threshold). Keep the merge math in `report_api_usage.py`; move section-fetch orchestration (`_fetch_sections`, `_fetch_legacy_billing_sections`) into a focused submodule so the builders stay thin. Flagged in review on PR #39; deferred to keep that PR's diff small.

- [ ] 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

Expand Down
2 changes: 1 addition & 1 deletion docs/email-reports.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ The email command supports the options below. Run `./start.sh email-report --hel
- Missing GitHub `user` scope: billing endpoints may return 404. Fix GitHub CLI auth with `gh auth refresh -h github.com -s user`, or use a PAT with the `user` scope.
- GitHub Actions token confusion: use `GH_USAGE_TOKEN`, not the automatic `GITHUB_TOKEN`.
- Resend domain unverified: set `RESEND_FROM` to an address on a verified Resend domain.
- Rate limiting: reduce frequency, lower `--max-repos`, avoid repo-level options, or use skip flags.
- Rate limiting: reduce frequency, lower `--max-repos`, avoid repo-level options, or use skip flags. The report's REST API Usage section shows how many requests each run issued — on a cache hit it shows the request count from the original fetch, since the current run issued none; see [Reports and exports](reports.md).
- Consumer breakdown truncation: increase `--max-repos` cautiously.
- Artifact storage request cost: `--include-artifact-storage` can add roughly one REST API request per scanned repository.
- Release asset inventory: `--include-release-assets` can add roughly one REST API request per scanned repository and requires explicit confirmation.
Expand Down
7 changes: 6 additions & 1 deletion docs/reports.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ After [authenticating](setup.md#authentication), run a local full report with `.

`--include-consumers`, `--include-artifact-storage`, and `--include-release-assets` add repo-level API calls. They consume GitHub REST API request quota, not Actions minutes, Actions storage, Copilot requests, Git LFS quota, or billable GitHub usage. Use monthly schedules and conservative `--max-repos` values for accounts with many repositories.

Every report also measures its own REST API footprint. Email quota blocks, terminal output, CSV/XLSX/PDF exports, and TUI detail rows carry a **REST API Usage** section: measured requests in the estimate scope vs the pre-fetch estimate, total requests issued (retries excluded), core quota remaining at report start, the core rate limit (live limit when available, else GitHub's documented 5,000/hour) with a link to [GitHub's rate-limit docs](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api), a per-resource breakdown, and the source (live fetch, or cached report with the original-fetch total). The JSON `api_estimate` object carries the same measured data, including the live `core_limit` when the snapshot succeeded; the 5,000/hour fallback and the documentation link are added by the rendered sections only. Counts are logical requests issued, not raw HTTP attempts — retries are excluded.

With `--include-consumers` (local full report and email), the **repo consumers** sections rank repositories by Actions usage alongside the existing combined top-by-minutes and top-by-cost lists:

- **Overall top-by-storage** — billed Actions storage ranked by average MB (`storage_avg_mb` from the billing API).
Expand Down Expand Up @@ -62,7 +64,10 @@ exporting). Export redaction is partial; see [Privacy](#privacy) before sharing
- **CSV** writes a UTF-8 BOM at the start of the file for Excel-on-Windows
compatibility.
- **JSON** preserves the full `ReportData` dict, including the `api_estimate`
metadata. Datetime values are emitted as ISO-8601 strings.
metadata (measured `actual_requests` / `total_requests`,
`actual_requests_by_resource`, `estimate_variance`, `estimate_scope` when
the window is explicit, `from_cache`). Datetime values are emitted as
ISO-8601 strings.
- **XLSX** uses one sheet per major report section. Sheet names are truncated
to 31 characters (Excel limit). Values starting with `=`, `+`, `-`, or `@`
are prefixed with a single quote to prevent Excel formula injection.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
> **Status:** IN PROGRESS
> **Status:** COMPLETE

> 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)
> **Implementation log:** Chunk 1 complete 2026-11-11 — `GitHubAPI` request
> counting (`request_count`, `request_log`, ordered resource buckets) plus
> `get_request_stats()` and unit tests; reviewed APPROVE with minor findings
> folded in (structural sum==total, segment-based actions match, TypedDicts,
> dense zeroed buckets, normalized-path/params/404 tests). Chunk 2 complete
> 2026-11-11 — `report_api_usage.py` shared lines/rows formatters with scope
> labels, rate-limit reference line, and cache-hit message; 9 unit tests at
> 100% file coverage. Chunk 3 complete 2026-11-11 — builder merge with
> per-getter tracking, caller-passed legacy baselines with listing carve-out,
> `annotate_cache_hit` at all three cache sites, `CACHE_VERSION` 4, and
> CountingFakeAPI + builder/helper/cache-hit tests (831 tests green).
> Chunk-3 review (deepseek, APPROVE, no blockers): most findings were already
> satisfied by the implementation (caller-baseline and session tests, fallback
> `other`-bucket, extracted `_merge_legacy_api_estimate`, sorted buckets,
> multi-page `page_counts`, GUI test placement); applied the remainder —
> fallback non-dict/count-combined tests, section-level abort coverage,
> redaction assertions, `_track_repo_calls`/`deltas` typing, legacy docstring.
> Chunk 4 complete 2026-11-11 — email text/HTML quota blocks, legacy terminal
> renderer, CSV/XLSX/PDF sections, GUI detail rows; 15 new tests; deepseek
> APPROVE with follow-ups applied. Grok pre-PR review (high, plan mode):
> REQUEST CHANGES with one major (PDF label-column overprint — fixed with
> label/value split rows) and one minor (static rate-limit list docs link —
> fixed); committed as follow-up. Docs complete 2026-11-11 —
> `reports.md`, `email-reports.md`, CHANGELOG `Added` entry, full
> `scripts/check` green; plan archived.

# Track GitHub REST API Calls and Report Usage

Expand Down Expand Up @@ -163,8 +187,9 @@ Matching windows (baseline capture points):
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.
snapshots at entry and records no scope, so renderers use the neutral
scope label instead of implying full-report coverage (the entry window is
narrower than the full estimate span).
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
Expand Down Expand Up @@ -234,28 +259,38 @@ 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
- `api_usage_lines(estimate: dict | None) -> list[str]`
- `api_usage_rows(estimate: dict | None) -> 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
- Repo requests in estimate scope: 123 (estimated 120)
- Total requests this fetch (retries excluded): 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
- 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): actions 100, billing 20, repos 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.
The scope label comes from `estimate_scope`: email renderers show
`Repo requests in estimate scope:`, legacy renderers show
`All requests in estimate scope:`, and unknown scopes fall back to the
neutral `Requests in estimate scope:`. Scope strings live as
`SCOPE_REPO_SECTIONS` / `SCOPE_FULL_REPORT` constants in
`report_api_usage.py` so builders import them instead of re-typing.
Formatters return no lines when the estimate carries no measurement keys,
zero-count buckets are omitted from the breakdown, and all strings are
ASCII-only (the PDF writer uses core Helvetica, which has no em dash).

On a cache hit: `- Source: cached report (0 new API requests; 130 total during the original fetch)`.

Cached rendering keeps the original measurement on the scope line; only the
total line is relabeled. (Recorded 2026-11-11: do not zero the scope line —
chunk 4 must preserve this.)

Surface-by-surface:

- **Email text** (`email_report_text.py`): do NOT add a new
Expand Down Expand Up @@ -408,19 +443,69 @@ which already lists static rate-limit numbers, to include the same docs link.

## Task breakdown

- [ ] Add `GitHubAPI` request counting + `get_request_stats()`; unit tests.
- [ ] Add `report_api_usage.py` (lines + rows adapter); cover the new file's 82%
- [x] Add `GitHubAPI` request counting + `get_request_stats()`; unit tests.
**Done:** 2026-11-11 — counter, per-resource log, and stats merged in
`api.py`; 9 unit tests (incl. failure/transport, pagination, buckets);
reviewer minors applied (no functional deviations).
- [x] Add `report_api_usage.py` (lines + rows adapter); cover the new file's 82%
coverage gate.
- [ ] Merge repo-level-delta actual usage into `api_estimate` in both builders
(email: per-getter snapshots around repo-level getters; legacy:
caller-passed `baseline_stats` full-snapshot subtraction incl. per-resource);
bump `CACHE_VERSION` (plus the test pin); add `annotate_cache_hit()` at all
three sites; tests.
- [ ] Extend the email text/HTML quota blocks; legacy terminal; CSV/XLSX/PDF;
**Done:** 2026-11-11 — shared `api_usage_lines`/`api_usage_rows` with scope
labels, quota/rate-limit/breakdown/source lines; 9 unit tests at 100% file
coverage.
**Review:** deepseek APPROVE with follow-ups applied — ASCII-only strings
(PDF-safe), absent-measurement gate returning no lines, zero-bucket filter,
cached total label, shared `SCOPE_*` constants, shorter PDF-safe labels.
- [x] Merge repo-level-delta actual usage into `api_estimate` in both builders
(email: per-getter snapshots around repo-level getters, using the shared
`SCOPE_*` constants for `estimate_scope`; legacy: caller-passed
`baseline_stats` full-snapshot subtraction incl. per-resource, minus the
`_limited_repos` listing calls); bump `CACHE_VERSION` (plus the test pin);
add `annotate_cache_hit()` at all three sites; tests.
**Done:** 2026-11-11 — per-getter `_track_repo_calls` + `_sum_repo_deltas`
merge in both builders; legacy caller-passed `baseline_stats` with listing
carve-out and omitted scope on entry fallback; `annotate_cache_hit` at all
three cache sites; `CACHE_VERSION` 4 + pin update; CountingFakeAPI (incl.
multi-page listings) + builder/helper/cache-hit integration tests (incl.
caller-baseline, 2-page invariance, session coverage, section-failure
fallback).
**Review:** deepseek APPROVE with follow-ups folded in — `_api_request_stats`
fallback buckets unknowns under `other`; merge helpers consolidated in
`report_api_usage.py` (report_data.py stays under the 500-line budget);
non-dict snapshots tolerated; exact-bucket test assertions kept where they
pin the dense contract; legacy None-baseline omits (rather than invents) a
scope value.
**Review 2:** deepseek APPROVE (no blockers) with minors applied — caller-
baseline test proves pre-builder inclusion; `_merge_legacy_api_estimate`
extracted to `report_api_usage.py` (~163→~140-line builder); section-level
abort path tested with fallback re-run; `annotate_cache_hit` covered at all
three call sites via integration tests; `_track_repo_calls`/`deltas` typed;
monotonicity documented; GUI test module ordering fixed.
- [x] Extend the email text/HTML quota blocks; legacy terminal; CSV/XLSX/PDF;
GUI legacy detail rows; add the rate-limit reference line + docs link;
tests.
- [ ] Docs (`docs/reports.md`, `docs/email-reports.md`), changelog,
tests. Chunk-4 decisions (locked): keep the cached scope line as the original
measurement (only the total line is relabeled); gate the extended quota
block on `notes or usage lines` so measured reports with zero notes still
render; label totals as requests-issued (retries excluded); HTML docs URL
stays plain text (matches text body; mail clients autolink); terminal keeps
both quota lines (usage block stays self-contained); PDF renders every entry
as a label line followed by its value line (fixed-width cells can't wrap).
**Review:** deepseek APPROVE with follow-ups applied — ruff-format fixes,
per-surface docs-link assertions, uniform PDF label/value split (no
overprint), shared "REST API Usage" naming, `_track_repo_calls` typing,
moved GUI cache test above the `__main__` guard.
**Pre-PR review (grok 4.7 high, plan mode):** REQUEST CHANGES with one
major (PDF 60 mm label column overprints the total-request counts —
fixed by rendering every API-usage entry as a label line followed by a
full-width value line, plus `add_section` full-width handling for
empty label/value rows) and one minor (static `render_what_else`
rate-limit list missing the docs link — fixed). Nits recorded as
follow-ups, not blockers.
- [x] Docs (`docs/reports.md`, `docs/email-reports.md`), changelog,
`scripts/check`, and a final review.
**Done:** 2026-11-11 — REST API Usage section documented in `reports.md`
(JSON `api_estimate` fields enumerated), rate-limit troubleshooting pointer
in `email-reports.md`, CHANGELOG `Added` entry under `[Unreleased]`;
`scripts/check` and `scripts/docs-check` green.

## Related follow-ups (out of scope here)

Expand Down
Loading
Loading