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: resolve rotation daemon park check (Bug A) and logging noise (Bug B) (#563)
Aurora Capital74c5a4e5268f
diff --git a/.metadata_never_index b/.metadata_never_indexnew file mode 100644index 00000000..e69de29bdiff --git a/claude-ops/scripts/account-rotation/bg-respawn.mjs b/claude-ops/scripts/account-rotation/bg-respawn.mjsindex b5de410a..03b74de3 100644--- a/claude-ops/scripts/account-rotation/bg-respawn.mjs+++ b/claude-ops/scripts/account-rotation/bg-respawn.mjs@@ -19,14 +19,43 @@//// Used by rotate.mjs (post-rotation) and daemon.mjs (periodic deferred sweep).-import { readFileSync, readdirSync, writeFileSync, unlinkSync, statSync, existsSync } from 'fs';+import { readFileSync, readdirSync, writeFileSync, unlinkSync, statSync, existsSync, mkdirSync, renameSync } 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}`;+// Markers live in a user-private dir (0700), not the world-writable OS temp dir,+// to avoid symlink/predictable-name attacks on the shared /tmp.+const MARKER_DIR = join(homedir(), '.claude', 'rotation-markers');+function ensureMarkerDir() {+ try {+ mkdirSync(MARKER_DIR, { recursive: true, mode: 0o700 });+ } catch {}+}+const LEGACY_TMP_DIR = '/tmp';+const DEFERRED_PREFIX = 'claude-respawn-deferred-';+const RESPAWNED_MARKER = (id) => join(MARKER_DIR, `claude-rotation-respawned-${id}`);+const DEFERRED_MARKER = (id) => join(MARKER_DIR, `${DEFERRED_PREFIX}${id}`);++/** Move deferred markers left under /tmp by pre-upgrade daemons into MARKER_DIR. */+function migrateLegacyDeferredMarkers() {+ ensureMarkerDir();+ let legacy = [];+ try {+ legacy = readdirSync(LEGACY_TMP_DIR).filter((f) => f.startsWith(DEFERRED_PREFIX));+ } catch {+ return;+ }+ for (const f of legacy) {+ const from = join(LEGACY_TMP_DIR, f);+ const to = join(MARKER_DIR, f);+ try {+ if (existsSync(to)) unlinkSync(from);+ else renameSync(from, to);+ } catch {}+ }+}const RESPAWN_THROTTLE_MS = 10 * 60_000; // never respawn the same session twice in 10 minconst BUSY_FORCE_AFTER_MS = 90 * 60_000; // busy this long after rotation → respawn anyway@@ -101,10 +130,32 @@ export function listLiveBgSessions() {}function doRespawn(session, log) {+ const stateFile = join(homedir(), '.claude', 'jobs', String(session.id), 'state.json');+ if (!existsSync(stateFile)) {+ log(+ `[bg-respawn] session ${session.id} (pid ${session.pid}) has no saved state (spare) — terminating process to refresh`,+ );+ try {+ process.kill(session.pid, 'SIGTERM');+ try {+ ensureMarkerDir();+ writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()), { mode: 0o600 });+ } catch {}+ try {+ unlinkSync(DEFERRED_MARKER(session.id));+ } catch {}+ return true;+ } catch (e) {+ log(`[bg-respawn] failed to terminate spare session ${session.id} (pid ${session.pid}): ${e.message}`);+ return false;+ }+ }+try {execFileSync(claudeBin(), ['respawn', String(session.id)], { timeout: 30_000, stdio: 'pipe' });try {- writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()));+ ensureMarkerDir();+ writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()), { mode: 0o600 });} catch {}try {unlinkSync(DEFERRED_MARKER(session.id));@@ -136,7 +187,9 @@ export function respawnBgSessions(log = () => {}) {}if (s.status === 'busy') {try {- if (!existsSync(DEFERRED_MARKER(s.id))) writeFileSync(DEFERRED_MARKER(s.id), String(Date.now()));+ ensureMarkerDir();+ if (!existsSync(DEFERRED_MARKER(s.id)))+ writeFileSync(DEFERRED_MARKER(s.id), String(Date.now()), { mode: 0o600 });} catch {}deferred++;log(`[bg-respawn] ${s.id} busy — deferred (daemon sweep will retry, force after 90min)`);@@ -153,9 +206,10 @@ export function respawnBgSessions(log = () => {}) {* BUSY_FORCE_AFTER_MS, and clears markers for sessions that exited.*/export function sweepDeferredRespawns(log = () => {}) {+ migrateLegacyDeferredMarkers();let markers = [];try {- markers = readdirSync('/tmp').filter((f) => f.startsWith('claude-respawn-deferred-'));+ markers = readdirSync(MARKER_DIR).filter((f) => f.startsWith(DEFERRED_PREFIX));} catch {return 0;}@@ -163,8 +217,8 @@ export function sweepDeferredRespawns(log = () => {}) {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 id = m.replace(DEFERRED_PREFIX, '');+ const markerPath = join(MARKER_DIR, m);const s = live.get(id);if (!s) {// session exited or state file gone — nothing to refreshdiff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjsindex 5d7ea6a9..f0552441 100644--- a/claude-ops/scripts/account-rotation/daemon.mjs+++ b/claude-ops/scripts/account-rotation/daemon.mjs@@ -49,8 +49,8 @@ const PID_FILE = join(__dirname, '.daemon.pid');const ROTATE_SCRIPT = join(__dirname, 'rotate.mjs');// Keychain account name — must match rotate.mjs convention.-const KEYCHAIN_ACCOUNT =- process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';+const ACTIVE_KEYCHAIN_ACCOUNT = 'unknown';+const VAULT_KEYCHAIN_ACCOUNT = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';const RECOVERY_STATUS_PATH = join(__dirname, '.bedrock-recovery-status.json');const USAGE_PROBE_CONCURRENCY = 3;@@ -285,9 +285,12 @@ function readStoredToken(account) {}}try {- const out = execSync(`security find-generic-password -s "${svc}" -a "${KEYCHAIN_ACCOUNT}" -g 2>&1`, {+ // spawnSync (no shell) — svc/account can't break out into a shell command.+ // `security -g` prints "password: ..." on stderr, so read both streams.+ const r = spawnSync('security', ['find-generic-password', '-s', svc, '-a', VAULT_KEYCHAIN_ACCOUNT, '-g'], {timeout: 5000,- }).toString();+ });+ const out = `${r.stdout?.toString() || ''}${r.stderr?.toString() || ''}`;const m = out.match(/^password: "?(.*?)"?$/m);return m ? m[1].replace(/\\"/g, '"') : null;} catch {@@ -307,7 +310,7 @@ function readActiveKeychainToken() {}try {const out = execSync(- `security find-generic-password -s "Claude Code-credentials" -a "${KEYCHAIN_ACCOUNT}" -g 2>&1`,+ `security find-generic-password -s "Claude Code-credentials" -a "${ACTIVE_KEYCHAIN_ACCOUNT}" -g 2>&1`,{timeout: 5000,},@@ -512,7 +515,7 @@ async function shouldRotate(config, state) {// Park check: if this account is already known-exhausted and parked until// its reset window, skip the rescue entirely — don't re-probe live API// every 30s just to confirm it's still at 100%.- if (isParked(probeKey)) {+ if (isParked(probeKey) && isMismatched) {const until = _parkedUntil.get(probeKey);const minsLeft = Math.ceil((until - Date.now()) / 60_000);log(`[park] ${probeKey} is parked for ${minsLeft}min more — suppressing rescue trigger`);@@ -649,7 +652,7 @@ async function shouldRotate(config, state) {// macOS: use spawnSync (no shell, no injection) instead of execSync.spawnSync('security',- ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', tokenToWrite],+ ['add-generic-password', '-U', '-s', svc, '-a', ACTIVE_KEYCHAIN_ACCOUNT, '-w', tokenToWrite],{timeout: 5000,},@@ -826,6 +829,14 @@ async function findValidRotationTarget(config, state) {const key = accountKey(account);const tokenJson = readStoredToken(account);if (!tokenJson) continue;++ const expiry = parseTokenExpiry(tokenJson);+ const isExpired = expiry > 0 && now > expiry - 5 * 60_000;+ if (isExpired) {+ const refreshed = await refreshSingleToken(account);+ if (!refreshed) continue;+ }+const live = await queryLiveUtilization(account);if (!isLiveUtilOk(live)) continue;const max = liveUtilMax(live);@@ -891,6 +902,19 @@ async function allCandidatesExhausted(config, state) {return true;}+function stopClaudeDaemon() {+ log('[daemon-stop] Stopping Claude daemon to clear cached environment...');+ try {+ const result = execSync('claude daemon stop --any', {+ encoding: 'utf8',+ env: { ...process.env, PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin' },+ });+ log(`[daemon-stop] Daemon stop success: ${result.trim()}`);+ } catch (err) {+ log(`[daemon-stop] Daemon stop failed: ${err.message}`);+ }+}+// Activate Bedrock fallback from inside daemon. Probes AWS reachability,// writes the sentinel + sends a desktop notification. Returns true on success.function activateBedrockFallbackFromDaemon(reason) {@@ -932,6 +956,11 @@ function activateBedrockFallbackFromDaemon(reason) {} catch (e) {log(`[bedrock-fallback] settings persist failed: ${e.message?.slice(0, 80)}`);}+ try {+ stopClaudeDaemon();+ } catch (e) {+ log(`[bedrock-fallback] stopClaudeDaemon failed: ${e.message}`);+ }log(`[bedrock-fallback] ACTIVATED region=${region} reason=${reason}`);notify('Bedrock Fallback Active',@@ -1030,7 +1059,7 @@ async function doRotation(reason) {// into running sessions — that interrupts active work. Sessions pick up the new// token on next 401 (auto-retry) or when the user voluntarily runs /login.// execFileSync (not execSync) — no shell, no injection risk on targetKey.- const result = execFileSync('node', [ROTATE_SCRIPT, '--no-browser', '--to', targetKey], {+ const result = execFileSync(process.execPath, [ROTATE_SCRIPT, '--no-browser', '--to', targetKey], {cwd: __dirname,timeout: 120_000, // 2min — keychain swap is fast; no per-session injectionenv: { ...process.env, NODE_NO_WARNINGS: '1' },@@ -1146,9 +1175,15 @@ async function refreshSingleToken(account) {}} else {// Use spawnSync (no shell) to avoid injection risk on tokenStr.- spawnSync('security', ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', tokenStr], {- timeout: 5000,- });+ const kcResult = spawnSync(+ 'security',+ ['add-generic-password', '-U', '-s', svc, '-a', VAULT_KEYCHAIN_ACCOUNT, '-w', tokenStr],+ { timeout: 5000 },+ );+ if (kcResult.error || kcResult.status !== 0) {+ const msg = kcResult.error?.message || kcResult.stderr?.toString() || `security exit ${kcResult.status}`;+ throw new Error(`Keychain write failed: ${msg}`);+ }}log(`[refresh] ${key}: refreshed (${((parsed.claudeAiOauth.expiresAt - Date.now()) / 3_600_000).toFixed(1)}h remaining)`,@@ -1269,6 +1304,11 @@ async function maybeRecoverOAuthFromBedrock(config, state, sentinelPath, ctx) {} catch (e) {log(`[bedrock-recovery] settings clear failed: ${e.message?.slice(0, 80)}`);}+ try {+ stopClaudeDaemon();+ } catch (e) {+ log(`[bedrock-recovery] stopClaudeDaemon failed: ${e.message}`);+ }notify('OAuth Restored',`${probeKey} has Max headroom — settings.json OAuth; Bedrock shells: source use-oauth.sh`,diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex f2098863..3c8b2b64 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -61,10 +61,8 @@ const BROWSER_PIN_BACKUP_PATH = join(__dirname, '.browser-pin-backup.json');const CLAUDE_JSON_PATH = join(process.env.HOME || '', '.claude.json');const KEYCHAIN_SERVICE = 'Claude Code-credentials';-// Use the OS username so multiple users on the same Mac don't collide on-// keychain entries. Override with CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT if needed.-const KEYCHAIN_ACCOUNT =- process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';+const ACTIVE_KEYCHAIN_ACCOUNT = 'unknown';+const VAULT_KEYCHAIN_ACCOUNT = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';const sleep = (ms) => new Promise((r) => setTimeout(r, ms));@@ -144,8 +142,20 @@ if (// ── Utilities ────────────────────────────────────────────────────────────────+// Strip anything that looks like an OAuth token / bearer secret before it can+// reach a log sink (console or rotation.log). Operational logs only need the+// account email/label, never the credential material — this scrubs accidental+// leakage of token bytes that flow through error messages or oauthAccount blobs.+function redactSecrets(s) {+ return String(s)+ .replace(/sk-ant-[A-Za-z0-9_-]+/g, 'sk-ant-***')+ .replace(/\bey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+/g, '***jwt***')+ .replace(/"?accessToken"?\s*[:=]\s*"?[A-Za-z0-9._-]{20,}"?/gi, 'accessToken:***')+ .replace(/"?refreshToken"?\s*[:=]\s*"?[A-Za-z0-9._-]{20,}"?/gi, 'refreshToken:***');+}+function log(msg) {- const line = `[${new Date().toISOString()}] ${msg}`;+ const line = `[${new Date().toISOString()}] ${redactSecrets(msg)}`;console.error(line);try {appendFileSync(LOG_PATH, line + '\n');@@ -154,7 +164,10 @@ function log(msg) {function notify(title, msg) {try {- execSync(`osascript -e 'display notification "${msg.replace(/"/g, '\\"')}" with title "${title}"'`);+ // execFileSync (no shell) — title/msg cannot break out into a shell command.+ // Escape only for the AppleScript string literal (backslash + double-quote).+ const esc = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');+ execFileSync('osascript', ['-e', `display notification "${esc(msg)}" with title "${esc(title)}"`]);} catch {}}@@ -696,6 +709,19 @@ function checkBedrockAvailable(region) {}}+function stopClaudeDaemon() {+ log('[daemon-stop] Stopping Claude daemon...');+ try {+ const result = execSync('claude daemon stop --any', {+ encoding: 'utf8',+ env: { ...process.env, PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin' },+ });+ log(`[daemon-stop] Daemon stop success: ${result.trim()}`);+ } catch (err) {+ log(`[daemon-stop] Daemon stop failed: ${err.message}`);+ }+}+// Activate Bedrock fallback. Writes a sentinel + prints source instructions.// Cannot mutate env of an already-running session — user must start a new// one with `source ~/.claude/scripts/account-rotation/use-bedrock.sh`.@@ -738,6 +764,11 @@ async function activateBedrockFallback(reason, dryRun = false) {} catch (e) {log(`⚠ settings.json Bedrock persist failed: ${(e.message || e).toString().slice(0, 120)}`);}+ try {+ stopClaudeDaemon();+ } catch (e) {+ log(`⚠ stopClaudeDaemon failed: ${e.message}`);+ }log(`✅ BEDROCK FALLBACK ACTIVATED region=${region} reason=${reason}`);notify('Bedrock Fallback Active', `All Anthropic accounts exhausted — switched to Bedrock (${region}).`);console.log('');@@ -795,7 +826,10 @@ function _linuxWriteCred(svc, json) {writeFileSync(LINUX_CRED_PATH, JSON.stringify(store, null, 2), { mode: 0o600 });}-function readKeychain(svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {+function readKeychain(+ svc = KEYCHAIN_SERVICE,+ acct = svc === KEYCHAIN_SERVICE ? ACTIVE_KEYCHAIN_ACCOUNT : VAULT_KEYCHAIN_ACCOUNT,+) {if (IS_LINUX) {if (svc === KEYCHAIN_SERVICE) {// Main slot: return full credentials JSON@@ -819,7 +853,11 @@ function readKeychain(svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {return m[1].replace(/\\"/g, '"');}-function writeKeychain(json, svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {+function writeKeychain(+ json,+ svc = KEYCHAIN_SERVICE,+ acct = svc === KEYCHAIN_SERVICE ? ACTIVE_KEYCHAIN_ACCOUNT : VAULT_KEYCHAIN_ACCOUNT,+) {if (IS_LINUX) {_linuxWriteCred(svc, json);return;@@ -1394,7 +1432,7 @@ async function swapToken(account) {if (sourceAccount) {const currentJson = (() => {try {- return readKeychain(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);+ return readKeychain(KEYCHAIN_SERVICE, ACTIVE_KEYCHAIN_ACCOUNT);} catch {return null;}@@ -4019,7 +4057,7 @@ async function rotate(targetEmail, opts = {}) {} catch {}if (signaled > 0) {log(`[hot-swap] signaled ${signaled} Claude session(s) on ${sourceEmail} to reload after rotation`);- } else {+ } else if (pids.length > 0) {log(`[hot-swap] no live Claude sessions to signal on ${sourceEmail} (pruned stale pidfile)`);}}@@ -4210,11 +4248,11 @@ async function setup() {console.log(`✅ Saved to vault: ${tokenService(account)}`);results.push({ key, ok: true });} catch (e) {- console.error(`❌ Error: ${e.message}`);+ console.error(redactSecrets(`❌ Error: ${e.message}`));results.push({key,ok: false,- reason: String(e.message || e).slice(0, 80),+ reason: redactSecrets(String(e.message || e)).slice(0, 80),});}}@@ -4225,7 +4263,7 @@ async function setup() {const failCount = results.length - okCount;for (const r of results) {const icon = r.ok ? (r.skipped ? '⏭ ' : '✅') : '❌';- console.log(` ${icon} ${r.key}${r.reason ? ` (${r.reason})` : ''}`);+ console.log(redactSecrets(` ${icon} ${r.key}${r.reason ? ` (${r.reason})` : ''}`));}console.log(`\n${okCount}/${results.length} captured${failCount ? `, ${failCount} failed` : ''}.`);@@ -4386,7 +4424,7 @@ function captureCmd(targetEmail = null) {console.log(`✓ Token captured and saved to keychain: ${tokenService(account)}`);console.log(` Account: ${account.email}${account.label ? ' [' + account.label + ']' : ''}`);} catch (e) {- console.error(e.message);+ console.error(redactSecrets(e.message));process.exit(1);}}diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.mdindex f1a80784..fab9d8fe 100644--- a/claude-ops/skills/ops-inbox/SKILL.md+++ b/claude-ops/skills/ops-inbox/SKILL.md@@ -27,6 +27,8 @@ allowed-tools:# (no MCP entry needed for those).- mcp__claude_ai_Slack__slack_search_public_and_private- mcp__claude_ai_Slack__slack_read_channel+ - mcp__claude_ai_Slack__slack_list_channels+ - mcp__claude_ai_Slack__channels_list# Telegram: user-auth MCP tools added when configured# Notion: MCP tools (claude.ai integration or self-hosted)- mcp__claude_ai_Notion__notion-search