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
fix(account-rotation): detect + refresh daemon-hosted bg sessions after rotation (#557)
Aurora Capital53da803c2414
diff --git a/claude-ops/scripts/account-rotation/account-leases.mjs b/claude-ops/scripts/account-rotation/account-leases.mjsnew file mode 100644index 00000000..37b1d0a5--- /dev/null+++ b/claude-ops/scripts/account-rotation/account-leases.mjs@@ -0,0 +1,184 @@+// ── Cross-machine account LEASES ─────────────────────────────────────────────+//+// Owner 2026-06-06 (supersedes the static machine-pool split): BOTH machines (the+// Mac and the EC2 box) 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-<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 the AWS account. 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';++// No default bucket in the public repo — set CLAUDE_LEASE_BUCKET to your+// private S3 bucket. Empty → every lease op fails open (single-machine mode).+const LEASE_BUCKET = process.env.CLAUDE_LEASE_BUCKET || '';+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();+ if (!LEASE_BUCKET) return leases; // unconfigured → single-machine mode+ 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 = () => {}) {+ if (!LEASE_BUCKET) return; // unconfigured → single-machine mode+ 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-respawn.mjs b/claude-ops/scripts/account-rotation/bg-respawn.mjsnew file mode 100644index 00000000..38bff490--- /dev/null+++ b/claude-ops/scripts/account-rotation/bg-respawn.mjs@@ -0,0 +1,189 @@+// ── Background-session respawn after rotation ────────────────────────────────+// Daemon-hosted `claude --bg` sessions have no TTY, so the /login-injection+// path in rotate.mjs can never reach them. They also never register in the+// statusline pidfile (`/tmp/claude-pids-<email>`), so the SIGHUP hot-swap+// misses them too. Net effect (observed 2026-06-11): after a rotation the bg+// fleet keeps running on the outgoing account's token until it expires+// (~1-2h), then wedges on 401s until a human runs /login.+//+// The supported refresh path for bg sessions is `claude respawn <id>` — the+// supervisor re-execs the session (transcript preserved, session resumes) and+// the fresh process reads the post-rotation keychain.+//+// Policy:+// idle / waiting → respawn immediately (nothing in flight, zero disruption)+// busy → defer (marker file); the daemon sweep retries until the+// session goes idle, or force-respawns after+// BUSY_FORCE_AFTER_MS (better to lose one tool call than+// wedge on an expired token for hours)+//+// Used by rotate.mjs (post-rotation) and daemon.mjs (periodic deferred sweep).++import { readFileSync, readdirSync, writeFileSync, unlinkSync, statSync, existsSync } from 'fs';+import { execFileSync, execSync } from 'child_process';+import { join } from 'path';+import { homedir } from 'os';++const SESSIONS_DIR = join(homedir(), '.claude', 'sessions');+const RESPAWNED_MARKER = (id) => `/tmp/claude-rotation-respawned-${id}`;+const DEFERRED_MARKER = (id) => `/tmp/claude-respawn-deferred-${id}`;+const RESPAWN_THROTTLE_MS = 10 * 60_000; // never respawn the same session twice in 10 min+const BUSY_FORCE_AFTER_MS = 90 * 60_000; // busy this long after rotation → respawn anyway++let _claudeBin = null;+function claudeBin() {+ if (_claudeBin) return _claudeBin;+ const candidates = [+ process.env.CLAUDE_BIN,+ join(homedir(), '.local', 'bin', 'claude'),+ '/usr/local/bin/claude',+ ].filter(Boolean);+ for (const c of candidates) {+ if (existsSync(c)) {+ _claudeBin = c;+ return c;+ }+ }+ try {+ const w = execSync('which claude', { timeout: 3000 }).toString().trim();+ if (w) {+ _claudeBin = w;+ return w;+ }+ } catch {}+ _claudeBin = 'claude'; // last resort: rely on PATH+ return _claudeBin;+}++function pidAlive(pid) {+ if (!pid || pid <= 0) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++function markerFresh(path, maxAgeMs) {+ try {+ return Date.now() - statSync(path).mtimeMs < maxAgeMs;+ } catch {+ return false;+ }+}++/** Enumerate live daemon-hosted bg sessions from ~/.claude/sessions/*.json. */+export function listLiveBgSessions() {+ const out = [];+ let files = [];+ try {+ files = readdirSync(SESSIONS_DIR).filter((f) => f.endsWith('.json'));+ } catch {+ return out;+ }+ for (const f of files) {+ try {+ const s = JSON.parse(readFileSync(join(SESSIONS_DIR, f), 'utf8'));+ if (s.kind !== 'bg') continue;+ const pid = Number(s.pid) || 0;+ if (!pidAlive(pid)) continue;+ if (pid === process.pid || pid === process.ppid) continue; // never respawn ourselves+ const id = s.id || f.replace(/\.json$/, '');+ out.push({ id, pid, status: s.status || 'unknown' });+ } catch {}+ }+ return out;+}++function doRespawn(session, log) {+ try {+ execFileSync(claudeBin(), ['respawn', String(session.id)], { timeout: 30_000, stdio: 'pipe' });+ try {+ writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()));+ } catch {}+ try {+ unlinkSync(DEFERRED_MARKER(session.id));+ } catch {}+ log(`[bg-respawn] respawned bg session ${session.id} (pid ${session.pid}, was ${session.status})`);+ return true;+ } catch (e) {+ log(`[bg-respawn] respawn ${session.id} failed: ${e.message?.slice(0, 80)}`);+ return false;+ }+}++/**+ * Post-rotation pass: respawn idle/waiting bg sessions so they pick up the+ * new keychain token; defer busy ones to the daemon sweep.+ */+export function respawnBgSessions(log = () => {}) {+ const sessions = listLiveBgSessions();+ if (sessions.length === 0) {+ log('[bg-respawn] no live bg sessions to refresh');+ return { respawned: 0, deferred: 0 };+ }+ let respawned = 0;+ let deferred = 0;+ for (const s of sessions) {+ if (markerFresh(RESPAWNED_MARKER(s.id), RESPAWN_THROTTLE_MS)) {+ log(`[bg-respawn] ${s.id} respawned <10min ago — skipping`);+ continue;+ }+ if (s.status === 'busy') {+ try {+ if (!existsSync(DEFERRED_MARKER(s.id))) writeFileSync(DEFERRED_MARKER(s.id), String(Date.now()));+ } catch {}+ deferred++;+ log(`[bg-respawn] ${s.id} busy — deferred (daemon sweep will retry, force after 90min)`);+ continue;+ }+ if (doRespawn(s, log)) respawned++;+ }+ return { respawned, deferred };+}++/**+ * Daemon sweep: retry deferred (busy-at-rotation-time) sessions. Respawns when+ * the session goes idle/waiting, force-respawns if it stayed busy past+ * BUSY_FORCE_AFTER_MS, and clears markers for sessions that exited.+ */+export function sweepDeferredRespawns(log = () => {}) {+ let markers = [];+ try {+ markers = readdirSync('/tmp').filter((f) => f.startsWith('claude-respawn-deferred-'));+ } catch {+ return 0;+ }+ if (markers.length === 0) return 0;+ const live = new Map(listLiveBgSessions().map((s) => [String(s.id), s]));+ let handled = 0;+ for (const m of markers) {+ const id = m.replace('claude-respawn-deferred-', '');+ const markerPath = `/tmp/${m}`;+ const s = live.get(id);+ if (!s) {+ // session exited or state file gone — nothing to refresh+ try {+ unlinkSync(markerPath);+ } catch {}+ continue;+ }+ const deferredAgo = (() => {+ try {+ return Date.now() - statSync(markerPath).mtimeMs;+ } catch {+ return 0;+ }+ })();+ if (s.status !== 'busy' || deferredAgo > BUSY_FORCE_AFTER_MS) {+ if (s.status === 'busy') {+ log(+ `[bg-respawn] ${id} still busy after ${Math.round(deferredAgo / 60000)}min — force-respawning before token expiry`,+ );+ }+ if (doRespawn(s, log)) handled++;+ }+ }+ return handled;+}diff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjsindex 2a5da563..5d7ea6a9 100644--- a/claude-ops/scripts/account-rotation/daemon.mjs+++ b/claude-ops/scripts/account-rotation/daemon.mjs@@ -39,6 +39,7 @@ import { fileURLToPath } from 'url';import { execSync, execFileSync, spawn, spawnSync } from 'child_process';import { tmpdir } from 'os';import { applyAccountLeases, writeLease } from './account-leases.mjs';+import { sweepDeferredRespawns } from './bg-respawn.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = join(__dirname, 'config.json');@@ -1408,6 +1409,7 @@ async function mainLoop() {let lastRefreshCheck = 0; // dynamic refresh checklet lastDriftCheck = 0; // cheap vault-based drift detectionlet lastFullProbe = 0; // periodic fleet-wide live-util snapshot refresh+ let lastRespawnSweep = 0; // deferred bg-session respawn retry (busy at rotation time)const FULL_PROBE_INTERVAL = 5 * 60_000;const bedrockRecCtx = {lastCheck: 0,@@ -1448,6 +1450,19 @@ async function mainLoop() {// its own token and the live no longer matches any vault.// Self-heals when state.json disagrees with the actual active account// (crashed rotation, manual /login, leftover lock).+ // Deferred bg-session respawn sweep (every 2 min): sessions that were+ // busy at rotation time get respawned once they go idle, or force-+ // respawned after 90 min so they never wedge on an expired token.+ if (Date.now() - lastRespawnSweep > 120_000) {+ lastRespawnSweep = Date.now();+ try {+ const handled = sweepDeferredRespawns((m) => log(m));+ if (handled > 0) log(`[bg-respawn] sweep refreshed ${handled} deferred bg session(s)`);+ } catch (e) {+ log(`[bg-respawn] sweep error: ${e.message?.substring(0, 80)}`);+ }+ }+if (Date.now() - lastDriftCheck > 120_000) {lastDriftCheck = Date.now();const stateLastRotation2 = state.lastRotation ? new Date(state.lastRotation).getTime() : 0;diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex 65e9b579..306a6945 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -48,6 +48,7 @@ import { createHmac } from 'node:crypto';import { askAIBrain, executeAIAction, AI_BRAIN_MAX_DECISIONS, scrapeBillingState } from './ai-brain.mjs';import { destinationUtilHardBlock } from './rotation-policy.mjs';import { applyAccountLeases, writeLease } from './account-leases.mjs';+import { respawnBgSessions } from './bg-respawn.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = join(__dirname, 'config.json');@@ -3320,11 +3321,31 @@ function findClaudeSessions() {// `grep -` (empty pattern) at the end of the pipeline caused the whole// execSync to throw "Command failed" on every call.// ps -eo pid,args works identically on macOS (BSD) and Linux (GNU).- const psOut = execSync(`ps -eo pid,args | grep -E '[c]laude.*--dangerously-skip-permissions' | grep -v 'grep'`, {+ //+ // Match ANY claude CLI process, not just `--dangerously-skip-permissions`+ // ones — plain interactive sessions, `claude --resume`, and headless+ // `claude -p` runs all hold tokens that go stale after rotation (observed+ // 2026-06-11: live agent sessions were invisible to this enum and wedged+ // on the expired outgoing token). The first ps token must BE the claude+ // binary — matching `claude` anywhere in args would false-positive on+ // `tail -f .../claude/...log`, `node .../account-rotation/daemon.mjs`, etc.+ // Utility invocations (daemon supervisor, respawn/attach/logs/agents, mcp)+ // are excluded here; daemon-hosted bg sessions are refreshed separately+ // via respawnBgSessions() (they have no TTY to inject /login into).+ const psRaw = execSync(`ps -eo pid,args | grep -E '[c]laude' | grep -v 'grep'`, {timeout: 5000,}).toString().trim();+ const CLAUDE_CMD_RE = /^(?:\S*\/)?claude(?:\s|$)/;+ const UTILITY_SUBCMD_RE = /^(?:\S*\/)?claude\s+(?:daemon|respawn|attach|logs|agents|mcp|doctor|update|config)\b/;+ const psOut = psRaw+ .split('\n')+ .filter((line) => {+ const args = line.trim().replace(/^\d+\s+/, '');+ return CLAUDE_CMD_RE.test(args) && !UTILITY_SUBCMD_RE.test(args);+ })+ .join('\n');if (!psOut) return sessions;// Build pid→tty map from tmux (best-effort; tty used only for tmux pane lookup)@@ -3447,6 +3468,7 @@ function detectTerminalForPid(pid) {async function refreshRunningSession(rotatedAccount = null, noBrowser = false) {const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const sessions = findClaudeSessions();if (sessions.length === 0) {@@ -4007,6 +4029,18 @@ async function rotate(targetEmail, opts = {}) {}}+ // Daemon-hosted `claude --bg` sessions have no TTY for /login injection and+ // don't register in the pidfile SIGHUP path — respawn after every successful+ // rotation (including daemon --no-browser without --session).+ if (ok && !dryRun) {+ try {+ const { respawned, deferred } = respawnBgSessions(log);+ if (respawned || deferred) log(`[bg-respawn] fleet: ${respawned} respawned, ${deferred} deferred (busy)`);+ } catch (e) {+ log(`[bg-respawn] pass skipped: ${e.message?.slice(0, 80)}`);+ }+ }+if (opts.session) {if (dryRun) {log('[DRY-RUN] Would restart running Claude sessions with --continue and send resume prompt');