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
2 changes: 1 addition & 1 deletion .github/workflows/email-report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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%)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
if [ ${#profile_args[@]} -gt 0 ]; then
args+=("${profile_args[@]}")
fi
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions TO_DO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
434 changes: 434 additions & 0 deletions docs/superpowers/plans/2026-11-09-api-call-tracking.md

Large diffs are not rendered by default.

136 changes: 136 additions & 0 deletions docs/superpowers/plans/2026-11-09-template-drift-pip-nosonar.md
Original file line number Diff line number Diff line change
@@ -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.
84 changes: 52 additions & 32 deletions src/github_usage/email_report_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -69,16 +69,15 @@ def _format_html_actions_section(data: dict) -> list[str]:
net = (data.get("monthly_costs") or {}).get("actions", {}).get("net", 0.0)
rows = ["<tr><th>Metric</th><th>Value</th></tr>"]
for label, value in email_actions_table_rows(actions):
rows.append(
f"<tr><td>{html.escape(label)}</td><td>{html.escape(value)}</td></tr>"
)
rows.append(f"<tr><td>{html.escape(label)}</td><td>{html.escape(value)}</td></tr>")
net_line = email_actions_net_cost_line(net)
_, _, net_value = net_line.partition(": ")
rows.append(f"<tr><td>Net cost</td><td>{html.escape(net_value)}</td></tr>")
return ["<h2>Actions</h2>", _TABLE_OPEN, *rows, _TABLE_CLOSE]


def _format_html_copilot_section(data: dict) -> list[str]:
"""Format the Copilot usage section as HTML."""
copilot = data.get("copilot")
if not copilot:
return []
Expand All @@ -91,9 +90,7 @@ def _format_html_copilot_section(data: dict) -> list[str]:
parts.append(f"<li>{html.escape(line.removeprefix('- '))}</li>")
by_model = copilot.get("by_model") or {}
if by_model:
parts.append(_UL_CLOSE)
parts.append("<h3>By model</h3>")
parts.append("<ul>")
parts.extend([_UL_CLOSE, "<h3>By model</h3>", "<ul>"])
for model, values in sorted(by_model.items()):
detail = copilot_model_detail_line(model, values, metering=metering).strip()
if detail.startswith("- "):
Expand Down Expand Up @@ -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 = ["<h2>Actions Artifact Storage</h2>"]
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"<li>{html_repo_cell(row)}: "
f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts</li>"
for row in repos
]
return ["<ul>", *rows, _UL_CLOSE]
parts = []
for vis, group_rows in groups.items():
parts.append(f"<h3>{html.escape(visibility_group_header(vis))}</h3>")
parts.append("<ul>")
for row in repos:
for row in group_rows:
parts.append(
f"<li>{html_repo_cell(row)}: "
f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts</li>"
)
parts.append(_UL_CLOSE)
else:
for vis, group_rows in groups.items():
parts.append(f"<h3>{html.escape(visibility_group_header(vis))}</h3>")
parts.append("<ul>")
for row in group_rows:
parts.append(
f"<li>{html_repo_cell(row)}: "
f"{_bytes_to_mb(row['artifact_bytes']):,.1f} MB artifacts</li>"
)
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"<li>{html.escape(repo_name)}: skipped ({html.escape(str(errors[repo_name]))})</li>"
for repo_name in sorted(errors)
]
return ["<ul>", *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 = ["<h2>Actions Artifact Storage</h2>"]
repos = artifact_storage.get("top_repos", [])
if repos:
parts.extend(_html_artifact_repo_rows(repos))
if artifact_storage.get("truncated"):
parts.append(
f"<p><em>Artifact scan truncated at "
f"{artifact_storage.get('max_repos')} repositories.</em></p>"
)
parts.extend(_html_artifact_error_rows(artifact_storage.get("errors") or {}))
return parts


Expand Down Expand Up @@ -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"<h1>GitHub Usage Report for {username}</h1>")
parts.append(f'<p class="meta">{html.escape(_generated_line(data.get("generated_at")))}</p>')
parts.append('<p class="meta">Period: current month</p>')
parts.extend(
[
f"<h1>GitHub Usage Report for {username}</h1>",
f'<p class="meta">{html.escape(_generated_line(data.get("generated_at")))}</p>',
'<p class="meta">Period: current month</p>',
]
)
parts.extend(_html_warning_block(data.get("warnings") or []))
for formatter in _SECTION_HTML_FORMATTERS:
if formatter is _format_html_forecast_section:
Expand Down
4 changes: 4 additions & 0 deletions src/github_usage/email_report_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
Expand All @@ -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

Expand Down
23 changes: 14 additions & 9 deletions src/github_usage/export_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@

from collections.abc import Callable

from .copilot_metering import copilot_export_primary_row
from .export_visibility import (
annotate_sku_name,
sources_rows,
storage_summary_label_values,
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

Expand Down Expand Up @@ -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)


Expand Down
Loading
Loading