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.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
salvage(account-rotation): preserve cross-machine lease + bg-spawn + policy modules
auroracapital4db9a785f6f8
diff --git a/claude-ops/scripts/account-rotation/account-leases.mjs b/claude-ops/scripts/account-rotation/account-leases.mjsnew file mode 100644index 00000000..5637a88b--- /dev/null+++ b/claude-ops/scripts/account-rotation/account-leases.mjs@@ -0,0 +1,175 @@+// ── Cross-machine account LEASES ─────────────────────────────────────────────+//+// Sam 2026-06-06 (supersedes the static machine-pool split): BOTH machines (the+// Mac and this EC2 box, dev-sandbox-fra) keep their OWN rotation logic/daemon and+// may use ALL accounts. The ONLY cross-machine constraint is: the same account+// must NEVER be ACTIVE on both machines concurrently.+//+// Coordination store: a small private S3 object per account.+// bucket: claude-account-leases-<AWS_ACCOUNT_ID> (us-east-1, all public access+// blocked, SSE-AES256). Override via CLAUDE_LEASE_BUCKET.+// key: leases/<accountKey>.json (one object per account → no+// read-modify-write races between machines)+// body: { "host": "<os.hostname()>", "account": "<key>", "ts": <epoch_ms> }+//+// A machine writes (PUT) its own lease when it ACTIVATES an account, and the+// daemon REFRESHES (heartbeats) the active account's lease every loop tick.+// Candidate selection EXCLUDES any account whose lease belongs to ANOTHER host+// and is still fresh (ts within LEASE_TTL_MS). A lease older than the TTL is+// stale and ignored (the other machine stopped heartbeating / is asleep).+//+// FAIL OPEN: every S3 call is best-effort with a short timeout. If the store is+// unreachable, missing, or errors, we log and proceed WITHOUT exclusion —+// rotation must never hard-fail because S3 is down. Worst case under an outage+// is the old behavior (possible double-active), which is exactly today's status+// quo, so failing open is strictly safe.+//+// PLATFORM-NEUTRAL: host identity is os.hostname(); all S3 access is via the+// `aws` CLI default credential chain (we delete AWS_PROFILE from the child env+// so a stale/broken AWS_PROFILE in the parent shell can't break it — both the+// EC2 IAM user and the Mac's default creds resolve correctly). For coordination+// to be MUTUAL, the Mac needs (a) this same rotate.mjs/daemon.mjs version and+// (b) working AWS creds for account <AWS_ACCOUNT_ID>. Until the Mac is updated, EC2+// honoring leases is one-sided but harmless (EC2 yields; Mac is unaware).++import { spawnSync } from 'child_process';+import { hostname } from 'os';++const LEASE_BUCKET = process.env.CLAUDE_LEASE_BUCKET || 'claude-account-leases-<AWS_ACCOUNT_ID>';+const LEASE_PREFIX = 'leases/';+const LEASE_REGION = process.env.CLAUDE_LEASE_REGION || 'us-east-1';+// Daemon heartbeats every loop (seconds–minutes); 2h TTL tolerates pauses,+// GC pauses, and brief outages without falsely freeing a still-active lease.+export const LEASE_TTL_MS = Number(process.env.CLAUDE_LEASE_TTL_MS || 2 * 60 * 60 * 1000);+const AWS_TIMEOUT_MS = 6000;++export function selfHost() {+ return (process.env.CLAUDE_LEASE_HOST || hostname() || 'unknown').trim();+}++function keyFor(accountKey) {+ // accountKey is an email or label; both are S3-key-safe but normalize spaces.+ return `${LEASE_PREFIX}${String(accountKey).replace(/\s+/g, '_')}.json`;+}++// Run `aws` with a clean credential env (drop a broken/parent AWS_PROFILE).+function runAws(args, { input } = {}) {+ const env = { ...process.env };+ delete env.AWS_PROFILE;+ delete env.AWS_DEFAULT_PROFILE;+ return spawnSync('aws', args, {+ env,+ input,+ timeout: AWS_TIMEOUT_MS,+ encoding: 'utf8',+ });+}++// Read ALL leases in one S3 list+get pass. Returns a Map<accountKey,{host,ts}>.+// Fails open: any error → empty map (no exclusions).+export function readAllLeases(log = () => {}) {+ const leases = new Map();+ try {+ const ls = runAws([+ 's3api', 'list-objects-v2',+ '--bucket', LEASE_BUCKET,+ '--prefix', LEASE_PREFIX,+ '--region', LEASE_REGION,+ '--output', 'json',+ ]);+ if (ls.status !== 0) {+ if (ls.stderr) log(`[lease] list failed (fail-open): ${ls.stderr.trim().split('\n')[0]}`);+ return leases;+ }+ const parsed = JSON.parse(ls.stdout || '{}');+ for (const obj of parsed.Contents || []) {+ const k = obj.Key;+ if (!k || !k.endsWith('.json')) continue;+ const got = runAws([+ 's3', 'cp', `s3://${LEASE_BUCKET}/${k}`, '-',+ '--region', LEASE_REGION,+ ]);+ if (got.status !== 0) continue;+ try {+ const body = JSON.parse(got.stdout);+ if (body && body.account && body.host && body.ts) {+ leases.set(body.account, { host: body.host, ts: Number(body.ts) });+ }+ } catch {}+ }+ } catch (e) {+ log(`[lease] readAll error (fail-open): ${e.message}`);+ }+ return leases;+}++// Accounts (by key) currently leased by ANOTHER host with a FRESH lease.+// Per host, only the NEWEST fresh lease is considered active — older leases+// from the same host are stale rotations that were never cleaned up.+export function foreignActiveKeys(log = () => {}) {+ const me = selfHost();+ const now = Date.now();+ // group all fresh foreign leases by host, then keep only the newest per host+ const byHost = new Map(); // host → { acct, ts }+ for (const [acct, { host, ts }] of readAllLeases(log)) {+ if (host === me || now - ts >= LEASE_TTL_MS) continue;+ const existing = byHost.get(host);+ if (!existing || ts > existing.ts) byHost.set(host, { acct, ts });+ }+ const blocked = new Set();+ for (const { acct } of byHost.values()) blocked.add(acct);+ return blocked;+}++// Write/refresh THIS machine's lease for accountKey. Best-effort; logs on fail.+// Deletes stale leases from this host for other accounts so the other machine+// doesn't exclude accounts we're no longer using.+export function writeLease(accountKey, log = () => {}) {+ try {+ const me = selfHost();+ const body = JSON.stringify({ host: me, account: accountKey, ts: Date.now() });+ const put = runAws([+ 's3', 'cp', '-', `s3://${LEASE_BUCKET}/${keyFor(accountKey)}`,+ '--region', LEASE_REGION,+ '--content-type', 'application/json',+ ], { input: body });+ if (put.status !== 0) {+ if (put.stderr) log(`[lease] write ${accountKey} failed (non-fatal): ${put.stderr.trim().split('\n')[0]}`);+ return false;+ }+ // Clean up this host's stale leases for other accounts (best-effort).+ try {+ const all = readAllLeases(log);+ for (const [acct, { host }] of all) {+ if (host === me && acct !== accountKey) {+ const del = runAws([+ 's3', 'rm', `s3://${LEASE_BUCKET}/${keyFor(acct)}`,+ '--region', LEASE_REGION,+ ]);+ if (del.status === 0) log(`[lease] cleared stale own-lease for ${acct}`);+ }+ }+ } catch {}+ return true;+ } catch (e) {+ log(`[lease] write ${accountKey} error (non-fatal): ${e.message}`);+ return false;+ }+}++// Filter a config.accounts list, dropping accounts foreign-leased & fresh.+// Never drops `keepKey` (the account we're staying on / activating).+export function applyAccountLeases(config, { keepKey = null, log = () => {} } = {}) {+ try {+ const blocked = foreignActiveKeys(log);+ if (!blocked.size) return config;+ const keyOf = (a) => a.label || a.email;+ config.accounts = config.accounts.filter(+ (a) => keyOf(a) === keepKey || !blocked.has(keyOf(a)),+ );+ log(`[lease] excluding foreign-active accounts: ${[...blocked].join(', ')}`);+ } catch (e) {+ log(`[lease] applyAccountLeases error (fail-open): ${e.message}`);+ }+ return config;+}diff --git a/claude-ops/scripts/account-rotation/bg-spawn.mjs b/claude-ops/scripts/account-rotation/bg-spawn.mjsnew file mode 100644index 00000000..0ea47514--- /dev/null+++ b/claude-ops/scripts/account-rotation/bg-spawn.mjs@@ -0,0 +1,188 @@+#!/usr/bin/env node+/**+ * bg-spawn.mjs — Per-session account router for `claude --bg` dispatches.+ *+ * Called by `ops-bg dispatch` when CLAUDE_SESSION_ROUTING=1.+ * Picks the least-utilized unleased account, injects CLAUDE_CODE_OAUTH_TOKEN+ * into the child environment, and execs `claude` with the supplied args.+ *+ * Falls back to plain `claude` spawn (global keychain) when:+ * - No healthy unleased account is available (all exhausted / rate-limited)+ * - Config or state cannot be read+ * - Any error occurs during routing+ *+ * NEVER modifies the global keychain entry. NEVER touches vault tokens except+ * to read the access token for the assigned account.+ *+ * Usage (called by ops-bg — do not invoke directly):+ * node bg-spawn.mjs [claude args...]+ *+ * Required env:+ * CLAUDE_BIN — path to the claude binary (set by ops-bg)+ * CLAUDE_SESSION_ROUTING — must equal "1" (ops-bg checks this before calling)+ *+ * Optional env:+ * CLAUDE_ROTATION_DIR — directory containing config.json + state.json+ * (defaults to same directory as this script)+ */++import { readFileSync, existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { spawnSync } from 'child_process';++const __dirname = dirname(fileURLToPath(import.meta.url));++// ── Config paths ───────────────────────────────────────────────────────────────++const ROTATION_DIR = process.env.CLAUDE_ROTATION_DIR || __dirname;+const CONFIG_PATH = join(ROTATION_DIR, 'config.json');+const STATE_PATH = join(ROTATION_DIR, 'state.json');+const ROUTER_PATH = join(__dirname, 'session-router.mjs');++// ── Logging (to stderr so ops-bg output is unaffected) ────────────────────────++function log(msg) {+ const ts = new Date().toISOString();+ process.stderr.write(`[bg-spawn ${ts}] ${msg}\n`);+}++// ── Main ───────────────────────────────────────────────────────────────────────++const claudeBin = process.env.CLAUDE_BIN;+if (!claudeBin) {+ log('CLAUDE_BIN not set — falling back to global keychain');+ fallback();+}++const claudeArgs = process.argv.slice(2);++// Validate CLAUDE_SESSION_ROUTING is actually set (ops-bg should have checked)+if (process.env.CLAUDE_SESSION_ROUTING !== '1') {+ log('CLAUDE_SESSION_ROUTING != 1 — falling back to global keychain');+ fallback();+}++// Read config + state — fall back on any parse error+let config, state;+try {+ config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));+ state = JSON.parse(readFileSync(STATE_PATH, 'utf8'));+} catch (e) {+ log(`Failed to read config/state (${e.message}) — falling back to global keychain`);+ fallback();+}++// Import router dynamically (same dir as this shim in repo; ROTATION_DIR in production)+let pickAccountForSession, recordSessionLease, releaseSessionLease;+try {+ const routerPath = existsSync(join(ROTATION_DIR, 'session-router.mjs'))+ ? join(ROTATION_DIR, 'session-router.mjs')+ : ROUTER_PATH;+ ({ pickAccountForSession, recordSessionLease, releaseSessionLease } = await import(routerPath));+} catch (e) {+ log(`Failed to import session-router (${e.message}) — falling back to global keychain`);+ fallback();+}++// accountKey helper (mirrors session-router.mjs)+const accountKey = (a) => a.label || a.email;++// Generate a stable session ID for this dispatch+const sessionId = `bg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;++// Pick account+const key = pickAccountForSession(sessionId, config, state);++if (!key) {+ log('No healthy unleased account available — falling back to global keychain');+ fallback();+}++// Find the account and read its vault token+const account = config.accounts.find((a) => accountKey(a) === key);+if (!account) {+ log(`Account ${key} not found in config — falling back to global keychain`);+ fallback();+}++const tokenJson = readVaultToken(account);+if (!tokenJson) {+ log(`No vault token for ${key} — falling back to global keychain`);+ fallback();+}++const accessToken = extractAccessToken(tokenJson);+if (!accessToken) {+ log(`Could not extract access token for ${key} — falling back to global keychain`);+ fallback();+}++// Route is confirmed — record the lease and spawn with injected token+log(`Routing bg session ${sessionId} → ${key}`);+recordSessionLease(sessionId, key, null /* pid unknown until spawn */);++const childEnv = { ...process.env, CLAUDE_CODE_OAUTH_TOKEN: accessToken };+// Ensure the child does NOT inherit our sentinel (avoid nested routing)+delete childEnv.CLAUDE_SESSION_ROUTING;++const result = spawnSync(claudeBin, claudeArgs, {+ env: childEnv,+ stdio: 'inherit',+});++// Release lease on exit (best-effort)+try {+ releaseSessionLease(sessionId);+} catch {}++process.exit(result.status ?? 1);++// ── Helpers ────────────────────────────────────────────────────────────────────++function fallback() {+ // Plain exec — global keychain, existing behavior+ const result = spawnSync(claudeBin || 'claude', claudeArgs, {+ env: process.env,+ stdio: 'inherit',+ });+ process.exit(result.status ?? 1);+}++const IS_LINUX = process.platform === 'linux';+const KEYCHAIN_ACCOUNT =+ process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';+const LINUX_CRED_PATH = join(process.env.HOME || '', '.claude', '.credentials.json');++function readVaultToken(account) {+ const svc = `Claude-Rotation-${accountKey(account)}`;+ if (IS_LINUX) {+ try {+ const store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));+ const val = store[svc];+ if (!val) return null;+ return typeof val === 'string' ? val : JSON.stringify(val);+ } catch {+ return null;+ }+ }+ try {+ const r = spawnSync('security', ['find-generic-password', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-g'], {+ timeout: 5000,+ encoding: 'utf8',+ });+ const out = (r.stdout || '') + (r.stderr || '');+ const m = out.match(/^password: "?(.*?)"?$/m);+ return m ? m[1].replace(/\\"/g, '"') : null;+ } catch {+ return null;+ }+}++function extractAccessToken(tokenJson) {+ try {+ return JSON.parse(tokenJson)?.claudeAiOauth?.accessToken || null;+ } catch {+ return null;+ }+}diff --git a/claude-ops/scripts/account-rotation/claude-settings-mode.mjs b/claude-ops/scripts/account-rotation/claude-settings-mode.mjsindex 754ae502..e8f3c39b 100644--- a/claude-ops/scripts/account-rotation/claude-settings-mode.mjs+++ b/claude-ops/scripts/account-rotation/claude-settings-mode.mjs@@ -107,7 +107,11 @@ function sonnetRank(inferenceProfileId) {function haikuRank(inferenceProfileId) {let m = inferenceProfileId.match(/\.anthropic\.claude-haiku-(\d+)-(\d+)-(\d{8})/);if (m) {- return [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];+ return [+ parseInt(m[1], 10),+ parseInt(m[2], 10),+ parseInt(m[3], 10),+ ];}m = inferenceProfileId.match(/\.anthropic\.claude-3-5-haiku-(\d{8})/);if (m) return [3, 5, parseInt(m[1], 10)];@@ -130,9 +134,18 @@ function candidatesWithPrefix(profiles, prefix, predicate) {}function pickLatestSonnet(profiles, prefix) {- const c = candidatesWithPrefix(profiles, prefix, (id) => id.includes('.anthropic.claude-sonnet-'));+ const c = candidatesWithPrefix(+ profiles,+ prefix,+ (id) => id.includes('.anthropic.claude-sonnet-'),+ );if (!c.length) return null;- c.sort((x, y) => rankCompareDesc(sonnetRank(x.inferenceProfileId), sonnetRank(y.inferenceProfileId)));+ c.sort((x, y) =>+ rankCompareDesc(+ sonnetRank(x.inferenceProfileId),+ sonnetRank(y.inferenceProfileId),+ ),+ );return c[0].inferenceProfileId;}@@ -143,7 +156,9 @@ function pickLatestHaiku(profiles, prefix) {return false;});if (!c.length) return null;- c.sort((x, y) => rankCompareDesc(haikuRank(x.inferenceProfileId), haikuRank(y.inferenceProfileId)));+ c.sort((x, y) =>+ rankCompareDesc(haikuRank(x.inferenceProfileId), haikuRank(y.inferenceProfileId)),+ );return c[0].inferenceProfileId;}@@ -211,7 +226,6 @@ export function clearHardcodedModelsForOAuthClaudeSettings() {for (const k of ['CLAUDE_CODE_USE_BEDROCK','AWS_BEDROCK_REGION',- 'AWS_REGION','ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','ANTHROPIC_BASE_URL',diff --git a/claude-ops/scripts/account-rotation/rotation-policy.mjs b/claude-ops/scripts/account-rotation/rotation-policy.mjsnew file mode 100644index 00000000..80ffbef0--- /dev/null+++ b/claude-ops/scripts/account-rotation/rotation-policy.mjs@@ -0,0 +1,32 @@+/**+ * Shared rotation / recovery policy — keep daemon + rotate.mjs aligned.+ */++/** Max(5h,7d) must stay strictly below this to be a pickNextAccount target (rotate.mjs). */+export function destinationUtilHardBlock(config) {+ const v = config.rateLimits?.destinationMaxUtilPercent;+ if (typeof v === 'number' && v > 0 && v <= 100) return v;+ return 95;+}++/** Daemon pre-rotate strict pass — same as findValidRotationTarget first loop. */+export const DAEMON_SAFE_5H_PCT = 95;+export const DAEMON_SAFE_7D_PCT = 95;++/** Daemon pre-rotate relaxed pass. */+export const DAEMON_RELAXED_BAR = 94;++/** True when live usage allows daemon keychain rotation to this account (strict bars). */+export function isDaemonRotationViable(live) {+ if (!live || live.ok !== true) return false;+ return live.pct5h < DAEMON_SAFE_5H_PCT && live.pct7d < DAEMON_SAFE_7D_PCT;+}++export function isLiveUtilOk(u) {+ return u != null && u.ok === true;+}++export function liveUtilMax(u) {+ if (!isLiveUtilOk(u)) return null;+ return Math.max(u.pct5h, u.pct7d);+}