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 `
` (or a small table) before the notes.
+- **Legacy terminal** (`legacy_terminal.py`): add
+ `render_api_usage(data.get("api_estimate"))` next to
+ `render_rate_limits(...)`. Implement the printer in
+ `report_api_usage.py` (or `report_account.py`). Add a case to
+ `test_legacy_terminal.py`.
+- **JSON export** (`export_json.py`): no code change needed; `api_estimate` is
+ already serialized. Add the new fields to the documented schema.
+- **CSV export** (`export_csv.py`): add `_write_api_usage_section(writer, data)`
+ to `_write_sections()` (`export_csv.py:61-86`), using the
+ `### Name ###` header convention (`export_csv.py:279-281`).
+- **XLSX export** (`export_xlsx.py`): add an "API Usage" sheet through the
+ `write_sheet(name, title, rows)` closure (`export_xlsx.py:62-75`), registered
+ in `_SECTION_WRITERS` (`export_xlsx.py:306`); place it first (near Metadata).
+- **PDF export** (`export_pdf.py`): add an "API Usage" page in
+ `_SECTION_PAGES` (`export_pdf.py:291`) rather than editing the cover; note
+ `_MAX_SECTION_ROWS = 30` (`export_pdf.py:30,59-71`) and `_fmt_num` for ints.
+- **Text export** (`export_text.py`): no code change; it delegates to
+ `format_report_email()`, so it inherits the email section.
+- **GUI**: `gui/views/email_report_view.py` inherits via
+ `run_email_dry_run` → `cli.main` → `format_report_email`
+ (`gui_backend.py:431`). The legacy report view does NOT:
+ `gui/views/report_view.py` renders through
+ `legacy_report_summary.legacy_report_detail_rows` (`report_view.py:277`), a
+ separate renderer with no `api_estimate` rows. Add the usage rows there and
+ a case to `test_legacy_report_summary.py`.
+- **`runs --api`**: out of scope for billing reports, but its `--json` output
+ could include the client's request count as a cheap follow-up.
+
+**Rate-limit reference line.** Every surface that shows API usage must include
+the current GitHub REST API primary limit and a link to the authoritative docs:
+
+`- GitHub core rate limit: 5,000 requests/hour (authenticated) — https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api`
+
+Use the live `core_limit` from `/rate_limit` when available (the report already
+fetches it) and fall back to the documented 5,000/hour value otherwise. As of
+November 2026 the documented primary limits are:
+
+- Authenticated requests: 5,000 requests/hour.
+- Unauthenticated requests: 60 requests/hour.
+- GitHub App installation tokens: 5,000/hour (15,000/hour for GitHub
+ Enterprise Cloud organizations).
+- Built-in `GITHUB_TOKEN` in GitHub Actions: 1,000/hour per repository
+ (15,000/hour for GHEC).
+- Search API: separate, more restrictive limits (30 requests/minute).
+- Secondary limits also apply (max 100 concurrent requests; 900 points/minute
+ for REST). `GET /rate_limit` does not count against the primary limit.
+
+Authoritative link: https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api
+
+Also update `report_account.render_what_else` (`report_account.py:144-152`),
+which already lists static rate-limit numbers, to include the same docs link.
+
+### 5. Protocol and test fakes
+
+- Leave `GitHubAPIClient` as-is and use `getattr` in `_api_request_stats`.
+- Update fakes in tests that assert on `api_estimate` to include the new keys.
+- Search for classes implementing `request`/`get_all_pages` in `tests/` and add
+ a `request_count` attribute where the new assertions need it.
+
+## Tests
+
+- `tests/test_api.py`: counter increments on `request()` and `request_raw()`;
+ `get_all_pages()` counts each page; `get_request_stats()` totals and
+ breakdown; failed calls still count; `sum(breakdown.values()) ==
+ actual_requests` even when a call fails.
+- `tests/test_report_data.py`: `build_report_data()` merges actual counts into
+ `api_estimate`; estimate fields remain; baseline delta is computed over the
+ matching window; partial-failure (`errors` non-empty) still merges counts and
+ keeps the pre-fetch estimate.
+- `tests/test_legacy_report_data.py`: same for the legacy builder, plus the
+ caller-passed `baseline_stats` path: a snapshot taken before the
+ pre-builder account/rate-limit fetches yields deltas covering the full
+ `account_level = 10` span, and per-resource deltas sum to `actual_requests`.
+- `tests/test_email_report_text.py` / `test_email_report_html.py`: extended
+ quota block renders actual, estimated, breakdown, and cache-hit variants.
+- `tests/test_export_csv.py`, `test_export_xlsx.py`, `test_export_pdf.py`:
+ new section/sheet renders.
+- `tests/test_legacy_terminal.py`: legacy terminal API usage section.
+- `tests/test_legacy_report_summary.py`: GUI legacy detail rows include usage.
+- `tests/test_report_cache.py`: cache hit annotates `from_cache` (and leaves
+ both counts); `CACHE_VERSION` bump invalidates old wrappers. Update the
+ `CACHE_VERSION` pin in `tests/test_report_optional.py:327`
+ (`CacheVersionTests.test_cache_version_is_3`) from 3 to 4 alongside the
+ bump, or `scripts/check` fails.
+- `tests/test_api.py` (or the new module's test): cover the `getattr` fallback
+ path (client without `get_request_stats`), the no-estimate case, the
+ `estimate_variance` sign / zero-estimate cases, and the listing carve-out:
+ a two-page `_limited_repos()` fetch must change `total_requests` while
+ leaving the variance against `estimate_legacy_api_request_count()`
+ untouched.
+- Fixtures `tests/fixtures/email_report_data.json:78` and
+ `tests/fixtures/export_report_data.json:97` lack the new keys; render with
+ `.get()` defaults so existing `assertIn`-style tests
+ (`test_email_report.py:16-29`) keep passing, or update the fixtures.
+- State that aggregated counts need no redaction; assert `request_log` never
+ enters the report dict.
+- Assert the original-fetch message uses `total_requests` (not the window
+ delta) in the email, legacy terminal, and export surfaces; assert the
+ estimate-scope delta is labeled separately.
+- Assert the rate-limit reference line and the docs link render in the email,
+ legacy terminal, and export surfaces.
+- New `report_api_usage.py` must clear the 82% new-file coverage gate
+ (`scripts/coverage-check`).
+- Run `scripts/check` (install the `gui` extra first if the environment lacks
+ `textual`).
+
+## Docs and changelog
+
+- `docs/reports.md:64-65` (JSON preserves `api_estimate`) and
+ `docs/email-reports.md:140-141` (request-cost framing): document the new
+ `api_estimate` fields and the API usage section.
+- `CHANGELOG.md`: add an `[Unreleased]` → `Added` entry.
+- This plan now lives in `docs/superpowers/plans/`; follow the repo's plan
+ lifecycle (status banner, archive to `archived/` when complete).
+
+## Open questions
+
+1. **Logical calls vs HTTP attempts.** Counting logical calls is simple and
+ matches the estimate. Retry attempts are invisible without threading a
+ counter through `http_retry` (one logical call can consume up to
+ `max_retries + 1` HTTP requests, `http_retry.py:113-118`). Recommendation:
+ ship logical calls first, label the number "requests issued (retries
+ excluded)", and add an `on_attempt` callback / `http_attempts` only if
+ users ask.
+2. **Post-fetch `/rate_limit`.** Fetching `/rate_limit` after the report gives
+ an exact `core_remaining_after` and `quota_consumed`, at the cost of one
+ extra request. Recommendation: make it an opt-in flag (default off); the
+ actual request count plus `core_remaining_before` is enough for the email.
+ If enabled, exclude the probe from `actual_requests` or label it.
+3. **Breakdown granularity.** By resource category is compact and useful; by
+ full path is noisy. Recommendation: resource category, always logged.
+4. **Cache-hit semantics.** Set `from_cache: True` and leave the original
+ count; renderers print "0 new requests (N during the original fetch)".
+5. **Naming.** Extend `api_estimate` with `actual_*` fields (recommended) vs a
+ new top-level `api_usage` key. Extending avoids two sources of truth.
+6. **Redundant `/rate_limit`.** `build_legacy_report_data` calls
+ `_rate_limit(api)` at `legacy_report_data.py:238` even when `rate_limits`
+ was already fetched and passed in (`legacy_report.py:101`). The new counter
+ will surface this; do not fix it here, but record it as a follow-up.
+
+## 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%
+ 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;
+ GUI legacy detail rows; add the rate-limit reference line + docs link;
+ tests.
+- [ ] Docs (`docs/reports.md`, `docs/email-reports.md`), changelog,
+ `scripts/check`, and a final review.
+
+## Related follow-ups (out of scope here)
+
+- The truncation note "Repository list truncated to 50 of 51 repositories" is a
+ lower bound (`max_repos + 1`), not the true repo count. Fixing it needs a
+ separate count or a full fetch.
+- The email "Top Repositories by Actions Minutes" list is capped at 5
+ (`get_repo_consumers(..., limit=5)`); raising `max_repos` does not raise the
+ top-N.
+- Redundant `/rate_limit` call in `build_legacy_report_data`
+ (`legacy_report_data.py:238`); the counter will surface it.
diff --git a/docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md b/docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md
new file mode 100644
index 0000000..ea49bab
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md
@@ -0,0 +1,136 @@
+> **Status:** IN PROGRESS
+
+> Line numbers cited below are accurate as of 2026-11-09; relocate by anchor (comment text / step name) 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)
+
+# Port Manual pip-install Comment + NOSONAR into email-report Template
+
+## Problem
+
+The committed workflow `.github/workflows/email-report.yml:72-75` carries a
+hand-added 3-line explanatory comment plus a `# NOSONAR` suppression on the
+`pip install -e .` step:
+
+```yaml
+ # 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.
+ - run: pip install -e . # NOSONAR
+```
+
+The generator template `.github/workflows/email-report.yml.template:72` emits
+only the bare step:
+
+```yaml
+ - run: pip install -e .
+```
+
+`render_workflow()` (`setup_workflow.py:109-147`) passes static template text
+through unchanged, so the next setup regeneration (option 5 / wizard /
+`write_workflow`) silently drops both the comment and the suppression. The
+suppression loss is the real risk: it currently silences
+`githubactions:S8541`/`S8544` (unpinned package versions / dependencies —
+see `CHANGELOG.md` and commit `d7f143f5`), which would fire again on the next
+regenerated workflow.
+
+One correction before porting: the comment's last line ("nothing else is
+resolved here") overclaims. `pyproject.toml:2` (`[build-system] requires`)
+pins only `setuptools>=77.0.3` — a range, not a pin — and pip resolves that
+build backend in an isolated env, not from `uv.lock`. The suppression remains
+appropriate (the only unpinned resolution is the setuptools build backend for
+this repo's own package install in CI; no third-party runtime code is installed
+unpinned — `dependencies` is empty), but the comment must say so honestly. The
+corrected wording below replaces the third line; it goes into the template
+**and** the committed workflow identically so parity holds.
+
+Tracked in `TO_DO.md` (Code Health): remove that item when this plan is
+complete (per repo rule, completed items are removed, not checked off).
+
+## Scope
+
+- Single edit to `email-report.yml.template`: expand the single line 72 into
+ the 4-line block below (corrected third line — see Problem). Apply the
+ identical block to the committed `email-report.yml:72-75` so the two files
+ stay byte-identical outside the generator placeholders:
+
+ ```yaml
+ # 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
+ ```
+
+ Bare `# NOSONAR` is the repo standard; parameterized forms like
+ `# NOSONAR(rule)` are invalid and rejected by `python:S7632` (commit
+ `d7f143f5`). The suppression guards the *regenerated workflow output*,
+ not the template file itself.
+- No change to `render_workflow()` — static text passes through; no new
+ placeholder needed.
+- No change to the committed `email-report.yml` — it already has the block.
+- Verify there is no *other* committed-vs-template drift while here (last
+ verified 2026-11-09: the pip-install block was the only delta).
+
+## Out of scope
+
+- Changing install behavior or the suppression itself.
+- Other workflow/template drift (none known).
+- The API-call-tracking plan and the `--max-repos` cap raise (same branch,
+ separate commits).
+
+## Done criteria
+
+- Template and committed workflow contain the corrected comment block and the
+ `# NOSONAR` suffix verbatim (identical in both files).
+- `render_workflow()` output from an in-memory test config matching the
+ committed workflow's parameters (`include_consumers=True`,
+ `include_artifact_storage=True`, `email_format="html"`, `max_repos=100`,
+ `warn_over=["25", "80%"]`) equals the committed `email-report.yml`
+ byte-for-byte (zero drift across all static template lines). Do NOT verify
+ against the local gitignored `.github-usage/config.toml`: it varies per
+ machine, so a local-config parity check passes only by coincidence.
+- New/updated tests pin the block in both files (see Test plan).
+- `scripts/check` and `scripts/docs-check` pass.
+- SonarCloud PR check stays green, confirming the regenerated workflow keeps
+ its `S8541`/`S8544` suppression. If Sonar flags anything new, stop and
+ reassess rather than forcing it through.
+- No `CHANGELOG.md` entry: template-only change, not user-visible behavior
+ (per `AGENTS.md` done criteria, docs/changelog updates are for user-visible
+ changes).
+- Remove the `TO_DO.md` item and move this plan to
+ `docs/superpowers/plans/archived/` in the same change set, before
+ commit/merge (per `AGENTS.md` documentation lifecycle), with the status
+ banner set to the canonical `> **Status:** COMPLETE` form.
+
+## Test plan
+
+- `tests/test_setup_workflow.py`: extend with an assertion that
+ `render_workflow()` output contains the comment text and the
+ `pip install -e . # NOSONAR` line (guards the template, the generator's
+ only input for this block).
+- `tests/test_workflow_templates.py`: assert the committed workflow and the
+ template agree on the pip-install block (same corrected comment + same
+ `# NOSONAR`), guarding drift in both directions.
+- Parity check as a test (not a manual local-config diff): render from an
+ in-memory config matching the committed workflow's parameters
+ (`include_consumers=True`, `include_artifact_storage=True`,
+ `email_format="html"`, `max_repos=100`, `warn_over=["25", "80%"]`) and
+ assert byte-equality with the committed `email-report.yml`, so the check is
+ machine-independent (the local gitignored `config.toml` varies per
+ workstation and must not be the reference).
+- Keep assertions to `assertIn` on the distinctive strings (comment first
+ line, `# NOSONAR` on the pip-install line) rather than full-file compares,
+ so unrelated profile-arg changes do not break them.
+
+## Task breakdown
+
+- [ ] Port the comment + `# NOSONAR` into `email-report.yml.template`.
+- [ ] Add the `test_setup_workflow.py` render assertion and the
+ `test_workflow_templates.py` parity assertion.
+- [ ] Verify static parity via the updated unit tests (in-memory config
+ matching the committed workflow's parameters, not the local gitignored
+ config); run `scripts/check` and `scripts/docs-check`.
+- [ ] Confirm SonarCloud check green on the PR; remove the `TO_DO.md` item;
+ archive this plan.
diff --git a/src/github_usage/email_report_html.py b/src/github_usage/email_report_html.py
index bf0a087..e933509 100644
--- a/src/github_usage/email_report_html.py
+++ b/src/github_usage/email_report_html.py
@@ -10,12 +10,6 @@
email_actions_net_cost_line,
email_actions_table_rows,
)
-from .copilot_metering import (
- _effective_metering,
- copilot_model_detail_line,
- copilot_section_title,
- copilot_usage_summary_lines,
-)
from ._email_report_html_tables import (
html_cost_consumer_row,
html_flat_table,
@@ -25,6 +19,12 @@
html_storage_row,
html_workflow_breakdown_table,
)
+from .copilot_metering import (
+ _effective_metering,
+ copilot_model_detail_line,
+ copilot_section_title,
+ copilot_usage_summary_lines,
+)
from .repo_consumers import private_list_is_redundant
from .report_forecast_data import build_report_forecast, forecast_metric_rows
from .report_helpers import fmt_price
@@ -69,9 +69,7 @@ def _format_html_actions_section(data: dict) -> list[str]:
net = (data.get("monthly_costs") or {}).get("actions", {}).get("net", 0.0)
rows = ["| Metric | Value |
"]
for label, value in email_actions_table_rows(actions):
- rows.append(
- f"| {html.escape(label)} | {html.escape(value)} |
"
- )
+ rows.append(f"| {html.escape(label)} | {html.escape(value)} |
")
net_line = email_actions_net_cost_line(net)
_, _, net_value = net_line.partition(": ")
rows.append(f"| Net cost | {html.escape(net_value)} |
")
@@ -79,6 +77,7 @@ def _format_html_actions_section(data: dict) -> list[str]:
def _format_html_copilot_section(data: dict) -> list[str]:
+ """Format the Copilot usage section as HTML."""
copilot = data.get("copilot")
if not copilot:
return []
@@ -91,9 +90,7 @@ def _format_html_copilot_section(data: dict) -> list[str]:
parts.append(f"- {html.escape(line.removeprefix('- '))}
")
by_model = copilot.get("by_model") or {}
if by_model:
- parts.append(_UL_CLOSE)
- parts.append("By model
")
- parts.append("")
+ parts.extend([_UL_CLOSE, "By model
", ""])
for model, values in sorted(by_model.items()):
detail = copilot_model_detail_line(model, values, metering=metering).strip()
if detail.startswith("- "):
@@ -222,36 +219,55 @@ def _format_html_workflow_breakdown_section(data: dict) -> list[str]:
return html_workflow_breakdown_table(breakdown, limit=5)
-def _format_html_artifact_storage_section(data: dict) -> list[str]:
- artifact_storage = data.get("artifact_storage")
- if not artifact_storage:
- return []
- repos = artifact_storage.get("top_repos", [])
- parts = ["Actions Artifact Storage
"]
+def _html_artifact_repo_rows(repos: list) -> list[str]:
+ """Render artifact repo rows as list items, grouped by visibility."""
groups = group_by_visibility(repos)
if len(groups) <= 1:
+ rows = [
+ f"- {html_repo_cell(row)}: "
+ f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts
"
+ for row in repos
+ ]
+ return ["", *rows, _UL_CLOSE]
+ parts = []
+ for vis, group_rows in groups.items():
+ parts.append(f"{html.escape(visibility_group_header(vis))}
")
parts.append("")
- for row in repos:
+ for row in group_rows:
parts.append(
f"- {html_repo_cell(row)}: "
f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts
"
)
parts.append(_UL_CLOSE)
- else:
- for vis, group_rows in groups.items():
- parts.append(f"{html.escape(visibility_group_header(vis))}
")
- parts.append("")
- for row in group_rows:
- parts.append(
- f"- {html_repo_cell(row)}: "
- f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts
"
- )
- parts.append(_UL_CLOSE)
+ return parts
+
+
+def _html_artifact_error_rows(errors: dict) -> list[str]:
+ """Render per-repo artifact scan errors as list items."""
+ if not errors:
+ return []
+ rows = [
+ f"- {html.escape(repo_name)}: skipped ({html.escape(str(errors[repo_name]))})
"
+ for repo_name in sorted(errors)
+ ]
+ return ["", *rows, _UL_CLOSE]
+
+
+def _format_html_artifact_storage_section(data: dict) -> list[str]:
+ """Format the Actions Artifact Storage section as HTML, including per-repo errors."""
+ artifact_storage = data.get("artifact_storage")
+ if not artifact_storage:
+ return []
+ parts = ["Actions Artifact Storage
"]
+ repos = artifact_storage.get("top_repos", [])
+ if repos:
+ parts.extend(_html_artifact_repo_rows(repos))
if artifact_storage.get("truncated"):
parts.append(
f"Artifact scan truncated at "
f"{artifact_storage.get('max_repos')} repositories.
"
)
+ parts.extend(_html_artifact_error_rows(artifact_storage.get("errors") or {}))
return parts
@@ -472,9 +488,13 @@ def format_html_report(
"""Format report data as an HTML email body."""
username = html.escape(data.get("username") or "?")
parts: list[str] = [_HTML_DOCUMENT_HEAD]
- parts.append(f"GitHub Usage Report for {username}
")
- parts.append(f'{html.escape(_generated_line(data.get("generated_at")))}
')
- parts.append('Period: current month
')
+ parts.extend(
+ [
+ f"GitHub Usage Report for {username}
",
+ f'{html.escape(_generated_line(data.get("generated_at")))}
',
+ 'Period: current month
',
+ ]
+ )
parts.extend(_html_warning_block(data.get("warnings") or []))
for formatter in _SECTION_HTML_FORMATTERS:
if formatter is _format_html_forecast_section:
diff --git a/src/github_usage/email_report_text.py b/src/github_usage/email_report_text.py
index f2200c0..edab6fd 100644
--- a/src/github_usage/email_report_text.py
+++ b/src/github_usage/email_report_text.py
@@ -265,6 +265,7 @@ def _format_workflow_breakdown_section(data: dict) -> list[str]:
def _format_artifact_storage_section(data: dict) -> list[str]:
+ """Format the Actions Artifact Storage section, including per-repo scan errors."""
artifact_storage = data.get("artifact_storage")
if not artifact_storage:
return []
@@ -287,6 +288,9 @@ def _format_artifact_storage_section(data: dict) -> list[str]:
lines.append(
f"- Artifact scan truncated at {artifact_storage.get('max_repos')} repositories."
)
+ for repo_name in sorted(artifact_storage.get("errors") or {}):
+ message = artifact_storage["errors"][repo_name]
+ lines.append(f"- {repo_name}: skipped ({message})")
lines.append("")
return lines
diff --git a/src/github_usage/export_pdf.py b/src/github_usage/export_pdf.py
index 4c8691f..7fefc94 100644
--- a/src/github_usage/export_pdf.py
+++ b/src/github_usage/export_pdf.py
@@ -16,6 +16,7 @@
from collections.abc import Callable
+from .copilot_metering import copilot_export_primary_row
from .export_visibility import (
annotate_sku_name,
sources_rows,
@@ -23,7 +24,6 @@
visibility_summary_label_values,
)
from .report_forecast_data import build_report_forecast, forecast_metric_rows
-from .copilot_metering import copilot_export_primary_row
from .usage_split import classify_actions_sku
from .visibility import repo_visibility, visibility_label
@@ -223,16 +223,21 @@ def _write_sources_page(add_section: AddSectionFn, data: dict) -> None:
def _write_artifact_storage_page(add_section: AddSectionFn, data: dict) -> None:
+ """Write the Artifact Storage page, including per-repo scan errors."""
artifacts = data.get("artifact_storage") or {}
artifact_repos = artifacts.get("top_repos") or []
- if artifact_repos:
- rows = [
- (
- _annotated_repo_label(entry),
- f"{_fmt_num(entry.get('artifact_bytes'))} bytes",
- )
- for entry in artifact_repos
- ]
+ # Error rows first: add_section renders only rows[:_MAX_SECTION_ROWS], and
+ # repo rows (capped at 5 upstream) must never push errors off the page.
+ errors = artifacts.get("errors") or {}
+ rows = [(repo_name, f"skipped: {errors[repo_name]}") for repo_name in sorted(errors)]
+ rows.extend(
+ (
+ _annotated_repo_label(entry),
+ f"{_fmt_num(entry.get('artifact_bytes'))} bytes",
+ )
+ for entry in artifact_repos
+ )
+ if rows:
add_section("Artifact Storage", rows)
diff --git a/src/github_usage/report_optional.py b/src/github_usage/report_optional.py
index c692ee3..c236b2f 100644
--- a/src/github_usage/report_optional.py
+++ b/src/github_usage/report_optional.py
@@ -63,11 +63,19 @@ def get_repo_consumers(api, repos: list[dict], limit: int = 5, max_repos: int =
def get_artifact_storage_details(api, repos: list[dict], max_repos: int = 100) -> dict:
"""Return per-repo artifact storage totals for the top storage consumers."""
rows = []
+ errors: dict = {}
considered = repos[:max_repos]
for repo in considered:
owner = repo.get("owner", {}).get("login", "")
name = repo.get("name", "")
- artifacts = api.get_all_pages(f"/repos/{owner}/{name}/actions/artifacts", {"per_page": 100})
+ full_name = repo.get("full_name") or f"{owner}/{name}"
+ try:
+ artifacts = api.get_all_pages(
+ f"/repos/{owner}/{name}/actions/artifacts", {"per_page": 100}
+ )
+ except RuntimeError as e:
+ errors[full_name] = str(e)
+ continue
size = sum(
s
for s in (_safe_int_size(item.get("size_in_bytes")) for item in artifacts)
@@ -76,7 +84,7 @@ def get_artifact_storage_details(api, repos: list[dict], max_repos: int = 100) -
if size:
rows.append(
{
- "repo": repo.get("full_name") or f"{owner}/{name}",
+ "repo": full_name,
"artifact_bytes": size,
"visibility": repo_visibility(repo),
}
@@ -86,6 +94,7 @@ def get_artifact_storage_details(api, repos: list[dict], max_repos: int = 100) -
"max_repos": max_repos,
"truncated": len(repos) > max_repos,
"top_repos": sorted(rows, key=lambda row: row["artifact_bytes"], reverse=True)[:5],
+ "errors": errors,
}
diff --git a/tests/test_email_report.py b/tests/test_email_report.py
index c6262d6..f529001 100644
--- a/tests/test_email_report.py
+++ b/tests/test_email_report.py
@@ -681,6 +681,29 @@ def test_artifact_storage_grouped_by_visibility_text(self):
self.assertIn("Private Repos:", text)
self.assertIn("Public Repos:", text)
+ def test_artifact_storage_errors_rendered_alongside_rows_text(self):
+ from github_usage.email_report_text import _format_artifact_storage_section
+
+ data = {
+ "artifact_storage": {
+ "top_repos": [
+ {"repo": "org/good", "visibility": "public", "artifact_bytes": 1024},
+ ],
+ "errors": {"org/bad": "API error 403"},
+ }
+ }
+ text = "\n".join(_format_artifact_storage_section(data))
+ self.assertIn("- org/good: 0.0 MB artifacts", text)
+ self.assertIn("- org/bad: skipped (API error 403)", text)
+
+ def test_artifact_storage_errors_only_section_text(self):
+ from github_usage.email_report_text import _format_artifact_storage_section
+
+ data = {"artifact_storage": {"top_repos": [], "errors": {"org/bad": "API error 403"}}}
+ text = "\n".join(_format_artifact_storage_section(data))
+ self.assertIn("Actions Artifact Storage", text)
+ self.assertIn("- org/bad: skipped (API error 403)", text)
+
def test_artifact_storage_grouped_by_visibility_html(self):
from github_usage.email_report_html import _format_html_artifact_storage_section
@@ -697,6 +720,35 @@ def test_artifact_storage_grouped_by_visibility_html(self):
self.assertIn("Private Repos:", joined)
self.assertIn("Public Repos:", joined)
+ def test_artifact_storage_errors_rendered_alongside_rows_html(self):
+ from github_usage.email_report_html import _format_html_artifact_storage_section
+
+ data = {
+ "artifact_storage": {
+ "top_repos": [
+ {"repo": "org/good", "visibility": "public", "artifact_bytes": 1024},
+ ],
+ "errors": {"org/a&b": "oops "},
+ }
+ }
+ joined = "\n".join(_format_html_artifact_storage_section(data))
+ self.assertIn("- org/good: 0.0 MB artifacts
", joined)
+ self.assertIn("- org/a&b: skipped (oops <boom>)
", joined)
+
+ def test_artifact_storage_errors_only_section_html(self):
+ from github_usage.email_report_html import _format_html_artifact_storage_section
+
+ data = {
+ "artifact_storage": {
+ "top_repos": [],
+ "errors": {"org/bad": "API error 403"},
+ }
+ }
+ joined = "\n".join(_format_html_artifact_storage_section(data))
+ self.assertIn("Actions Artifact Storage
", joined)
+ self.assertIn("- org/bad: skipped (API error 403)
", joined)
+ self.assertNotIn("", joined)
+
def test_release_assets_grouped_by_visibility_text(self):
from github_usage.email_report_text import _format_release_assets_section
diff --git a/tests/test_export_pdf.py b/tests/test_export_pdf.py
index d524854..edd4d77 100644
--- a/tests/test_export_pdf.py
+++ b/tests/test_export_pdf.py
@@ -176,6 +176,72 @@ def test_write_actions_page_renders_minutes_and_storage(self):
# plus the actions page).
self.assertGreaterEqual(pdf.pages_count, 1)
+ def test_write_artifact_storage_page_renders_errors_alongside_rows(self):
+ from fpdf import FPDF
+
+ from github_usage.export_pdf import _make_pdf_writer, _write_artifact_storage_page
+
+ pdf = FPDF()
+ pdf.set_auto_page_break(auto=True, margin=20)
+ seen = []
+
+ def recording(title, rows):
+ seen.append((title, rows))
+ add_section(title, rows)
+
+ add_section, _ = _make_pdf_writer(pdf)
+ data = {
+ "artifact_storage": {
+ "top_repos": [{"repo": "org/good", "artifact_bytes": 1024}],
+ "errors": {"org/bad": "API error 403"},
+ }
+ }
+ _write_artifact_storage_page(recording, data)
+ self.assertEqual(len(seen), 1)
+ title, rows = seen[0]
+ self.assertEqual(title, "Artifact Storage")
+ labels = [label for label, _ in rows]
+ self.assertIn("org/good", labels)
+ self.assertIn("org/bad", labels)
+ values = dict(rows)
+ self.assertEqual(values["org/bad"], "skipped: API error 403")
+
+ def test_write_artifact_storage_page_errors_first_and_errors_only(self):
+ from fpdf import FPDF
+
+ from github_usage.export_pdf import _make_pdf_writer, _write_artifact_storage_page
+
+ pdf = FPDF()
+ pdf.set_auto_page_break(auto=True, margin=20)
+ seen = []
+
+ def recording(title, rows):
+ seen.append((title, rows))
+ add_section(title, rows)
+
+ add_section, _ = _make_pdf_writer(pdf)
+ data = {
+ "artifact_storage": {
+ "top_repos": [{"repo": f"org/repo{i}", "artifact_bytes": 1024} for i in range(5)],
+ "errors": {f"org/bad{i}": "API error 403" for i in range(26)},
+ }
+ }
+ _write_artifact_storage_page(recording, data)
+ self.assertEqual(len(seen), 1)
+ _, rows = seen[0]
+ # Error rows precede repo rows so the 30-row page cap truncates
+ # successful rows first, never silently dropping failures.
+ self.assertTrue(all(label.startswith("org/bad") for label, _ in rows[:26]))
+ self.assertTrue(all(label.startswith("org/repo") for label, _ in rows[26:]))
+
+ seen.clear()
+ _write_artifact_storage_page(
+ recording,
+ {"artifact_storage": {"top_repos": [], "errors": {"org/bad": "API error 403"}}},
+ )
+ self.assertEqual(len(seen), 1)
+ self.assertEqual(seen[0][1], [("org/bad", "skipped: API error 403")])
+
def test_dependency_check_at_orchestrator(self):
from github_usage import export_report
diff --git a/tests/test_report_optional.py b/tests/test_report_optional.py
index 0e94684..b560ffd 100644
--- a/tests/test_report_optional.py
+++ b/tests/test_report_optional.py
@@ -90,6 +90,31 @@ def test_handles_empty_artifacts(self):
result = get_artifact_storage_details(api, [_repo("octocat/repo")], max_repos=10)
self.assertEqual(result["top_repos"], [])
+ def test_records_per_repo_error_and_keeps_other_repos(self):
+ """One repo's artifact API error must not abort the whole scan."""
+ api = FakeAPI()
+ # Failing repo first: the error side_effect pairs with the first repo,
+ # proving the scan continues past it (order matters here).
+ with mock.patch.object(
+ api,
+ "get_all_pages",
+ side_effect=[
+ RuntimeError("API error 403"),
+ [{"size_in_bytes": 1024}],
+ ],
+ ):
+ result = get_artifact_storage_details(
+ api,
+ [_repo("octocat/bad", name="bad"), _repo("octocat/good", name="good")],
+ max_repos=10,
+ )
+ self.assertEqual(
+ result["top_repos"],
+ [{"repo": "octocat/good", "artifact_bytes": 1024, "visibility": "public"}],
+ )
+ self.assertIn("octocat/bad", result["errors"])
+ self.assertEqual(result["scanned_repo_count"], 2)
+
def test_populates_from_object_shaped_artifacts_response(self):
"""Artifact collector populates rows when GitHub returns {artifacts: [...]}."""
import json
diff --git a/tests/test_workflow_templates.py b/tests/test_workflow_templates.py
index 36fa508..10bdbb3 100644
--- a/tests/test_workflow_templates.py
+++ b/tests/test_workflow_templates.py
@@ -18,6 +18,7 @@ def test_email_report_workflow_uses_safe_secret_names_and_dispatch_inputs(self):
self.assertIn("only_public:", workflow)
self.assertIn("only_private:", workflow)
self.assertIn("--only-public", workflow)
+ self.assertRegex(workflow, r"--max-repos 100(?!\d)")
def test_checked_in_workflow_and_template_use_only_recipient_secret(self):
for name in ("email-report.yml", "email-report.yml.template"):