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): monthly Anthropic credit reclaim + consumption summary (#255)

Aurora Capital67fb0ed59fbc
diff --git a/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs b/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs
new file mode 100644
index 00000000..088de19e
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs
@@ -0,0 +1,123 @@
+/**
+ * monthly-credit-reclaim.mjs — summary math tests (HEA-4049).
+ *
+ * Run: node --test claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs
+ */
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ buildPriorMonthSummary,
+ summarizePostClaim,
+ formatSlackBody,
+ ymKey,
+ priorMonthKey,
+} from '../monthly-credit-reclaim.mjs';
+import { SCHEMA_VERSION, MAX_PLAN_MONTHLY_USD } from '../ledger.mjs';
+
+function makeLedger(month, accounts) {
+ return { schema_version: SCHEMA_VERSION, month, accounts };
+}
+
+test('buildPriorMonthSummary: all claimed + half consumed → 0% waste', () => {
+ const cfg = [{ email: 'a@x' }, { email: 'b@x' }];
+ const ledger = makeLedger('2026-05', [
+ { email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 100 },
+ { email: 'b@x', cycle: '2026-05', claimed: true, remaining_usd: 100 },
+ ]);
+ const s = buildPriorMonthSummary(ledger, cfg);
+ assert.equal(s.poolUsd, 400);
+ assert.equal(s.claimedUsd, 400);
+ assert.equal(s.unclaimedPoolUsd, 0);
+ assert.equal(s.wastePct, 0);
+ assert.equal(s.consumedUsd, 200);
+ assert.equal(s.unclaimedCount, 0);
+});
+
+test('buildPriorMonthSummary: one unclaimed → 50% waste', () => {
+ const cfg = [{ email: 'a@x' }, { email: 'b@x' }];
+ const ledger = makeLedger('2026-05', [
+ { email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 50 },
+ { email: 'b@x', cycle: '2026-05', claimed: false, remaining_usd: null },
+ ]);
+ const s = buildPriorMonthSummary(ledger, cfg);
+ assert.equal(s.poolUsd, 400);
+ assert.equal(s.claimedUsd, 200);
+ assert.equal(s.unclaimedPoolUsd, 200);
+ assert.equal(s.wastePct, 50);
+ assert.equal(s.consumedUsd, 150);
+ assert.equal(s.unclaimedCount, 1);
+});
+
+test('buildPriorMonthSummary: 7-account $1400 pool — all unclaimed → 100% waste', () => {
+ const cfg = Array.from({ length: 7 }, (_, i) => ({ email: `acc${i}@x` }));
+ const ledger = makeLedger('2026-05', []);
+ const s = buildPriorMonthSummary(ledger, cfg);
+ assert.equal(s.poolUsd, 7 * MAX_PLAN_MONTHLY_USD);
+ assert.equal(s.poolUsd, 1400);
+ assert.equal(s.claimedUsd, 0);
+ assert.equal(s.unclaimedPoolUsd, 1400);
+ assert.equal(s.wastePct, 100);
+ assert.equal(s.unclaimedCount, 7);
+});
+
+test('buildPriorMonthSummary: 7-account fully optimized → 0% waste', () => {
+ const cfg = Array.from({ length: 7 }, (_, i) => ({ email: `acc${i}@x` }));
+ const ledger = makeLedger(
+ '2026-05',
+ cfg.map(({ email }) => ({ email, cycle: '2026-05', claimed: true, remaining_usd: 0 })),
+ );
+ const s = buildPriorMonthSummary(ledger, cfg);
+ assert.equal(s.claimedUsd, 1400);
+ assert.equal(s.consumedUsd, 1400);
+ assert.equal(s.wastePct, 0);
+});
+
+test('buildPriorMonthSummary: empty pool → 0% waste, no division by zero', () => {
+ const s = buildPriorMonthSummary(makeLedger('2026-05', []), []);
+ assert.equal(s.poolUsd, 0);
+ assert.equal(s.wastePct, 0);
+});
+
+test('summarizePostClaim: counts only entries with current cycle', () => {
+ const cfg = [{ email: 'a@x' }, { email: 'b@x' }, { email: 'c@x' }];
+ const cycle = ymKey();
+ const ledger = makeLedger(cycle, [
+ { email: 'a@x', cycle, claimed: true, remaining_usd: 200 },
+ { email: 'b@x', cycle: '2026-04', claimed: true, remaining_usd: 200 }, // stale cycle
+ { email: 'c@x', cycle, claimed: false, remaining_usd: null },
+ ]);
+ const r = summarizePostClaim(ledger, cfg);
+ assert.equal(r.claimedCount, 1);
+ assert.deepEqual(r.failed.sort(), ['b@x', 'c@x']);
+});
+
+test('formatSlackBody: includes pool, waste %, prior cycle, no secrets', () => {
+ const cfg = [{ email: 'a@x' }, { email: 'b@x' }];
+ const ledger = makeLedger('2026-05', [
+ { email: 'a@x', cycle: '2026-05', claimed: true, remaining_usd: 0 },
+ { email: 'b@x', cycle: '2026-05', claimed: false, remaining_usd: null },
+ ]);
+ const s = buildPriorMonthSummary(ledger, cfg);
+ const body = formatSlackBody(s, { claimedCount: 2, failed: [] });
+ assert.match(body, /Pool: \$400/);
+ assert.match(body, /50% waste/);
+ assert.match(body, /2026-05/);
+ assert.match(body, /2\/2 accounts re-claimed/);
+ // Ensure no API token / webhook leaks
+ assert.doesNotMatch(body, /hooks\.slack\.com/);
+});
+
+test('formatSlackBody: reports failed accounts', () => {
+ const cfg = [{ email: 'a@x' }, { email: 'b@x' }];
+ const ledger = makeLedger('2026-05', []);
+ const s = buildPriorMonthSummary(ledger, cfg);
+ const body = formatSlackBody(s, { claimedCount: 1, failed: ['b@x'] });
+ assert.match(body, /Failed: b@x/);
+});
+
+test('priorMonthKey: returns prior YYYY-MM', () => {
+ assert.equal(priorMonthKey(new Date(Date.UTC(2026, 5, 15))), '2026-05'); // Jun 15 → May
+ assert.equal(priorMonthKey(new Date(Date.UTC(2026, 0, 15))), '2025-12'); // Jan → Dec prev year
+});
diff --git a/claude-ops/scripts/account-rotation/kapture-claim-credits.mjs b/claude-ops/scripts/account-rotation/kapture-claim-credits.mjs
index 2a89c562..fdab9af0 100755
--- a/claude-ops/scripts/account-rotation/kapture-claim-credits.mjs
+++ b/claude-ops/scripts/account-rotation/kapture-claim-credits.mjs
@@ -66,6 +66,7 @@ import {
writeLedger,
findAccount,
upsertAccount,
+ ymKey,
} from './ledger.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -185,10 +186,6 @@ function saveLedger(ledger) {
writeLedger(LEDGER_PATH, ledger);
}
-function ymKey(date = new Date()) {
- return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`;
-}
-
function receiptPath(email) {
mkdirSync(RECEIPTS_DIR, { recursive: true });
const safe = email.replace(/[^a-zA-Z0-9._-]/g, '_');
diff --git a/claude-ops/scripts/account-rotation/ledger.mjs b/claude-ops/scripts/account-rotation/ledger.mjs
index d1e58962..2a23b891 100644
--- a/claude-ops/scripts/account-rotation/ledger.mjs
+++ b/claude-ops/scripts/account-rotation/ledger.mjs
@@ -42,7 +42,7 @@ export const SCHEMA_VERSION = 2;
* @returns {object}
*/
function migrateV1(v1) {
- const month = v1.month || _ymKey();
+ const month = v1.month || ymKey();
const accounts = [];
const raw = v1.accounts || {};
for (const [email, cycles] of Object.entries(raw)) {
@@ -69,9 +69,12 @@ function migrateV1(v1) {
}
/**
- * Returns "YYYY-MM" for the current UTC month.
+ * Returns "YYYY-MM" for the given date's UTC month (default: now).
+ *
+ * @param {Date} [date]
+ * @returns {string}
*/
-function _ymKey(date = new Date()) {
+export function ymKey(date = new Date()) {
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`;
}
@@ -87,7 +90,7 @@ function _ymKey(date = new Date()) {
*/
export function readLedger(path) {
if (!existsSync(path)) {
- return { schema_version: SCHEMA_VERSION, month: _ymKey(), accounts: [] };
+ return { schema_version: SCHEMA_VERSION, month: ymKey(), accounts: [] };
}
let raw;
diff --git a/claude-ops/scripts/account-rotation/monthly-credit-reclaim.mjs b/claude-ops/scripts/account-rotation/monthly-credit-reclaim.mjs
new file mode 100755
index 00000000..308d1973
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/monthly-credit-reclaim.mjs
@@ -0,0 +1,293 @@
+#!/usr/bin/env node
+/* eslint-disable no-console */
+
+// ──────────────────────────────────────────────────────────────────────────────
+// monthly-credit-reclaim.mjs
+// Day-1 09:00 monthly cron entrypoint (HEA-4049).
+//
+// Sequence:
+// 1. Snapshot pre-run ledger so we can compute prior-month consumption.
+// 2. Invoke kapture-claim-credits.mjs --live to re-claim the $200 Agent SDK
+// credit on each of the ~7 Max accounts registered in config.json.
+// 3. Re-read the ledger and compute the prior-month delta:
+// claimed_usd = sum of accounts that successfully claimed last cycle
+// consumed_usd = sum of (granted − remaining) just before re-claim
+// waste_pct = unclaimed_pool / total_pool (× 100, rounded)
+// Pool size = MAX_PLAN_MONTHLY_USD × account_count.
+// 4. Post a Slack summary (env: SLACK_WEBHOOK_URL) AND fan-out via
+// scripts/ops-notify.sh (Discord / ntfy / Telegram / Pushover are picked
+// up automatically when their env vars are present).
+//
+// CLI:
+// --dry-run Print the planned Slack payload + skip the live claim.
+// (Forwards --dry-run intent to kapture-claim-credits.mjs by
+// NOT passing --live.)
+// --skip-claim Compute + post the summary only; do not invoke the claimer
+// (useful for re-posting after a manual claim).
+// --help Print this header.
+//
+// Exit codes:
+// 0 success (claim ran AND summary posted, or dry-run plan printed)
+// 1 partial — claim ran but Slack post failed (logged, do not retry inside
+// the same window; cron will catch the next month)
+// 2 hard failure (missing config, ledger schema mismatch, claimer crashed)
+// ──────────────────────────────────────────────────────────────────────────────
+
+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 CLAIMER = join(__dirname, 'kapture-claim-credits.mjs');
+const CONFIG_PATH = join(__dirname, 'config.json');
+const LEDGER_PATH = join(homedir(), '.claude', 'credits-ledger.json');
+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, 'monthly-credit-reclaim.log');
+const NOTIFY_SCRIPT = join(__dirname, '..', 'ops-notify.sh');
+
+const args = process.argv.slice(2);
+const flag = (n) => args.includes(n);
+const DRY_RUN = flag('--dry-run');
+const SKIP_CLAIM = flag('--skip-claim');
+
+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 priorMonthKey(date = new Date()) {
+ const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() - 1, 1));
+ return ymKey(d);
+}
+
+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 [];
+ }
+}
+
+function snapshotLedger() {
+ // readLedger handles missing file (returns empty v2 ledger) and v1→v2 migration.
+ // Safe to call even when the claimer has never run.
+ try {
+ return readLedger(LEDGER_PATH);
+ } catch (e) {
+ log(`[fatal] ledger read failed: ${e.message}`);
+ process.exit(2);
+ }
+}
+
+function runClaimer() {
+ if (SKIP_CLAIM) {
+ log('[monthly-reclaim] --skip-claim set; not invoking kapture-claim-credits.mjs');
+ return { code: 0, signal: null };
+ }
+ if (DRY_RUN) {
+ log('[monthly-reclaim] DRY RUN — would invoke:');
+ log(` node ${CLAIMER} --live`);
+ return { code: 0, signal: null, dryRun: true };
+ }
+ log(`[monthly-reclaim] invoking ${CLAIMER} --live`);
+ const res = spawnSync(process.execPath, [CLAIMER, '--live'], {
+ stdio: 'inherit',
+ env: process.env,
+ });
+ return { code: res.status, signal: res.signal };
+}
+
+/**
+ * Build the consumption summary for the prior month from the pre-run ledger.
+ * Pre-run ledger holds last cycle's `claimed` + `remaining_usd` BEFORE the
+ * new month's claim overwrites them.
+ */
+function buildPriorMonthSummary(preLedger, accountsConfig) {
+ // "Prior cycle" = whatever cycle the pre-run ledger holds, UNLESS that cycle
+ // is the current month or later (e.g. ledger was just provisioned, not yet
+ // claimed against), in which case we fall back to "last calendar month".
+ const ledgerCycle = preLedger.month;
+ const currentCycle = ymKey();
+ const priorCycle = ledgerCycle && ledgerCycle < currentCycle ? ledgerCycle : priorMonthKey();
+ const accounts = accountsConfig.length ? accountsConfig : (preLedger.accounts || []).map((a) => ({ email: a.email }));
+ const poolUsd = MAX_PLAN_MONTHLY_USD * accounts.length;
+
+ let claimedUsd = 0;
+ let consumedUsd = 0;
+ let unclaimedCount = 0;
+ const perAccount = [];
+
+ for (const cfg of accounts) {
+ const entry = findAccount(preLedger, cfg.email);
+ const claimed = !!entry?.claimed;
+ const remaining = typeof entry?.remaining_usd === 'number' ? entry.remaining_usd : null;
+ const granted = claimed ? MAX_PLAN_MONTHLY_USD : 0;
+ const consumed = claimed && remaining != null ? Math.max(0, granted - remaining) : null;
+ if (claimed) claimedUsd += granted;
+ else unclaimedCount += 1;
+ if (consumed != null) consumedUsd += consumed;
+ perAccount.push({ email: cfg.email, claimed, remaining_usd: remaining, consumed_usd: consumed });
+ }
+
+ const unclaimedPoolUsd = poolUsd - claimedUsd;
+ const wastePct = poolUsd > 0 ? Math.round((unclaimedPoolUsd / poolUsd) * 100) : 0;
+
+ return {
+ priorCycle,
+ accountCount: accounts.length,
+ poolUsd,
+ claimedUsd,
+ unclaimedPoolUsd,
+ unclaimedCount,
+ consumedUsd,
+ wastePct,
+ perAccount,
+ };
+}
+
+function formatSlackBody(summary, postClaimSummary, { dryRun = false, skipClaim = false } = {}) {
+ const lines = [];
+ lines.push(`Monthly Anthropic credit reclaim — ${ymKey()} (prior cycle ${summary.priorCycle})`);
+ lines.push('');
+ lines.push(`Pool: $${summary.poolUsd} (${summary.accountCount} × $${MAX_PLAN_MONTHLY_USD})`);
+ lines.push(`Claimed last month: $${summary.claimedUsd}`);
+ lines.push(
+ `Unclaimed pool: $${summary.unclaimedPoolUsd} (${summary.wastePct}% waste, ${summary.unclaimedCount} accounts skipped)`,
+ );
+ lines.push(`Consumed last month: $${summary.consumedUsd}`);
+ lines.push('');
+ if (postClaimSummary) {
+ lines.push(`This cycle: ${postClaimSummary.claimedCount}/${summary.accountCount} accounts re-claimed`);
+ if (postClaimSummary.failed.length) {
+ lines.push(`Failed: ${postClaimSummary.failed.join(', ')}`);
+ }
+ } else if (dryRun) {
+ lines.push('(dry-run — no claim attempted)');
+ } else if (skipClaim) {
+ lines.push('(--skip-claim — ledger unchanged this run)');
+ }
+ return lines.join('\n');
+}
+
+function summarizePostClaim(postLedger, accountsConfig) {
+ const cycle = ymKey();
+ const accounts = accountsConfig.length
+ ? accountsConfig
+ : (postLedger.accounts || []).map((a) => ({ email: a.email }));
+ let claimedCount = 0;
+ const failed = [];
+ for (const cfg of accounts) {
+ const e = findAccount(postLedger, cfg.email);
+ if (e?.claimed && e.cycle === cycle) claimedCount += 1;
+ else failed.push(cfg.email);
+ }
+ return { claimedCount, failed };
+}
+
+async function postSlack(body) {
+ const webhook = process.env.SLACK_WEBHOOK_URL;
+ if (!webhook) {
+ log('[monthly-reclaim] SLACK_WEBHOOK_URL not set — skipping Slack post');
+ return { ok: true, skipped: true };
+ }
+ if (DRY_RUN) {
+ log('[monthly-reclaim] 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(`[monthly-reclaim] Slack post failed: ${res.status} ${txt.slice(0, 200)}`);
+ return { ok: false };
+ }
+ log('[monthly-reclaim] Slack post OK');
+ return { ok: true };
+ } catch (e) {
+ log(`[monthly-reclaim] Slack post threw: ${e.message}`);
+ return { ok: false };
+ }
+}
+
+function fanOutNotify(severity, title, body) {
+ if (DRY_RUN) {
+ log(`[monthly-reclaim] 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(`[monthly-reclaim] ops-notify fan-out failed: ${e.message}`);
+ }
+}
+
+async function main() {
+ log(`[monthly-reclaim] start cycle=${ymKey()} dry-run=${DRY_RUN} skip-claim=${SKIP_CLAIM}`);
+
+ const accountsConfig = loadAccountsConfig();
+ const preLedger = snapshotLedger();
+ const priorSummary = buildPriorMonthSummary(preLedger, accountsConfig);
+
+ const claim = runClaimer();
+ if (claim.code !== 0 && !claim.dryRun) {
+ log(`[monthly-reclaim] claimer exited code=${claim.code} signal=${claim.signal}`);
+ fanOutNotify(
+ 'HIGH',
+ 'Monthly credit reclaim FAILED',
+ `kapture-claim-credits.mjs exited ${claim.code}. Cycle ${ymKey()} claim incomplete.`,
+ );
+ // Continue to post the prior-month summary anyway — operator still needs visibility.
+ }
+
+ const postLedger = snapshotLedger();
+ const postClaim = SKIP_CLAIM || DRY_RUN ? null : summarizePostClaim(postLedger, accountsConfig);
+
+ const body = formatSlackBody(priorSummary, postClaim, { dryRun: DRY_RUN, skipClaim: SKIP_CLAIM });
+ const slack = await postSlack(body);
+
+ const title = `Monthly credit reclaim — ${priorSummary.wastePct}% waste last month`;
+ const severity = priorSummary.wastePct >= 30 ? 'HIGH' : 'LOW';
+ fanOutNotify(severity, title, body);
+
+ if (claim.code !== 0 && !claim.dryRun) process.exit(2);
+ if (!slack.ok && !slack.skipped) process.exit(1);
+ log('[monthly-reclaim] 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, 44).join('\n'));
+ process.exit(0);
+ }
+ main().catch((e) => {
+ log(`[fatal] ${e.stack || e.message}`);
+ process.exit(2);
+ });
+}
+
+// Test exports
+export { buildPriorMonthSummary, summarizePostClaim, formatSlackBody, ymKey, priorMonthKey };
diff --git a/claude-ops/scripts/install-monthly-credit-reclaim.sh b/claude-ops/scripts/install-monthly-credit-reclaim.sh
new file mode 100755
index 00000000..cc1a7322
--- /dev/null
+++ b/claude-ops/scripts/install-monthly-credit-reclaim.sh
@@ -0,0 +1,60 @@
+#!/usr/bin/env bash
+# install-monthly-credit-reclaim.sh — Install the monthly Anthropic credit
+# reclaim cron as a launchd LaunchAgent (HEA-4049).
+#
+# Renders templates/com.claude-ops.monthly-credit-reclaim.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: monthly-credit-reclaim cron is macOS-only (launchd)" >&2
+ echo "Linux users: install equivalent systemd timer (OnCalendar=*-*-01 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/monthly-credit-reclaim.mjs"
+PLIST_TEMPLATE="$PLUGIN_ROOT/templates/com.claude-ops.monthly-credit-reclaim.plist"
+PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.monthly-credit-reclaim.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")"
+
+sed -e "s|__SCRIPT_PATH__|$SCRIPT_PATH|g" \
+ -e "s|__LOG_DIR__|$LOG_DIR|g" \
+ -e "s|__HOME__|$HOME|g" \
+ -e "s|__NODE_BIN__|$NODE_BIN|g" \
+ "$PLIST_TEMPLATE" \
+ | SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}" "$NODE_BIN" -e \
+ 'const fs=require("fs");const t=fs.readFileSync(0,"utf8");const e=s=>s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");process.stdout.write(t.replace("__SLACK_WEBHOOK_URL__",e(process.env.SLACK_WEBHOOK_URL||"")));' \
+ > "$PLIST_DEST"
+
+launchctl bootout "gui/$(id -u)/com.claude-ops.monthly-credit-reclaim" 2>/dev/null || true
+launchctl bootstrap "gui/$(id -u)" "$PLIST_DEST"
+
+echo "ok: monthly-credit-reclaim installed"
+echo " plist: $PLIST_DEST"
+echo " script: $SCRIPT_PATH"
+echo " logs: $LOG_DIR/monthly-credit-reclaim-*.log"
+echo " next run: day 1 of next month, 09:00 local time"
+if [[ -z "${SLACK_WEBHOOK_URL:-}" ]]; then
+ echo " note: SLACK_WEBHOOK_URL was unset — Slack summary is skipped unless you export it and re-run this installer."
+fi
diff --git a/claude-ops/templates/com.claude-ops.monthly-credit-reclaim.plist b/claude-ops/templates/com.claude-ops.monthly-credit-reclaim.plist
new file mode 100644
index 00000000..18826db0
--- /dev/null
+++ b/claude-ops/templates/com.claude-ops.monthly-credit-reclaim.plist
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Monthly Anthropic credit reclaim cron (HEA-4049).
+
+ Schedule: day 1 of each month, 09:00 local time (Europe/Amsterdam for Sam).
+ Equivalent cron: 0 9 1 * *
+
+ The installer (scripts/install-monthly-credit-reclaim.sh) substitutes
+ __SCRIPT_PATH__, __LOG_DIR__, __HOME__, __NODE_BIN__, __SLACK_WEBHOOK_URL__
+ (from SLACK_WEBHOOK_URL at install time; empty if unset) and writes the
+ rendered copy to ~/Library/LaunchAgents/com.claude-ops.monthly-credit-reclaim.plist
+ before running:
+ launchctl bootstrap "gui/$(id -u)" <plist>
+
+ To uninstall:
+ launchctl bootout "gui/$(id -u)/com.claude-ops.monthly-credit-reclaim"
+ rm ~/Library/LaunchAgents/com.claude-ops.monthly-credit-reclaim.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.monthly-credit-reclaim</string>
+
+ <key>ProgramArguments</key>
+ <array>
+ <string>__NODE_BIN__</string>
+ <string>__SCRIPT_PATH__</string>
+ </array>
+
+ <key>StartCalendarInterval</key>
+ <dict>
+ <key>Day</key>
+ <integer>1</integer>
+ <key>Hour</key>
+ <integer>9</integer>
+ <key>Minute</key>
+ <integer>0</integer>
+ </dict>
+
+ <key>RunAtLoad</key>
+ <false/>
+
+ <key>StandardOutPath</key>
+ <string>__LOG_DIR__/monthly-credit-reclaim-stdout.log</string>
+ <key>StandardErrorPath</key>
+ <string>__LOG_DIR__/monthly-credit-reclaim-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>
+ </dict>
+
+ <key>ProcessType</key>
+ <string>Background</string>
+</dict>
+</plist>