WORKFLOW · cost-engineering
Workflow: weekly cost-per-merged-PR report
A GitHub Actions job that joins Claude Code Analytics API spend to merged PRs, classifies agent-assisted PRs by commit trailer, and posts the weekly ratio to the run summary.
✓ verified 2026-07-11 · stack: github-actions, github, claude-code · source
The automation for cost per merged PR: every Monday it sums the previous week’s Claude Code spend from the Analytics API, counts the repository’s merged PRs, classifies each as agent-assisted by grepping its commits for a trailer, and posts the ratios to the workflow run summary. Two files, no dependencies.
Requires an Admin API key (ANTHROPIC_ADMIN_KEY secret), a
different key class from a standard API key, available to organisations
only. Individual accounts and Bedrock/Vertex/Foundry fleets cannot use
this numerator; substitute the spend query from your
OTel backend or
CUR in the marked
function and keep the rest.
name: cost-per-pr-report
on: schedule: - cron: "30 6 * * 1" # Mondays 06:30 UTC, reporting on the prior week workflow_dispatch: {}
permissions: contents: read pull-requests: read
jobs: report: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - name: Build weekly report env: ANTHROPIC_ADMIN_KEY: ${{ secrets.ANTHROPIC_ADMIN_KEY }} GITHUB_TOKEN: ${{ github.token }} run: node scripts/cost-per-pr-report.mjs#!/usr/bin/env node// Weekly cost-per-merged-PR report. Zero dependencies; Node 20+.// Numerator: Claude Code Analytics API (per-user per-day, cents USD).// Denominator: merged PRs in this repo, split by agent-assisted trailer.import { appendFileSync } from 'node:fs';
const repo = process.env.GITHUB_REPOSITORY;const DAYS = 7;// The trailer(s) your agent commits carry — adjust to your convention.const TRAILER = /Co-Authored-By: Claude|Claude-Session:/i;
const end = new Date();end.setUTCHours(0, 0, 0, 0); // today 00:00 UTC, exclusiveconst start = new Date(end);start.setUTCDate(end.getUTCDate() - DAYS);const iso = (d) => d.toISOString().slice(0, 10);const lastDay = iso(new Date(end.getTime() - 1));
// --- Numerator: swap this function for an OTel/CUR query on cloud// deployments the Analytics API does not cover.async function analyticsDay(date) { let cents = 0; let created = 0; let page; do { const url = new URL('https://api.anthropic.com/v1/organizations/usage_report/claude_code'); url.searchParams.set('starting_at', date); url.searchParams.set('limit', '1000'); if (page) url.searchParams.set('page', page); const res = await fetch(url, { headers: { 'x-api-key': process.env.ANTHROPIC_ADMIN_KEY, 'anthropic-version': '2023-06-01', }, }); if (!res.ok) throw new Error(`analytics ${date}: HTTP ${res.status}`); const body = await res.json(); for (const rec of body.data) { created += rec.core_metrics?.pull_requests_by_claude_code ?? 0; for (const m of rec.model_breakdown ?? []) { cents += m.estimated_cost?.amount ?? 0; } } page = body.has_more ? body.next_page : undefined; } while (page); return { cents, created };}
async function gh(path) { const res = await fetch(`https://api.github.com${path}`, { headers: { authorization: `Bearer ${process.env.GITHUB_TOKEN}`, accept: 'application/vnd.github+json', }, }); if (!res.ok) throw new Error(`github ${path}: HTTP ${res.status}`); return res.json();}
// Merged PRs in the window (search caps at 1,000 results).const q = encodeURIComponent( `repo:${repo} is:pr is:merged merged:${iso(start)}..${lastDay}`,);const merged = [];for (let p = 1; p <= 10; p++) { const r = await gh(`/search/issues?q=${q}&per_page=100&page=${p}`); merged.push(...r.items); if (merged.length >= r.total_count || r.items.length === 0) break;}
// Classify agent-assisted by commit trailer (first 100 commits per PR).let assisted = 0;for (const pr of merged) { const commits = await gh(`/repos/${repo}/pulls/${pr.number}/commits?per_page=100`); if (commits.some((c) => TRAILER.test(c.commit.message))) assisted++;}
// Sum the week's spend.let cents = 0;let createdByAgent = 0;for (let i = 0; i < DAYS; i++) { const d = new Date(start); d.setUTCDate(start.getUTCDate() + i); const day = await analyticsDay(iso(d)); cents += day.cents; createdByAgent += day.created;}
const usd = cents / 100;const ratio = (n) => (n > 0 ? `$${(usd / n).toFixed(2)}` : 'n/a');const report = `## Cost per merged PR — ${iso(start)} to ${lastDay}
| Measure | Value ||---|---|| Claude Code spend (estimated, all users) | $${usd.toFixed(2)} || PRs merged | ${merged.length} || … agent-assisted (trailer match) | ${assisted} || PRs created via Claude Code (API metric) | ${createdByAgent} || Cost per merged PR | ${ratio(merged.length)} || Cost per agent-assisted merged PR | ${ratio(assisted)} |
Numerator is an estimate (Analytics API, cents USD) covering the wholeorganisation's Claude API usage; scope the denominator accordingly.`;
if (process.env.GITHUB_STEP_SUMMARY) { appendFileSync(process.env.GITHUB_STEP_SUMMARY, report);}console.log(report);What it does
- Pulls per-user per-day records from
/v1/organizations/usage_report/claude_codewith cursor pagination, summingestimated_cost.amount(cents) across users and models, plus thepull_requests_by_claude_codecreated-PR metric for the level-2 proxy. - Counts the repository’s merged PRs for the seven prior UTC days via the search API, then fetches each PR’s commits once and greps for the agent trailer, the level-3 classification from the pattern page, with no infrastructure beyond a commit-message convention.
- Emits the six-line report to the run summary and the job log: total spend, merged and assisted counts, created-via-agent count, and the two ratios. Week on week, the run history is the trend chart.
Failure modes
- Numerator and denominator scopes differ. The API reports the whole organisation’s spend; the search counts one repository’s merges. Fine for a single-product org; otherwise run the job in each active repo against a shared numerator and read the assisted-PR splits rather than the headline ratio, or accept it as the org ratio it is.
- The Admin key is powerful: treat it accordingly. It reads org-wide usage including user emails. Store it as an environment secret in a protected environment, not a repo secret shared with every workflow.
- Organisations only, Claude API only. Individual accounts get HTTP
errors, and Bedrock/Vertex/Foundry usage is invisible to this API.
Swap
analyticsDayfor a query against your OTel backend or CUR in those deployments. The rest of the script is deployment-agnostic. - Trailer discipline is the classifier. A squash-merge that drops trailers, or agents committing without them, undercounts agent-assisted PRs. Enforce the trailer in the merge-commit body (or match on PR body markers instead) and treat a sudden assisted-count drop as a convention regression, not a behaviour change.
- Estimates, not invoices.
estimated_costis the API’s own caveat; reconcile monthly against billing truth per the three-layer model. - Scale limits. Search returns at most 1,000 merged PRs per window and the commit scan reads the first 100 commits per PR; both are generous for a weekly repo window, but a monorepo merging more than that needs the GraphQL API instead.
Verified against the Claude Code Analytics API documentation (endpoint, auth class, field names, cents unit, pagination, coverage limits and the 1-hour freshness note), 2026-07-11.