Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(cron): daily Anthropic credit digest + burn-rate + month-end projection (#259)

Aurora Capitalec6bc5e8b636
diff --git a/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs b/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs
new file mode 100644
index 00000000..a143bf42
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs
@@ -0,0 +1,334 @@
+/**
+ * daily-credit-digest.mjs — burn rate / projection / severity / format tests (HEA-4047).
+ *
+ * Run: node --test claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs
+ */
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ computeBurnRate,
+ daysRemainingInMonth,
+ projectMonthEnd,
+ computeSeverity,
+ formatSlackBody,
+ readSnapshotHistory,
+ SEVERITY_HIGH_PROJECTED_PCT,
+ SEVERITY_HIGH_FALLBACK_RATIO,
+} from '../daily-credit-digest.mjs';
+import { SCHEMA_VERSION, MAX_PLAN_MONTHLY_USD } from '../ledger.mjs';
+
+function makeLedger(month, accounts) {
+ return { schema_version: SCHEMA_VERSION, month, accounts };
+}
+
+// ─── computeBurnRate ────────────────────────────────────────────────────────
+
+test('computeBurnRate: linear consumption over 7d gives expected $/day', () => {
+ const cfg = [{ email: 'a@x' }];
+ const now = new Date(Date.UTC(2026, 4, 19, 9, 0, 0));
+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
+ const history = [{ ts: sevenDaysAgo.toISOString(), email: 'a@x', remaining_usd: 200, cycle: '2026-05' }];
+ const ledger = makeLedger('2026-05', [{ email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 130 }]);
+ const { perAccount, totalDailyBurnUsd } = computeBurnRate(history, cfg, ledger, now);
+ // 70 USD consumed over 7 days → $10/day
+ assert.equal(perAccount.length, 1);
+ assert.ok(Math.abs(perAccount[0].dailyBurnUsd - 10) < 1e-6, `expected ~10, got ${perAccount[0].dailyBurnUsd}`);
+ assert.ok(Math.abs(totalDailyBurnUsd - 10) < 1e-6);
+});
+
+test('computeBurnRate: no history → null burn rate, total 0', () => {
+ const cfg = [{ email: 'a@x' }];
+ const now = new Date();
+ const ledger = makeLedger('2026-05', [{ email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 150 }]);
+ const r = computeBurnRate([], cfg, ledger, now);
+ assert.equal(r.perAccount[0].dailyBurnUsd, null);
+ assert.equal(r.totalDailyBurnUsd, 0);
+});
+
+test('computeBurnRate: ignores rows from different cycle (post-reclaim spike)', () => {
+ const cfg = [{ email: 'a@x' }];
+ const now = new Date(Date.UTC(2026, 5, 5, 9, 0, 0));
+ const history = [
+ // Prior cycle: remaining had drained to 50 by end of May
+ { ts: new Date(Date.UTC(2026, 4, 25)).toISOString(), email: 'a@x', remaining_usd: 50, cycle: '2026-05' },
+ // Current cycle: reclaimed; should be the only one considered
+ { ts: new Date(Date.UTC(2026, 5, 1)).toISOString(), email: 'a@x', remaining_usd: 200, cycle: '2026-06' },
+ ];
+ const ledger = makeLedger('2026-06', [{ email: 'a@x', cycle: '2026-06', claimed: true, remaining_usd: 170 }]);
+ const { perAccount } = computeBurnRate(history, cfg, ledger, now);
+ // 30 USD consumed over ~4 days → ~7.5/day; would be wildly negative if cross-cycle leaked
+ assert.ok(perAccount[0].dailyBurnUsd > 0 && perAccount[0].dailyBurnUsd < 20);
+});
+
+test('computeBurnRate: clamps negative burn (mid-cycle top-up) to 0', () => {
+ const cfg = [{ email: 'a@x' }];
+ const now = new Date(Date.UTC(2026, 4, 19));
+ const history = [
+ { ts: new Date(Date.UTC(2026, 4, 12)).toISOString(), email: 'a@x', remaining_usd: 50, cycle: '2026-05' },
+ ];
+ const ledger = makeLedger('2026-05', [
+ // Higher than the historical row — would yield negative consumption
+ { email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 180 },
+ ]);
+ const { perAccount, totalDailyBurnUsd } = computeBurnRate(history, cfg, ledger, now);
+ assert.equal(perAccount[0].dailyBurnUsd, 0);
+ assert.equal(totalDailyBurnUsd, 0);
+});
+
+test('computeBurnRate: 7-account fleet aggregates total burn', () => {
+ const cfg = Array.from({ length: 7 }, (_, i) => ({ email: `acc${i}@x` }));
+ const now = new Date(Date.UTC(2026, 4, 19, 9, 0, 0));
+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
+ const history = cfg.map(({ email }) => ({ ts: sevenDaysAgo, email, remaining_usd: 200, cycle: '2026-05' }));
+ const ledger = makeLedger(
+ '2026-05',
+ cfg.map(({ email }) => ({ email, cycle: '2026-05', claimed: true, remaining_usd: 130 })),
+ );
+ const { totalDailyBurnUsd } = computeBurnRate(history, cfg, ledger, now);
+ assert.ok(Math.abs(totalDailyBurnUsd - 70) < 1e-6, `expected 70, got ${totalDailyBurnUsd}`);
+});
+
+// ─── daysRemainingInMonth ───────────────────────────────────────────────────
+
+test('daysRemainingInMonth: mid-month May → 13 days', () => {
+ // May 19, 2026: 31 - 19 + 1 = 13
+ assert.equal(daysRemainingInMonth(new Date(Date.UTC(2026, 4, 19))), 13);
+});
+
+test('daysRemainingInMonth: first of month → full month', () => {
+ // Feb 1 2025 (non-leap): 28
+ assert.equal(daysRemainingInMonth(new Date(Date.UTC(2025, 1, 1))), 28);
+});
+
+test('daysRemainingInMonth: last day of month → 1', () => {
+ assert.equal(daysRemainingInMonth(new Date(Date.UTC(2026, 4, 31))), 1);
+});
+
+// ─── projectMonthEnd ────────────────────────────────────────────────────────
+
+test('projectMonthEnd: 7-account pool, mid-cycle drain', () => {
+ const cfg = Array.from({ length: 7 }, (_, i) => ({ email: `acc${i}@x` }));
+ // Each account at $100 remaining → $700 total of $1400 pool (50% consumed)
+ const ledger = makeLedger(
+ '2026-05',
+ cfg.map(({ email }) => ({ email, cycle: '2026-05', claimed: true, remaining_usd: 100 })),
+ );
+ // 13 days left, $10/day total burn → $130 more would be consumed
+ // projected consumed = 700 + 130 = 830 / 1400 ≈ 59%
+ const now = new Date(Date.UTC(2026, 4, 19));
+ const p = projectMonthEnd(ledger, cfg, 10, now);
+ assert.equal(p.poolUsd, 1400);
+ assert.equal(p.accountCount, 7);
+ assert.equal(p.currentRemainingUsd, 700);
+ assert.equal(p.currentConsumedUsd, 700);
+ assert.equal(p.currentConsumedPct, 50);
+ assert.equal(p.daysRemaining, 13);
+ assert.equal(p.projectedRemainingUsd, 570);
+ assert.equal(p.projectedConsumedUsd, 830);
+ assert.equal(p.projectedConsumedPct, 59);
+});
+
+test('projectMonthEnd: burn high enough to drain pool → clamped at pool size', () => {
+ const cfg = [{ email: 'a@x' }];
+ const ledger = makeLedger('2026-05', [{ email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 50 }]);
+ // 10 days left × $100/day burn → would drain to -950, clamp to 0
+ const now = new Date(Date.UTC(2026, 4, 22));
+ const p = projectMonthEnd(ledger, cfg, 100, now);
+ assert.equal(p.projectedRemainingUsd, 0);
+ assert.equal(p.projectedConsumedUsd, MAX_PLAN_MONTHLY_USD);
+ assert.equal(p.projectedConsumedPct, 100);
+});
+
+test('projectMonthEnd: zero burn → projection equals current state', () => {
+ const cfg = [{ email: 'a@x' }];
+ const ledger = makeLedger('2026-05', [{ email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 120 }]);
+ const p = projectMonthEnd(ledger, cfg, 0, new Date(Date.UTC(2026, 4, 15)));
+ assert.equal(p.currentRemainingUsd, 120);
+ assert.equal(p.projectedRemainingUsd, 120);
+ assert.equal(p.projectedConsumedUsd, 80);
+});
+
+test('projectMonthEnd: empty pool — no division by zero', () => {
+ const p = projectMonthEnd(makeLedger('2026-05', []), [], 0, new Date(Date.UTC(2026, 4, 19)));
+ assert.equal(p.poolUsd, 0);
+ assert.equal(p.currentConsumedPct, 0);
+ assert.equal(p.projectedConsumedPct, 0);
+});
+
+// ─── computeSeverity (threshold boundaries) ─────────────────────────────────
+
+test('computeSeverity: projected 89% + fallback 29% → LOW', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 89 }, { available: true, ratio: 0.29 });
+ assert.equal(sev, 'LOW');
+});
+
+test('computeSeverity: projected exactly 30% fallback (boundary low side) → LOW for projection at 89', () => {
+ // fallback ratio 0.30 is the threshold — >= triggers HIGH
+ const sev = computeSeverity({ projectedConsumedPct: 89 }, { available: true, ratio: 0.3 });
+ assert.equal(sev, 'HIGH');
+});
+
+test('computeSeverity: fallback 31% → HIGH regardless of projection', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 10 }, { available: true, ratio: 0.31 });
+ assert.equal(sev, 'HIGH');
+});
+
+test('computeSeverity: projected 90% (boundary) → HIGH', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 90 }, { available: true, ratio: 0 });
+ assert.equal(sev, 'HIGH');
+});
+
+test('computeSeverity: projected 91% → HIGH', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 91 }, { available: true, ratio: 0 });
+ assert.equal(sev, 'HIGH');
+});
+
+test('computeSeverity: projected 89% (boundary low side) → LOW', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 89 }, { available: true, ratio: 0 });
+ assert.equal(sev, 'LOW');
+});
+
+test('computeSeverity: thresholds match exported constants', () => {
+ // Sanity guard: prevent silent threshold drift via constant renames.
+ assert.equal(SEVERITY_HIGH_PROJECTED_PCT, 90);
+ assert.equal(SEVERITY_HIGH_FALLBACK_RATIO, 0.3);
+});
+
+test('computeSeverity: fallback unavailable does not contribute to severity', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 50 }, { available: false, reason: 'no datapoints' });
+ assert.equal(sev, 'LOW');
+});
+
+test('computeSeverity: fallback unavailable but projection high → HIGH (projection alone)', () => {
+ const sev = computeSeverity({ projectedConsumedPct: 92 }, { available: false, reason: 'aws cli not invokable' });
+ assert.equal(sev, 'HIGH');
+});
+
+// ─── readSnapshotHistory (missing-file path) ────────────────────────────────
+
+test('readSnapshotHistory: missing file → empty array', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'daily-credit-digest-'));
+ try {
+ const rows = readSnapshotHistory(join(tmp, 'does-not-exist.jsonl'));
+ assert.deepEqual(rows, []);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+test('readSnapshotHistory: parses valid JSONL + skips malformed lines', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'daily-credit-digest-'));
+ try {
+ const path = join(tmp, 'snapshots.jsonl');
+ writeFileSync(
+ path,
+ [
+ JSON.stringify({ ts: '2026-05-12T09:00:00Z', email: 'a@x', remaining_usd: 200, cycle: '2026-05' }),
+ 'not json',
+ JSON.stringify({ ts: '2026-05-19T09:00:00Z', email: 'a@x', remaining_usd: 130, cycle: '2026-05' }),
+ '',
+ ].join('\n'),
+ );
+ const rows = readSnapshotHistory(path);
+ assert.equal(rows.length, 2);
+ assert.equal(rows[0].email, 'a@x');
+ assert.equal(rows[1].remaining_usd, 130);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+// ─── formatSlackBody ────────────────────────────────────────────────────────
+
+test('formatSlackBody: includes pool, severity, projection, fallback section', () => {
+ const body = formatSlackBody({
+ cycle: '2026-05',
+ perAccountBalances: [
+ { email: 'a@x', remaining_usd: 100 },
+ { email: 'b@x', remaining_usd: 50 },
+ ],
+ burn: {
+ perAccount: [
+ { email: 'a@x', dailyBurnUsd: 5, windowDays: 7 },
+ { email: 'b@x', dailyBurnUsd: 10, windowDays: 7 },
+ ],
+ totalDailyBurnUsd: 15,
+ },
+ projection: {
+ accountCount: 2,
+ poolUsd: 400,
+ currentRemainingUsd: 150,
+ currentConsumedUsd: 250,
+ currentConsumedPct: 63,
+ projectedRemainingUsd: 0,
+ projectedConsumedUsd: 400,
+ projectedConsumedPct: 100,
+ daysRemaining: 13,
+ },
+ fallback: { available: true, fallbackCount: 5, hitCount: 95, ratio: 0.05 },
+ severity: 'HIGH',
+ });
+ assert.match(body, /severity HIGH/);
+ assert.match(body, /Pool: \$400/);
+ assert.match(body, /2026-05/);
+ assert.match(body, /13 day\(s\) left/);
+ assert.match(body, /63% consumed/);
+ assert.match(body, /Fallback 24h:/);
+ assert.match(body, /a@x/);
+ assert.match(body, /b@x/);
+ // No webhook leaks
+ assert.doesNotMatch(body, /hooks\.slack\.com/);
+});
+
+test('formatSlackBody: graceful fallback when CloudWatch unavailable', () => {
+ const body = formatSlackBody({
+ cycle: '2026-05',
+ perAccountBalances: [{ email: 'a@x', remaining_usd: 200 }],
+ burn: { perAccount: [{ email: 'a@x', dailyBurnUsd: null, windowDays: 0 }], totalDailyBurnUsd: 0 },
+ projection: {
+ accountCount: 1,
+ poolUsd: 200,
+ currentRemainingUsd: 200,
+ currentConsumedUsd: 0,
+ currentConsumedPct: 0,
+ projectedRemainingUsd: 200,
+ projectedConsumedUsd: 0,
+ projectedConsumedPct: 0,
+ daysRemaining: 5,
+ },
+ fallback: { available: false, reason: 'aws cli not invokable' },
+ severity: 'LOW',
+ });
+ assert.match(body, /Fallback 24h: unavailable/);
+ assert.match(body, /section skipped/);
+ // null burn renders as n/a, not as $null/d
+ assert.match(body, /burn: n\/a/);
+});
+
+test('formatSlackBody: dry-run marker', () => {
+ const body = formatSlackBody({
+ cycle: '2026-05',
+ perAccountBalances: [],
+ burn: { perAccount: [], totalDailyBurnUsd: 0 },
+ projection: {
+ accountCount: 0,
+ poolUsd: 0,
+ currentRemainingUsd: 0,
+ currentConsumedUsd: 0,
+ currentConsumedPct: 0,
+ projectedRemainingUsd: 0,
+ projectedConsumedUsd: 0,
+ projectedConsumedPct: 0,
+ daysRemaining: 13,
+ },
+ fallback: { available: false, reason: 'no datapoints' },
+ severity: 'LOW',
+ dryRun: true,
+ });
+ assert.match(body, /dry-run/);
+});
diff --git a/claude-ops/scripts/account-rotation/daily-credit-digest.mjs b/claude-ops/scripts/account-rotation/daily-credit-digest.mjs
new file mode 100755
index 00000000..b95cd8ff
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/daily-credit-digest.mjs
@@ -0,0 +1,518 @@
+#!/usr/bin/env node
+/* eslint-disable no-console */
+
+// ──────────────────────────────────────────────────────────────────────────────
+// daily-credit-digest.mjs
+// Daily 09:00 cron entrypoint (HEA-4047).
+//
+// Posts a Slack digest of Anthropic credit-pool health:
+// 1. Per-account remaining balance (read from credits-ledger.json — same
+// file HEA-4049's monthly reclaimer writes).
+// 2. 7-day burn rate per account + total (computed from a rolling JSONL
+// snapshot ledger at ~/.claude/credit-snapshots.jsonl that this script
+// appends to on every run).
+// 3. Month-end projection: remaining_now − (days_left_in_month × daily_burn),
+// expressed as "$X consumed of $1400 pool (Y%)".
+// 4. Anthropic→Bedrock fallback ratio over the last 24h, read from
+// CloudWatch (namespace My-Project/LLM, metrics bedrock_fallback_count +
+// anthropic_credit_hit established by HEA-4045). Graceful skip with a
+// warning line if CloudWatch read fails or metrics are absent.
+// 5. Severity escalation via scripts/ops-notify.sh:
+// HIGH → projected_consumption_pct >= 90 OR fallback_ratio >= 0.30
+// LOW → otherwise
+//
+// CLI:
+// --dry-run Print the planned Slack body + severity; do NOT post or
+// fan-out, and do NOT append today's snapshot to the JSONL.
+// --skip-snapshot Compute + post but do not append today's snapshot
+// (useful for re-posting after a manual rerun).
+// --help Print this header.
+//
+// Exit codes:
+// 0 success (digest posted, or dry-run plan printed)
+// 1 partial — digest computed but Slack post failed (logged)
+// 2 hard failure (missing config, ledger schema mismatch, snapshot append crash)
+// ──────────────────────────────────────────────────────────────────────────────
+
+import { spawnSync } from 'node:child_process';
+import { existsSync, readFileSync, mkdirSync, appendFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { homedir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+
+import { MAX_PLAN_MONTHLY_USD, readLedger, findAccount, ymKey } from './ledger.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const CONFIG_PATH = join(__dirname, 'config.json');
+const LEDGER_PATH = join(homedir(), '.claude', 'credits-ledger.json');
+const SNAPSHOTS_PATH = join(homedir(), '.claude', 'credit-snapshots.jsonl');
+const DATA_DIR =
+ process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');
+const LOG_DIR = join(DATA_DIR, 'logs');
+const LOG_PATH = join(LOG_DIR, 'daily-credit-digest.log');
+const NOTIFY_SCRIPT = join(__dirname, '..', 'ops-notify.sh');
+
+const CLOUDWATCH_NAMESPACE = 'My-Project/LLM';
+const CLOUDWATCH_FALLBACK_METRIC = 'bedrock_fallback_count';
+const CLOUDWATCH_HIT_METRIC = 'anthropic_credit_hit';
+
+// Thresholds.
+export const SEVERITY_HIGH_PROJECTED_PCT = 90;
+export const SEVERITY_HIGH_FALLBACK_RATIO = 0.3;
+
+const args = process.argv.slice(2);
+const flag = (n) => args.includes(n);
+const DRY_RUN = flag('--dry-run');
+const SKIP_SNAPSHOT = flag('--skip-snapshot');
+
+function log(line) {
+ try {
+ mkdirSync(LOG_DIR, { recursive: true });
+ appendFileSync(LOG_PATH, `${new Date().toISOString()} ${line}\n`);
+ } catch {
+ /* logging is best-effort */
+ }
+ console.log(line);
+}
+
+function loadAccountsConfig() {
+ if (!existsSync(CONFIG_PATH)) return [];
+ try {
+ const cfg = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
+ return (cfg.accounts ?? []).filter((a) => a?.email);
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Read all historical snapshots from the JSONL file.
+ * Returns an array of { ts: ISO, email: string, remaining_usd: number, cycle: string }
+ * Missing file → empty array.
+ */
+export function readSnapshotHistory(path = SNAPSHOTS_PATH) {
+ if (!existsSync(path)) return [];
+ try {
+ const txt = readFileSync(path, 'utf8');
+ const lines = txt.split('\n').filter((l) => l.trim());
+ const rows = [];
+ for (const line of lines) {
+ try {
+ const row = JSON.parse(line);
+ if (row && typeof row.email === 'string' && typeof row.ts === 'string') {
+ rows.push(row);
+ }
+ } catch {
+ /* skip malformed line */
+ }
+ }
+ return rows;
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Append today's per-account snapshot to the JSONL log.
+ */
+function appendSnapshot(ledger, accountsConfig, path = SNAPSHOTS_PATH) {
+ const ts = new Date().toISOString();
+ const accounts = accountsConfig.length ? accountsConfig : (ledger.accounts || []).map((a) => ({ email: a.email }));
+ const rows = [];
+ for (const cfg of accounts) {
+ const entry = findAccount(ledger, cfg.email);
+ const remaining = typeof entry?.remaining_usd === 'number' ? entry.remaining_usd : null;
+ if (remaining == null) continue;
+ rows.push({ ts, email: cfg.email, remaining_usd: remaining, cycle: entry?.cycle ?? null });
+ }
+ if (!rows.length) return;
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, rows.map((r) => JSON.stringify(r)).join('\n') + '\n');
+}
+
+/**
+ * Compute 7-day burn rate per account ($/day) from snapshot history.
+ *
+ * For each account: find the oldest snapshot >= (now - 7d) within the SAME cycle
+ * as the current snapshot, and the latest snapshot. burn = (older.remaining -
+ * latest.remaining) / days_elapsed. If older == latest (same day, only one
+ * snapshot), burn = 0. If no historical snapshot in window, burn = null.
+ *
+ * Returns { perAccount: [{ email, dailyBurnUsd, windowDays }], totalDailyBurnUsd }.
+ *
+ * @param {Array} history rows from readSnapshotHistory
+ * @param {Array} accountsConfig account configs (provides email list)
+ * @param {Object} currentLedger current ledger (provides "now" balance + cycle)
+ * @param {Date} now current time
+ */
+export function computeBurnRate(history, accountsConfig, currentLedger, now = new Date()) {
+ const sevenDaysAgoMs = now.getTime() - 7 * 24 * 60 * 60 * 1000;
+ const perAccount = [];
+ let totalDailyBurnUsd = 0;
+
+ const accounts = accountsConfig.length
+ ? accountsConfig
+ : (currentLedger.accounts || []).map((a) => ({ email: a.email }));
+
+ for (const cfg of accounts) {
+ const current = findAccount(currentLedger, cfg.email);
+ const currentRemaining = typeof current?.remaining_usd === 'number' ? current.remaining_usd : null;
+ const currentCycle = current?.cycle ?? null;
+
+ if (currentRemaining == null) {
+ perAccount.push({ email: cfg.email, dailyBurnUsd: null, windowDays: 0 });
+ continue;
+ }
+
+ // Filter history to this account + same cycle (avoid burn-rate spike from
+ // monthly reset where remaining jumps from ~0 back to 200).
+ const rows = history
+ .filter((r) => r.email.toLowerCase() === cfg.email.toLowerCase())
+ .filter((r) => (currentCycle == null ? true : r.cycle === currentCycle))
+ .filter((r) => new Date(r.ts).getTime() >= sevenDaysAgoMs)
+ .sort((a, b) => new Date(a.ts) - new Date(b.ts));
+
+ if (rows.length === 0) {
+ perAccount.push({ email: cfg.email, dailyBurnUsd: null, windowDays: 0 });
+ continue;
+ }
+
+ const oldest = rows[0];
+ const oldestMs = new Date(oldest.ts).getTime();
+ const elapsedMs = now.getTime() - oldestMs;
+ const elapsedDays = elapsedMs / (24 * 60 * 60 * 1000);
+
+ if (elapsedDays <= 0) {
+ perAccount.push({ email: cfg.email, dailyBurnUsd: 0, windowDays: 0 });
+ continue;
+ }
+
+ const consumed = oldest.remaining_usd - currentRemaining;
+ // Negative burn (e.g. mid-cycle re-claim or a glitch) → clamp to 0.
+ const dailyBurn = consumed > 0 ? consumed / elapsedDays : 0;
+ totalDailyBurnUsd += dailyBurn;
+ perAccount.push({ email: cfg.email, dailyBurnUsd: dailyBurn, windowDays: elapsedDays });
+ }
+
+ return { perAccount, totalDailyBurnUsd };
+}
+
+/**
+ * Days remaining in the current calendar month (UTC), inclusive of today.
+ * E.g. on 2026-05-19, May has 31 days → 31 - 19 + 1 = 13 days remaining.
+ */
+export function daysRemainingInMonth(now = new Date()) {
+ const year = now.getUTCFullYear();
+ const month = now.getUTCMonth();
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
+ return lastDay - now.getUTCDate() + 1;
+}
+
+/**
+ * Compute month-end projection.
+ *
+ * Returns {
+ * currentRemainingUsd, // sum across accounts right now
+ * poolUsd, // accountCount * MAX_PLAN_MONTHLY_USD
+ * currentConsumedUsd, // poolUsd - currentRemainingUsd
+ * currentConsumedPct,
+ * projectedConsumedUsd, // poolUsd - (currentRemainingUsd - daysLeft*burn), clamped [0, poolUsd]
+ * projectedConsumedPct,
+ * daysRemaining,
+ * }
+ */
+export function projectMonthEnd(currentLedger, accountsConfig, totalDailyBurnUsd, now = new Date()) {
+ const accounts = accountsConfig.length
+ ? accountsConfig
+ : (currentLedger.accounts || []).map((a) => ({ email: a.email }));
+ const accountCount = accounts.length;
+ const poolUsd = MAX_PLAN_MONTHLY_USD * accountCount;
+ let currentRemainingUsd = 0;
+ for (const cfg of accounts) {
+ const e = findAccount(currentLedger, cfg.email);
+ if (typeof e?.remaining_usd === 'number') currentRemainingUsd += e.remaining_usd;
+ }
+ const daysLeft = daysRemainingInMonth(now);
+ const projectedRemainingUsd = Math.max(0, currentRemainingUsd - daysLeft * totalDailyBurnUsd);
+ const projectedConsumedUsd = poolUsd - projectedRemainingUsd;
+ const currentConsumedUsd = poolUsd - currentRemainingUsd;
+ const pct = (n) => (poolUsd > 0 ? Math.round((n / poolUsd) * 100) : 0);
+
+ return {
+ accountCount,
+ poolUsd,
+ currentRemainingUsd,
+ currentConsumedUsd,
+ currentConsumedPct: pct(currentConsumedUsd),
+ projectedRemainingUsd,
+ projectedConsumedUsd: Math.min(poolUsd, Math.max(0, projectedConsumedUsd)),
+ projectedConsumedPct: Math.min(100, Math.max(0, pct(projectedConsumedUsd))),
+ daysRemaining: daysLeft,
+ };
+}
+
+/**
+ * Fetch the Anthropic→Bedrock fallback ratio for the last 24h from CloudWatch.
+ *
+ * Uses AWS CLI (`aws cloudwatch get-metric-data`) to avoid adding an npm
+ * dependency to this public plugin. Returns:
+ * {
+ * available: true,
+ * fallbackCount, hitCount, ratio
+ * }
+ * or { available: false, reason: string } on any failure (missing CLI, missing
+ * metric, no creds, non-zero exit, JSON parse error). The caller should render
+ * a graceful warning when available=false rather than failing the digest.
+ *
+ * `_now` (default `new Date()`) is exposed for testability.
+ */
+export async function fetchFallbackRatio({ now = new Date(), region = process.env.AWS_REGION || 'eu-west-1' } = {}) {
+ const endTime = now.toISOString();
+ const startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
+ const query = {
+ MetricDataQueries: [
+ {
+ Id: 'fallback',
+ MetricStat: {
+ Metric: { Namespace: CLOUDWATCH_NAMESPACE, MetricName: CLOUDWATCH_FALLBACK_METRIC },
+ Period: 86400,
+ Stat: 'Sum',
+ },
+ ReturnData: true,
+ },
+ {
+ Id: 'hits',
+ MetricStat: {
+ Metric: { Namespace: CLOUDWATCH_NAMESPACE, MetricName: CLOUDWATCH_HIT_METRIC },
+ Period: 86400,
+ Stat: 'Sum',
+ },
+ ReturnData: true,
+ },
+ ],
+ StartTime: startTime,
+ EndTime: endTime,
+ };
+
+ const res = spawnSync(
+ 'aws',
+ [
+ 'cloudwatch',
+ 'get-metric-data',
+ '--region',
+ region,
+ '--cli-input-json',
+ JSON.stringify(query),
+ '--output',
+ 'json',
+ ],
+ { encoding: 'utf8', timeout: 30_000 },
+ );
+
+ if (res.error) {
+ return { available: false, reason: `aws cli not invokable: ${res.error.code || res.error.message}` };
+ }
+ if (res.status !== 0) {
+ return { available: false, reason: `aws cli exited ${res.status}: ${(res.stderr || '').slice(0, 200).trim()}` };
+ }
+
+ let parsed;
+ try {
+ parsed = JSON.parse(res.stdout);
+ } catch (e) {
+ return { available: false, reason: `cloudwatch JSON parse error: ${e.message}` };
+ }
+
+ const results = Array.isArray(parsed?.MetricDataResults) ? parsed.MetricDataResults : [];
+ const sumOf = (id) => {
+ const r = results.find((x) => x.Id === id);
+ if (!r || !Array.isArray(r.Values)) return 0;
+ return r.Values.reduce((acc, v) => acc + (Number.isFinite(v) ? v : 0), 0);
+ };
+ const fallbackCount = sumOf('fallback');
+ const hitCount = sumOf('hits');
+ const denom = fallbackCount + hitCount;
+
+ if (denom === 0) {
+ return { available: false, reason: 'no datapoints in last 24h (metrics may not exist yet)' };
+ }
+
+ return {
+ available: true,
+ fallbackCount,
+ hitCount,
+ ratio: fallbackCount / denom,
+ };
+}
+
+/**
+ * Pure version that drives off a pre-fetched result. Lets us unit-test the
+ * formatter + severity logic without invoking AWS CLI.
+ */
+export function computeSeverity(projection, fallback) {
+ const projectedHigh = projection.projectedConsumedPct >= SEVERITY_HIGH_PROJECTED_PCT;
+ const fallbackHigh = fallback.available && fallback.ratio >= SEVERITY_HIGH_FALLBACK_RATIO;
+ return projectedHigh || fallbackHigh ? 'HIGH' : 'LOW';
+}
+
+function fmtUsd(n) {
+ if (!Number.isFinite(n)) return '?';
+ return `$${n.toFixed(2)}`;
+}
+
+function fmtRatio(r) {
+ if (!Number.isFinite(r)) return '?';
+ return `${(r * 100).toFixed(1)}%`;
+}
+
+export function formatSlackBody({
+ cycle,
+ perAccountBalances,
+ burn,
+ projection,
+ fallback,
+ severity,
+ dryRun = false,
+} = {}) {
+ const lines = [];
+ lines.push(`Anthropic credit-pool daily digest — ${cycle} (severity ${severity})`);
+ lines.push('');
+ lines.push(
+ `Pool: $${projection.poolUsd} (${projection.accountCount} × $${MAX_PLAN_MONTHLY_USD}) — ${projection.daysRemaining} day(s) left in month`,
+ );
+ lines.push(`Remaining now: ${fmtUsd(projection.currentRemainingUsd)} (${projection.currentConsumedPct}% consumed)`);
+ lines.push(
+ `7d burn rate: ${fmtUsd(burn.totalDailyBurnUsd)}/day — month-end projection ${fmtUsd(projection.projectedConsumedUsd)} consumed (${projection.projectedConsumedPct}% of pool)`,
+ );
+ if (fallback.available) {
+ lines.push(
+ `Fallback 24h: ${fmtRatio(fallback.ratio)} (${fallback.fallbackCount} bedrock fallbacks / ${fallback.hitCount} anthropic hits)`,
+ );
+ } else {
+ lines.push(`Fallback 24h: unavailable (${fallback.reason}) — section skipped`);
+ }
+ lines.push('');
+ lines.push('Per-account:');
+ for (const row of perAccountBalances) {
+ const burnRow = burn.perAccount.find((b) => b.email === row.email);
+ const burnTxt =
+ burnRow == null || burnRow.dailyBurnUsd == null ? 'burn: n/a' : `burn: ${fmtUsd(burnRow.dailyBurnUsd)}/d`;
+ const remainTxt = row.remaining_usd == null ? 'remaining: n/a' : `remaining: ${fmtUsd(row.remaining_usd)}`;
+ lines.push(` • ${row.email} — ${remainTxt} — ${burnTxt}`);
+ }
+ if (dryRun) {
+ lines.push('');
+ lines.push('(dry-run — no Slack post / no snapshot append)');
+ }
+ return lines.join('\n');
+}
+
+function gatherPerAccountBalances(ledger, accountsConfig) {
+ const accounts = accountsConfig.length ? accountsConfig : (ledger.accounts || []).map((a) => ({ email: a.email }));
+ return accounts.map((cfg) => {
+ const e = findAccount(ledger, cfg.email);
+ return {
+ email: cfg.email,
+ remaining_usd: typeof e?.remaining_usd === 'number' ? e.remaining_usd : null,
+ };
+ });
+}
+
+async function postSlack(body) {
+ const webhook = process.env.SLACK_WEBHOOK_URL;
+ if (!webhook) {
+ log('[daily-digest] SLACK_WEBHOOK_URL not set — skipping Slack post');
+ return { ok: true, skipped: true };
+ }
+ if (DRY_RUN) {
+ log('[daily-digest] DRY RUN — Slack payload below:');
+ log(body);
+ return { ok: true, dryRun: true };
+ }
+ try {
+ const res = await fetch(webhook, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ text: body }),
+ });
+ if (!res.ok) {
+ const txt = await res.text().catch(() => '');
+ log(`[daily-digest] Slack post failed: ${res.status} ${txt.slice(0, 200)}`);
+ return { ok: false };
+ }
+ log('[daily-digest] Slack post OK');
+ return { ok: true };
+ } catch (e) {
+ log(`[daily-digest] Slack post threw: ${e.message}`);
+ return { ok: false };
+ }
+}
+
+function fanOutNotify(severity, title, body) {
+ if (DRY_RUN) {
+ log(`[daily-digest] DRY RUN — would fan-out via ops-notify (${severity}): ${title}`);
+ return;
+ }
+ if (!existsSync(NOTIFY_SCRIPT)) return;
+ try {
+ spawnSync(NOTIFY_SCRIPT, [severity, title, body], { stdio: 'ignore', env: process.env });
+ } catch (e) {
+ log(`[daily-digest] ops-notify fan-out failed: ${e.message}`);
+ }
+}
+
+async function main() {
+ log(`[daily-digest] start cycle=${ymKey()} dry-run=${DRY_RUN} skip-snapshot=${SKIP_SNAPSHOT}`);
+
+ const accountsConfig = loadAccountsConfig();
+
+ let ledger;
+ try {
+ ledger = readLedger(LEDGER_PATH);
+ } catch (e) {
+ log(`[fatal] ledger read failed: ${e.message}`);
+ process.exit(2);
+ }
+
+ // Append today's snapshot BEFORE computing burn so the rolling window stays
+ // populated even on first run (a single-row history will yield burn=null,
+ // which the formatter handles gracefully).
+ if (!DRY_RUN && !SKIP_SNAPSHOT) {
+ try {
+ appendSnapshot(ledger, accountsConfig, SNAPSHOTS_PATH);
+ } catch (e) {
+ log(`[fatal] snapshot append failed: ${e.message}`);
+ process.exit(2);
+ }
+ }
+
+ const history = readSnapshotHistory(SNAPSHOTS_PATH);
+ const burn = computeBurnRate(history, accountsConfig, ledger);
+ const projection = projectMonthEnd(ledger, accountsConfig, burn.totalDailyBurnUsd);
+ const fallback = await fetchFallbackRatio();
+ const perAccountBalances = gatherPerAccountBalances(ledger, accountsConfig);
+ const severity = computeSeverity(projection, fallback);
+
+ const cycle = ymKey();
+ const body = formatSlackBody({ cycle, perAccountBalances, burn, projection, fallback, severity, dryRun: DRY_RUN });
+
+ const slack = await postSlack(body);
+ const title = `Credit pool daily — ${projection.currentConsumedPct}% consumed, projected ${projection.projectedConsumedPct}%`;
+ fanOutNotify(severity, title, body);
+
+ if (!slack.ok && !slack.skipped) process.exit(1);
+ log('[daily-digest] done');
+}
+
+// Only run main() when executed directly (not when imported by tests).
+const _entryPath = fileURLToPath(import.meta.url);
+if (process.argv[1] && process.argv[1] === _entryPath) {
+ if (flag('--help') || flag('-h')) {
+ console.log(readFileSync(_entryPath, 'utf8').split('\n').slice(0, 40).join('\n'));
+ process.exit(0);
+ }
+ main().catch((e) => {
+ log(`[fatal] ${e.stack || e.message}`);
+ process.exit(2);
+ });
+}
diff --git a/claude-ops/scripts/install-daily-credit-digest.sh b/claude-ops/scripts/install-daily-credit-digest.sh
new file mode 100755
index 00000000..cd33465c
--- /dev/null
+++ b/claude-ops/scripts/install-daily-credit-digest.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# install-daily-credit-digest.sh — Install the daily Anthropic credit-pool
+# digest cron as a launchd LaunchAgent (HEA-4047).
+#
+# Renders templates/com.claude-ops.daily-credit-digest.plist with the
+# absolute paths to node + the wrapper script, then bootstraps it under the
+# current user's GUI session. macOS-only.
+
+set -euo pipefail
+
+if [[ "$(uname -s)" != "Darwin" ]]; then
+ echo "skip: daily-credit-digest cron is macOS-only (launchd)" >&2
+ echo "Linux users: install equivalent systemd timer (OnCalendar=*-*-* 09:00:00)."
+ exit 0
+fi
+
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+if [[ -z "$PLUGIN_ROOT" || ! -d "$PLUGIN_ROOT" ]]; then
+ echo "error: could not resolve CLAUDE_PLUGIN_ROOT" >&2
+ exit 1
+fi
+
+SCRIPT_PATH="$PLUGIN_ROOT/scripts/account-rotation/daily-credit-digest.mjs"
+PLIST_TEMPLATE="$PLUGIN_ROOT/templates/com.claude-ops.daily-credit-digest.plist"
+PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.daily-credit-digest.plist"
+DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
+LOG_DIR="$DATA_DIR/logs"
+
+for f in "$SCRIPT_PATH" "$PLIST_TEMPLATE"; do
+ [[ -f "$f" ]] || { echo "error: required file not found: $f" >&2; exit 1; }
+done
+
+NODE_BIN="$(command -v node 2>/dev/null || true)"
+if [[ -z "$NODE_BIN" ]]; then
+ echo "error: node not found in PATH" >&2
+ exit 1
+fi
+
+mkdir -p "$LOG_DIR" "$(dirname "$PLIST_DEST")"
+
+PLIST_TEMPLATE_PATH="$PLIST_TEMPLATE" \
+DIGEST_SCRIPT_PATH="$SCRIPT_PATH" \
+DIGEST_LOG_DIR="$LOG_DIR" \
+DIGEST_HOME="$HOME" \
+DIGEST_NODE_BIN="$NODE_BIN" \
+SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}" \
+AWS_REGION="${AWS_REGION:-eu-west-1}" \
+"$NODE_BIN" -e \
+ 'const fs=require("fs");const e=(s)=>String(s??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");const t=fs.readFileSync(process.env.PLIST_TEMPLATE_PATH,"utf8");process.stdout.write(t.replace(/__SCRIPT_PATH__/g,e(process.env.DIGEST_SCRIPT_PATH)).replace(/__LOG_DIR__/g,e(process.env.DIGEST_LOG_DIR)).replace(/__HOME__/g,e(process.env.DIGEST_HOME)).replace(/__NODE_BIN__/g,e(process.env.DIGEST_NODE_BIN)).replace(/__SLACK_WEBHOOK_URL__/g,e(process.env.SLACK_WEBHOOK_URL||"")).replace(/__AWS_REGION__/g,e(process.env.AWS_REGION||"eu-west-1")));' \
+ > "$PLIST_DEST"
+
+launchctl bootout "gui/$(id -u)/com.claude-ops.daily-credit-digest" 2>/dev/null || true
+launchctl bootstrap "gui/$(id -u)" "$PLIST_DEST"
+
+echo "ok: daily-credit-digest installed"
+echo " plist: $PLIST_DEST"
+echo " script: $SCRIPT_PATH"
+echo " logs: $LOG_DIR/daily-credit-digest-*.log"
+echo " next run: tomorrow at 09:00 local time (then every 24h)"
+if [[ -z "${SLACK_WEBHOOK_URL:-}" ]]; then
+ echo " note: SLACK_WEBHOOK_URL was unset — Slack digest is skipped unless you export it and re-run this installer."
+fi
+echo " note: CloudWatch fallback ratio reads from namespace My-Project/LLM (HEA-4045); section auto-skips if unavailable."
diff --git a/claude-ops/templates/com.claude-ops.daily-credit-digest.plist b/claude-ops/templates/com.claude-ops.daily-credit-digest.plist
new file mode 100644
index 00000000..5c28176d
--- /dev/null
+++ b/claude-ops/templates/com.claude-ops.daily-credit-digest.plist
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Daily Anthropic credit-pool digest cron (HEA-4047).
+
+ Schedule: every day, 09:00 local time (Europe/Amsterdam for Sam).
+ Equivalent cron: 0 9 * * *
+
+ The installer (scripts/install-daily-credit-digest.sh) substitutes
+ __SCRIPT_PATH__, __LOG_DIR__, __HOME__, __NODE_BIN__, __SLACK_WEBHOOK_URL__,
+ __AWS_REGION__ (from SLACK_WEBHOOK_URL / AWS_REGION at install time; empty if
+ unset) and writes the rendered copy to
+ ~/Library/LaunchAgents/com.claude-ops.daily-credit-digest.plist
+ before running:
+ launchctl bootstrap "gui/$(id -u)" <plist>
+
+ To uninstall:
+ launchctl bootout "gui/$(id -u)/com.claude-ops.daily-credit-digest"
+ rm ~/Library/LaunchAgents/com.claude-ops.daily-credit-digest.plist
+-->
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.claude-ops.daily-credit-digest</string>
+
+ <key>ProgramArguments</key>
+ <array>
+ <string>__NODE_BIN__</string>
+ <string>__SCRIPT_PATH__</string>
+ </array>
+
+ <key>StartCalendarInterval</key>
+ <dict>
+ <key>Hour</key>
+ <integer>9</integer>
+ <key>Minute</key>
+ <integer>0</integer>
+ </dict>
+
+ <key>RunAtLoad</key>
+ <false/>
+
+ <key>StandardOutPath</key>
+ <string>__LOG_DIR__/daily-credit-digest-stdout.log</string>
+ <key>StandardErrorPath</key>
+ <string>__LOG_DIR__/daily-credit-digest-stderr.log</string>
+
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key>
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
+ <key>HOME</key>
+ <string>__HOME__</string>
+ <key>NODE_NO_WARNINGS</key>
+ <string>1</string>
+ <key>SLACK_WEBHOOK_URL</key>
+ <string>__SLACK_WEBHOOK_URL__</string>
+ <key>AWS_REGION</key>
+ <string>__AWS_REGION__</string>
+ </dict>
+
+ <key>ProcessType</key>
+ <string>Background</string>
+</dict>
+</plist>