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(account-rotation): claude-p-as wrapper — run claude -p as highest-credit account (#222)

Aurora Capitaladecb002e708
diff --git a/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs b/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs
new file mode 100644
index 00000000..a2d9a6fe
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs
@@ -0,0 +1,199 @@
+/**
+ * claude-p-as wrapper tests (node --test).
+ *
+ * Run: node --test claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs
+ *
+ * Covers: ledger account selection, --pin honoring, $0 refuse paths,
+ * extra_usage refuse, ledger decrement, and lock contention.
+ */
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { writeFileSync, readFileSync, mkdtempSync, openSync, closeSync, unlinkSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { spawnSync } from 'child_process';
+import { fileURLToPath } from 'url';
+import { dirname } from 'path';
+
+import { parseArgs, pickAccount, effectiveBudget, parseUsageCost, decrementLedger } from '../claude-p-as.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SCRIPT = join(__dirname, '..', 'claude-p-as.mjs');
+
+function makeLedger(accounts) {
+ return {
+ schema_version: 1,
+ month: '2026-06',
+ month_resets_at: '2026-07-01T00:00:00Z',
+ accounts,
+ };
+}
+
+function tmpFile(name = 'ledger.json') {
+ const dir = mkdtempSync(join(tmpdir(), 'claude-p-as-'));
+ return join(dir, name);
+}
+
+test('pickAccount selects highest remaining_usd by default', () => {
+ const ledger = makeLedger([
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 50 },
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 175 },
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 100 },
+ ]);
+ const a = pickAccount(ledger, null);
+ assert.equal(a.email, '[email protected]');
+});
+
+test('pickAccount honors --pin even when not the richest', () => {
+ const ledger = makeLedger([
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 50 },
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 175 },
+ ]);
+ const a = pickAccount(ledger, '[email protected]');
+ assert.equal(a.email, '[email protected]');
+ assert.equal(a.remaining_usd, 50);
+});
+
+test('pickAccount refuses (exit 2) when all accounts $0', () => {
+ const ledger = makeLedger([
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 0 },
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 0 },
+ ]);
+ // pickAccount calls die() which calls process.exit. Run as subprocess.
+ const ledgerPath = tmpFile();
+ writeFileSync(ledgerPath, JSON.stringify(ledger));
+ const r = spawnSync('node', [SCRIPT, '--ledger', ledgerPath, '--', '/help'], { encoding: 'utf8' });
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /all accounts \$0/);
+});
+
+test('pickAccount refuses (exit 2) when pinned account at $0', () => {
+ const ledger = makeLedger([
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 0 },
+ { email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 200 },
+ ]);
+ const ledgerPath = tmpFile();
+ writeFileSync(ledgerPath, JSON.stringify(ledger));
+ const r = spawnSync('node', [SCRIPT, '--ledger', ledgerPath, '--pin', '[email protected]', '--', '/help'], {
+ encoding: 'utf8',
+ });
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /pinned account a@x\.com credit exhausted/);
+});
+
+test('assertNotExtraUsage refuses accounts with extra_usage flag in ledger', () => {
+ const account = { email: '[email protected]', remaining_usd: 100, extra_usage: true };
+ const r = spawnSync(
+ 'node',
+ [
+ '--input-type=module',
+ '-e',
+ `import { assertNotExtraUsage } from "${SCRIPT}"; assertNotExtraUsage(${JSON.stringify(account)}, "/nonexistent");`,
+ ],
+ { encoding: 'utf8' },
+ );
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /extra_usage=true/);
+});
+
+test('assertNotExtraUsage refuses accounts with extraUsageEnabled=true in rotation config', () => {
+ const cfgPath = tmpFile('config.json');
+ writeFileSync(cfgPath, JSON.stringify({ accounts: [{ email: '[email protected]', extraUsageEnabled: true }] }));
+ const account = { email: '[email protected]', remaining_usd: 100 };
+ const r = spawnSync(
+ 'node',
+ [
+ '--input-type=module',
+ '-e',
+ `import { assertNotExtraUsage } from "${SCRIPT}"; assertNotExtraUsage(${JSON.stringify(account)}, "${cfgPath}");`,
+ ],
+ { encoding: 'utf8' },
+ );
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /extraUsageEnabled=true/);
+});
+
+test('effectiveBudget caps at $200 hard ceiling regardless of user input', () => {
+ assert.equal(effectiveBudget(null), 200);
+ assert.equal(effectiveBudget(undefined), 200);
+ assert.equal(effectiveBudget(50), 50);
+ assert.equal(effectiveBudget(500), 200);
+ assert.equal(effectiveBudget(-5), 0);
+});
+
+test('parseUsageCost extracts $cost from claude output strings', () => {
+ assert.equal(parseUsageCost('foo\n', 'Cost: $0.1234\n'), 0.1234);
+ assert.equal(parseUsageCost('', 'Total cost: $1.5'), 1.5);
+ assert.equal(parseUsageCost('no money here', ''), null);
+ assert.equal(parseUsageCost('The project has a $500 cost estimate.\n', 'Cost: $0.05\n'), 0.05);
+});
+
+test('decrementLedger atomically subtracts cost and stamps last_call_at', () => {
+ const ledgerPath = tmpFile();
+ const ledger = makeLedger([{ email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 150, last_call_at: null }]);
+ writeFileSync(ledgerPath, JSON.stringify(ledger));
+ decrementLedger(ledgerPath, '[email protected]', 0.42);
+ const after = JSON.parse(readFileSync(ledgerPath, 'utf8'));
+ assert.equal(after.accounts[0].remaining_usd, 149.58);
+ assert.ok(after.accounts[0].last_call_at);
+});
+
+test('decrementLedger never drops remaining below zero', () => {
+ const ledgerPath = tmpFile();
+ writeFileSync(
+ ledgerPath,
+ JSON.stringify(makeLedger([{ email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 0.05 }])),
+ );
+ decrementLedger(ledgerPath, '[email protected]', 10);
+ const after = JSON.parse(readFileSync(ledgerPath, 'utf8'));
+ assert.equal(after.accounts[0].remaining_usd, 0);
+});
+
+test('parseArgs splits --pin and -- delimiter cleanly', () => {
+ const a = parseArgs(['--pin', '[email protected]', '--', '-p', 'hello']);
+ assert.equal(a.pin, '[email protected]');
+ assert.deepEqual(a.rest, ['-p', 'hello']);
+});
+
+test('parseArgs accepts --max-budget-usd flag', () => {
+ const a = parseArgs(['--max-budget-usd', '50', '--', 'hello']);
+ assert.equal(a.budget, 50);
+});
+
+test('refuses when ledger file missing', () => {
+ const r = spawnSync('node', [SCRIPT, '--ledger', '/nonexistent/ledger.json', '--', 'hello'], {
+ encoding: 'utf8',
+ });
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /ledger missing/);
+});
+
+test('lock contention: second invocation refuses while lock file exists', () => {
+ const ledgerPath = tmpFile();
+ writeFileSync(
+ ledgerPath,
+ JSON.stringify(makeLedger([{ email: '[email protected]', monthly_credit_usd: 200, remaining_usd: 200 }])),
+ );
+ const lockPath = tmpFile('lock');
+ // Pre-create lock to simulate in-flight rotation
+ const fd = openSync(lockPath, 'wx');
+ closeSync(fd);
+ try {
+ const r = spawnSync(
+ 'node',
+ [SCRIPT, '--ledger', ledgerPath, '--lock', lockPath, '--config', '/nonexistent', '--', 'hello'],
+ { encoding: 'utf8' },
+ );
+ // Will fail at lock OR earlier at assertBudgetFlagAvailable if claude CLI isn't installed.
+ // Accept either: status 2 + (lock-held OR claude-cli-missing) — both are correct refusals.
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /(keychain lock held|--max-budget-usd.*not available|ledger)/);
+ } finally {
+ try {
+ unlinkSync(lockPath);
+ } catch {
+ /* ignore */
+ }
+ }
+});
diff --git a/claude-ops/scripts/account-rotation/claude-p-as.mjs b/claude-ops/scripts/account-rotation/claude-p-as.mjs
new file mode 100755
index 00000000..c035f566
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/claude-p-as.mjs
@@ -0,0 +1,332 @@
+#!/usr/bin/env node
+/**
+ * claude-p-as — run `claude -p` as the highest-credit-remaining Max-OAuth account.
+ *
+ * Usage: claude-p-as [--pin <email>] [--ledger <path>] [--config <path>]
+ * [--max-budget-usd <N>] -- <claude -p args>
+ *
+ * Behavior (per Wave 0 plan, activation 2026-06-15):
+ * 1. Read ~/.claude/credits-ledger.json. Refuse if missing.
+ * 2. Filter accounts with remaining_usd > 0. Pinned account honored if set.
+ * 3. Verify selected account is not flagged extra_usage: true (post-2026-04-21 guard).
+ * 4. flock on ~/.claude/keychain.lock (O_EXCL atomic).
+ * 5. Swap active Claude keychain to that account's stored OAuth token.
+ * 6. Run `claude -p <args> --max-budget-usd <cap>` (cap = min(200, user-supplied, account remaining_usd)).
+ * 7. On exit (any signal), restore prior keychain & release lock.
+ * 8. Best-effort parse usage from claude output → decrement remaining_usd atomically.
+ *
+ * Refusal cases (exit code 2):
+ * - Ledger file missing
+ * - All accounts at $0 ("credit exhausted, resets day 1 of next month")
+ * - Pinned account at $0
+ * - Selected account has extra_usage: true
+ * - `claude --max-budget-usd` flag unavailable in installed CLI
+ *
+ * No network calls from this script (only the `claude -p` subprocess).
+ * No user prompts.
+ */
+
+import { existsSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync, renameSync } from 'fs';
+import { spawnSync, spawn } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { homedir, constants } from 'os';
+
+import { swapToEmail, restoreToken } from './keychain-swap.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const DEFAULT_LEDGER = join(homedir(), '.claude', 'credits-ledger.json');
+const DEFAULT_CONFIG = join(__dirname, 'config.json');
+const DEFAULT_LOCK = join(homedir(), '.claude', 'keychain.lock');
+const HARD_CAP_USD = 200;
+
+function die(code, msg) {
+ process.stderr.write(`[claude-p-as] ${msg}\n`);
+ process.exit(code);
+}
+
+function parseArgs(argv) {
+ const out = { pin: null, ledger: DEFAULT_LEDGER, config: DEFAULT_CONFIG, lock: DEFAULT_LOCK, budget: null, rest: [] };
+ let i = 0;
+ while (i < argv.length) {
+ const a = argv[i];
+ if (a === '--') {
+ out.rest = argv.slice(i + 1);
+ break;
+ }
+ if (a === '--pin' && argv[i + 1]) {
+ out.pin = argv[++i + 0];
+ i++;
+ continue;
+ }
+ if (a === '--ledger' && argv[i + 1]) {
+ out.ledger = argv[++i + 0];
+ i++;
+ continue;
+ }
+ if (a === '--config' && argv[i + 1]) {
+ out.config = argv[++i + 0];
+ i++;
+ continue;
+ }
+ if (a === '--lock' && argv[i + 1]) {
+ out.lock = argv[++i + 0];
+ i++;
+ continue;
+ }
+ if (a === '--max-budget-usd' && argv[i + 1]) {
+ out.budget = Number(argv[++i + 0]);
+ i++;
+ continue;
+ }
+ // Unknown leading flag — treat remainder as claude args
+ out.rest = argv.slice(i);
+ break;
+ }
+ return out;
+}
+
+function readJson(path) {
+ return JSON.parse(readFileSync(path, 'utf8'));
+}
+
+function atomicWriteJson(path, obj) {
+ const tmp = `${path}.tmp.${process.pid}`;
+ writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n');
+ renameSync(tmp, path);
+}
+
+function pickAccount(ledger, pin) {
+ const accts = (ledger.accounts || []).filter((a) => a && a.email);
+ if (!accts.length) die(2, 'ledger has no accounts');
+ if (pin) {
+ const found = accts.find((a) => a.email.toLowerCase() === pin.toLowerCase());
+ if (!found) die(2, `pinned account not in ledger: ${pin}`);
+ if (!(Number(found.remaining_usd) > 0))
+ die(2, `pinned account ${pin} credit exhausted, resets day 1 of next month`);
+ return found;
+ }
+ const live = accts.filter((a) => Number(a.remaining_usd) > 0);
+ if (!live.length) die(2, 'all accounts $0 — credit exhausted, resets day 1 of next month');
+ live.sort((x, y) => Number(y.remaining_usd) - Number(x.remaining_usd));
+ return live[0];
+}
+
+function assertNotExtraUsage(account, configPath) {
+ // Ledger may carry its own flag; if not, consult account-rotation config.json
+ if (account.extra_usage === true || account.extraUsageEnabled === true)
+ die(2, `account ${account.email} has extra_usage=true — refusing to bill against paid overage`);
+ if (!existsSync(configPath)) return;
+ try {
+ const cfg = readJson(configPath);
+ const match = (cfg.accounts || []).find((a) => a.email && a.email.toLowerCase() === account.email.toLowerCase());
+ if (match && (match.extraUsageEnabled === true || match.extra_usage === true))
+ die(2, `account ${account.email} has extraUsageEnabled=true in config — refusing to bill against paid overage`);
+ } catch (e) {
+ process.stderr.write(`[claude-p-as] warning: could not read config ${configPath}: ${e.message}\n`);
+ }
+}
+
+function assertBudgetFlagAvailable() {
+ const r = spawnSync('claude', ['--help'], { encoding: 'utf8', timeout: 8000 });
+ const helpText = (r.stdout || '') + (r.stderr || '');
+ if (!helpText.match(/--max-budget-usd/))
+ die(2, '`claude --max-budget-usd` not available in installed CLI — refusing to run without hard cap');
+}
+
+function acquireLock(lockPath) {
+ try {
+ const fd = openSync(lockPath, 'wx');
+ writeFileSync(lockPath, String(process.pid));
+ return fd;
+ } catch (e) {
+ if (e.code === 'EEXIST') {
+ let owner = '';
+ try {
+ owner = readFileSync(lockPath, 'utf8').trim();
+ } catch {
+ /* ignore */
+ }
+ die(2, `keychain lock held (${lockPath}, pid=${owner || 'unknown'}) — another rotation/claude-p-as in flight`);
+ }
+ die(2, `failed to acquire lock ${lockPath}: ${e.message}`);
+ }
+}
+
+function releaseLock(fd, lockPath) {
+ try {
+ closeSync(fd);
+ } catch {
+ /* ignore */
+ }
+ try {
+ unlinkSync(lockPath);
+ } catch {
+ /* ignore */
+ }
+}
+
+function effectiveBudget(userBudget, remainingUsd) {
+ const cap =
+ userBudget == null || Number.isNaN(userBudget) ? HARD_CAP_USD : Math.min(HARD_CAP_USD, Math.max(0, userBudget));
+ const rem = Number(remainingUsd);
+ if (Number.isFinite(rem) && rem >= 0) return Math.min(cap, rem);
+ return cap;
+}
+
+function parseUsageCost(_stdout, stderr) {
+ // Best-effort parse — usage/cost lines come from the CLI on stderr. stdout is
+ // model text and must not be scanned (phrases like "$500 cost estimate" false-match).
+ const text = stderr || '';
+ const m =
+ text.match(/\$([0-9]+(?:\.[0-9]+)?)[ \t]*(?:total|cost|spend)/i) ||
+ text.match(/total[^$\n]*\$([0-9.]+)/i) ||
+ text.match(/cost[^$\n]*\$([0-9.]+)/i);
+ if (m) {
+ const v = Number(m[1]);
+ if (!Number.isNaN(v) && v >= 0) return v;
+ }
+ return null;
+}
+
+function decrementLedger(ledgerPath, email, amount) {
+ let ledger;
+ try {
+ ledger = readJson(ledgerPath);
+ } catch (e) {
+ process.stderr.write(`[claude-p-as] warning: post-call ledger read failed: ${e.message}\n`);
+ return;
+ }
+ const a = (ledger.accounts || []).find((x) => x.email && x.email.toLowerCase() === email.toLowerCase());
+ if (!a) return;
+ a.remaining_usd = Math.max(0, Number(a.remaining_usd || 0) - Number(amount));
+ a.last_call_at = new Date().toISOString();
+ try {
+ atomicWriteJson(ledgerPath, ledger);
+ } catch (e) {
+ process.stderr.write(`[claude-p-as] warning: ledger write failed: ${e.message}\n`);
+ }
+}
+
+async function main(argv) {
+ const opts = parseArgs(argv);
+
+ if (!existsSync(opts.ledger))
+ die(
+ 2,
+ `ledger missing: ${opts.ledger} — run kapture redemption sweep first (Wave 1 day-1) or pass --ledger <path>`,
+ );
+
+ let ledger;
+ try {
+ ledger = readJson(opts.ledger);
+ } catch (e) {
+ die(2, `ledger unreadable: ${e.message}`);
+ }
+
+ const account = pickAccount(ledger, opts.pin);
+ assertNotExtraUsage(account, opts.config);
+ assertBudgetFlagAvailable();
+
+ const budget = effectiveBudget(opts.budget, account.remaining_usd);
+
+ // Acquire lock BEFORE any keychain mutation.
+ const lockFd = acquireLock(opts.lock);
+
+ // Swap keychain.
+ let previousToken = null;
+ try {
+ previousToken = swapToEmail(account.email, account.label);
+ } catch (e) {
+ releaseLock(lockFd, opts.lock);
+ die(2, `keychain swap failed: ${e.message}`);
+ }
+
+ // Wire restoration on every exit path BEFORE spawning child.
+ let restored = false;
+ const restoreOnce = () => {
+ if (restored) return;
+ restored = true;
+ try {
+ if (previousToken) restoreToken(previousToken);
+ } catch (e) {
+ process.stderr.write(`[claude-p-as] warning: failed to restore previous keychain: ${e.message}\n`);
+ }
+ releaseLock(lockFd, opts.lock);
+ };
+ process.on('exit', restoreOnce);
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {
+ process.on(sig, () => {
+ restoreOnce();
+ const n = constants.signals[sig];
+ process.exit(n == null ? 130 : 128 + n);
+ });
+ }
+
+ // Build claude args. Strip user-supplied --max-budget-usd if present, then prefix our floor.
+ const userArgs = [];
+ for (let i = 0; i < opts.rest.length; i++) {
+ const a = opts.rest[i];
+ if (a.startsWith('--max-budget-usd=')) {
+ continue;
+ }
+ if (a === '--max-budget-usd' && opts.rest[i + 1] != null) {
+ i++; // skip the value too
+ continue;
+ }
+ userArgs.push(a);
+ }
+ const finalArgs = ['-p', '--max-budget-usd', String(budget), ...userArgs];
+
+ // Spawn claude. Stream output through; collect for cost parsing.
+ const stdoutChunks = [];
+ const stderrChunks = [];
+ const child = spawn('claude', finalArgs, { stdio: ['inherit', 'pipe', 'pipe'] });
+ child.stdout.on('data', (b) => {
+ stdoutChunks.push(b);
+ process.stdout.write(b);
+ });
+ child.stderr.on('data', (b) => {
+ stderrChunks.push(b);
+ process.stderr.write(b);
+ });
+
+ const exitCode = await new Promise((resolve) => {
+ child.on('close', (code, signal) => {
+ if (signal) {
+ const n = constants.signals[signal];
+ resolve(n == null ? 128 : 128 + n);
+ } else {
+ resolve(code ?? 1);
+ }
+ });
+ child.on('error', (e) => {
+ process.stderr.write(`[claude-p-as] spawn failed: ${e.message}\n`);
+ resolve(127);
+ });
+ });
+
+ // Best-effort cost parse + ledger decrement.
+ const out = Buffer.concat(stdoutChunks).toString('utf8');
+ const err = Buffer.concat(stderrChunks).toString('utf8');
+ let cost = parseUsageCost(out, err);
+ if (cost == null) {
+ cost = 0.01; // conservative floor when parse fails — avoids zero-decrement drift
+ process.stderr.write('[claude-p-as] warning: usage cost not parsed from output; decrementing $0.01 floor\n');
+ }
+ decrementLedger(opts.ledger, account.email, cost);
+
+ restoreOnce();
+ process.exit(exitCode);
+}
+
+// Pure-import guard so tests can require helpers without triggering CLI.
+const invokedAsCli = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
+if (invokedAsCli) {
+ main(process.argv.slice(2)).catch((e) => {
+ process.stderr.write(`[claude-p-as] fatal: ${e.stack || e.message}\n`);
+ process.exit(1);
+ });
+}
+
+export { parseArgs, pickAccount, assertNotExtraUsage, effectiveBudget, parseUsageCost, decrementLedger };
diff --git a/claude-ops/scripts/account-rotation/keychain-swap.mjs b/claude-ops/scripts/account-rotation/keychain-swap.mjs
new file mode 100644
index 00000000..2732461b
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/keychain-swap.mjs
@@ -0,0 +1,100 @@
+/**
+ * keychain-swap.mjs — minimal account-keychain swap helpers for claude-p-as.
+ *
+ * Reuses the same `security` CLI approach as rotate.mjs but is self-contained
+ * so importing it has no side effects (rotate.mjs has top-level CLI execution).
+ *
+ * Exports:
+ * - readCurrentToken() → raw JSON string of active Claude credentials
+ * - writeCurrentToken(json) → overwrite active Claude credentials
+ * - readStoredToken(email) → per-account vault token (or null)
+ * - swapToEmail(email) → save current to previous, install email's token,
+ * return previous token JSON for restoration
+ * - restoreToken(prevJson) → write previous token back as active
+ */
+
+import { execFileSync, spawnSync } from 'child_process';
+
+const KEYCHAIN_SERVICE = 'Claude Code-credentials';
+const KEYCHAIN_ACCOUNT =
+ process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';
+const TOKEN_PREFIX = 'Claude-Rotation';
+
+function accountKey(email, label) {
+ return label ? `${email}|${label}` : email;
+}
+
+function tokenService(email, label) {
+ return `${TOKEN_PREFIX}-${accountKey(email, label)}`;
+}
+
+function readSecurityEntry(svc, acct = KEYCHAIN_ACCOUNT) {
+ const result = spawnSync('security', ['find-generic-password', '-s', svc, '-a', acct, '-g'], {
+ timeout: 5000,
+ encoding: 'utf8',
+ });
+ const out = (result.stdout || '') + (result.stderr || '');
+ const m = out.match(/^password: "?(.*?)"?$/m);
+ if (!m) return null;
+ return m[1].replace(/\\"/g, '"');
+}
+
+function writeSecurityEntry(json, svc, acct = KEYCHAIN_ACCOUNT) {
+ try {
+ execFileSync('security', ['delete-generic-password', '-s', svc, '-a', acct], { stdio: 'ignore' });
+ } catch {
+ /* not present, ignore */
+ }
+ execFileSync('security', ['add-generic-password', '-s', svc, '-a', acct, '-w', json], { timeout: 5000 });
+}
+
+export function readCurrentToken() {
+ const json = readSecurityEntry(KEYCHAIN_SERVICE);
+ if (!json) throw new Error(`No active Claude keychain entry (${KEYCHAIN_SERVICE})`);
+ return json;
+}
+
+export function writeCurrentToken(json) {
+ writeSecurityEntry(json, KEYCHAIN_SERVICE);
+}
+
+export function readStoredToken(email, label) {
+ return readSecurityEntry(tokenService(email, label));
+}
+
+/**
+ * Swap the active keychain to the given email's stored token.
+ * Returns the previous (now-replaced) token JSON so the caller can restore it.
+ * Throws if the target email has no stored token or it's malformed.
+ */
+export function swapToEmail(email, label) {
+ const target = readStoredToken(email, label);
+ if (!target) throw new Error(`No stored token for ${accountKey(email, label)} — run rotate.mjs --setup first`);
+ // Validate target token is well-formed before clobbering current
+ try {
+ const parsed = JSON.parse(target);
+ if (!parsed.claudeAiOauth) throw new Error('missing claudeAiOauth');
+ } catch (e) {
+ throw new Error(`Target token for ${email} is malformed: ${e.message}`);
+ }
+ const previous = readCurrentToken();
+ // Preserve any current mcpOAuth (Figma, Shake, etc.) across the swap.
+ try {
+ const cur = JSON.parse(previous);
+ const tgt = JSON.parse(target);
+ if (cur.mcpOAuth && Object.keys(cur.mcpOAuth).length > 0) {
+ tgt.mcpOAuth = { ...tgt.mcpOAuth, ...cur.mcpOAuth };
+ writeCurrentToken(JSON.stringify(tgt));
+ return previous;
+ }
+ } catch {
+ /* fallthrough to plain swap */
+ }
+ writeCurrentToken(target);
+ return previous;
+}
+
+export function restoreToken(prevJson) {
+ if (!prevJson) return;
+ writeCurrentToken(prevJson);
+}