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): redact PII from NOTES + Prettier format all 3 files
auroracapital0f4d0e551fa5
diff --git a/claude-ops/scripts/account-rotation/NOTES-rotation-consistency.md b/claude-ops/scripts/account-rotation/NOTES-rotation-consistency.mdindex c35987bc..339e5535 100644--- a/claude-ops/scripts/account-rotation/NOTES-rotation-consistency.md+++ b/claude-ops/scripts/account-rotation/NOTES-rotation-consistency.md@@ -1,90 +1,133 @@# Rotation System: Consistency & Hardening NotesBranch: `fix/rotation-consistency`-Date: 2026-06-11-Author: Claude Code (claude-sonnet-4-6)+Date: 2026-06-11---## Canonical Account Naming### Rule+`accountKey(a)` = `a.label || a.email`This is the SINGLE canonical key used everywhere: vault entries, state.json, logs, S3 leases.-### Current account map+### Account schema-| Email | Label (canonical key) | Org | Notes |-|---|---|---|---|-| `[email protected]` | _(none — key = email)_ | personal | autoAuthDisabled |-| `[email protected]` | _(none — key = email)_ | personal | |-| `[email protected]` | _(none — key = email)_ | personal | |-| `[email protected]` | _(none — key = email)_ | personal | maxUtilPercent=50 |-| `[email protected]` | `account-team` | Account-Main (team org d38d677e) | |-| `[email protected]` | `account-main` | [email protected]'s Organization (personal c2002323) | |-| `[email protected]` | _(none — key = email)_ | personal | |-| `[email protected]` | _(none — key = email)_ | Account-Main team seat | |-| `[email protected]` | _(none — key = email)_ | Account-Main team seat | |-| `[email protected]` | _(none — key = email)_ | personal | |+Each entry in `config.json` has:++- `email` — the Anthropic account email (stored in gitignored config, not committed)+- `label` (optional) — short slug used as the canonical key when the same email has+ multiple org entries (e.g. `team-label` vs `personal-label` for the same address)+- `orgName` (optional) — the org name shown in the claude.ai org-chooser; used to+ disambiguate multi-org accounts during OAuth+- `orgUuid` (optional) — the org UUID for post-rotation verification++When `label` is absent the canonical key is the email itself. When `label` is present+it takes precedence — this is how two config entries that share the same email address+(e.g. a personal-org slot and a team-org slot) can each have a unique vault entry:+`Claude-Rotation-<label>` vs `Claude-Rotation-<email>`.### Vault key format-`Claude-Rotation-<accountKey>` — e.g.:-- `Claude-Rotation-account-team`-- `Claude-Rotation-account-main`-- `[email protected]`++`Claude-Rotation-<accountKey>` — examples (using generic placeholders):++- `Claude-Rotation-team-label` (when label is set)+- `[email protected]` (when no label)++Real account emails live only in gitignored `config.json` / plugin data dir, never+committed to the repo.### Stale key migration-`account-personal` was an old label that appeared in logs and state.json.-Config never had this label — it was a state.json artifact from a prior config.-Both `rotate.mjs` and `daemon.mjs` now apply `STATE_KEY_MIGRATIONS` on every `readState()` call:-`account-personal` → `account-main` (silently, one-time, then writes the corrected state).++An old label (`account-personal`) appeared in logs and state.json as a state.json+artifact from a prior config. Config never had that label.+Both `rotate.mjs` and `daemon.mjs` now apply `STATE_KEY_MIGRATIONS` on every+`readState()` call, renaming the stale key to the current canonical key (silently,+one-time, then writes the corrected state).---## Bug Fixes Applied### 1. Session enumeration (CRITICAL — sessions never detected)+**File:** `rotate.mjs` — `findClaudeSessions()`**Root cause:** `ps -eo pid,tty,args | grep -E '...' | grep -v 'mcp ' | grep -v '\-p '`-The trailing `grep -v '\-p '` was missing its pattern in some shell expansions and silently became `grep -` (empty pattern = matches nothing → exit 1). The whole `execSync` threw, and the catch logged `Failed to enumerate sessions`. Also: macOS background processes show `tty=??` which never matched the `ttys?\d+` regex in the line parser.-**Fix:** Drop `tty` from `ps` entirely: `ps -eo pid,args | grep -E '[c]laude.*--dangerously-skip-permissions' | grep -v 'grep'`. Update tmux pane lookup to use `#{pane_pid}` (not tty). Update line parser to `^(\d+)\s+(.+)$`.-**Verified:** `ps -eo pid,args | grep -E '[c]laude.*--dangerously-skip-permissions'` returns real PIDs on this Mac.+The trailing `grep -v '\-p '` was missing its pattern in some shell expansions and+silently became `grep -` (empty pattern = matches nothing → exit 1). The whole+`execSync` threw, and the catch logged `Failed to enumerate sessions`. Also: macOS+background processes show `tty=??` which never matched the `ttys?\d+` regex in the+line parser.+**Fix:** Drop `tty` from `ps` entirely:+`ps -eo pid,args | grep -E '[c]laude.*--dangerously-skip-permissions' | grep -v 'grep'`.+Update tmux pane lookup to use `#{pane_pid}` (not tty). Update line parser to+`^(\d+)\s+(.+)$`.+**Verified:** fixed command returns real PIDs for running sessions on macOS.### 2. `require()` in ESM module (Linux/macOS breakage)+**File:** `daemon.mjs` — `shouldRotate()` in-place refresh path-**Root cause:** `require('child_process').execSync(...)` — `require` doesn't exist in ES modules (`.mjs`). Silently threw a ReferenceError on both platforms, skipping the mcpOAuth merge.-**Fix:** Replace with `readActiveKeychainToken()` (already platform-aware, already imported). Write path uses `spawnSync('security', ...)` on macOS, `writeFileSync` on Linux.+**Root cause:** `require('child_process').execSync(...)` — `require` doesn't exist in+ES modules (`.mjs`). Silently threw a ReferenceError on both platforms, skipping the+mcpOAuth merge.+**Fix:** Replace with `readActiveKeychainToken()` (already platform-aware, already+imported). Write path uses `spawnSync('security', ...)` on macOS, `writeFileSync` on+Linux.++### 3. Hot-loop rescue on exhausted accounts-### 3. Hot-loop rescue on exhausted accounts (FIXED)**File:** `daemon.mjs` — `shouldRotate()` multi-session rescue path-**Root cause:** When a parallel session on `[email protected]` was at 100%, the daemon re-probed and re-logged `is hot — rotating keychain to rescue` every 30s cycle. The existing `FILE_ROTATION_MIN_INTERVAL` anti-thrash cap is 2 minutes, but it only applies after a rotation was actually attempted. The rescue path hit the `return { should: true }` before reaching the cap.-**Fix:** Added `_parkedUntil` map. When a mismatched account is confirmed >=95% live, it's parked until its `reset5h || reset7d` + 2 min buffer. Every subsequent cycle checks `isParked(probeKey)` first (no network call) and returns `{ should: false }`. Park clears automatically when the reset window passes.+**Root cause:** When a parallel session's account was at 100% utilization, the daemon+re-probed and re-logged `is hot — rotating keychain to rescue` every 30s cycle. The+existing `FILE_ROTATION_MIN_INTERVAL` anti-thrash cap (2 minutes) only applies after+a rotation was actually attempted. The rescue path hit `return { should: true }` before+reaching the cap.+**Fix:** Added `_parkedUntil` map. When a mismatched account is confirmed >=95% live,+it is parked until its `reset5h || reset7d` + 2 min buffer. Every subsequent cycle+checks `isParked(probeKey)` first (no network call) and returns `{ should: false }`.+Park clears automatically when the reset window passes.### 4. Linux parity+**File:** `daemon.mjs`Changes:-- `notify()`: was `execSync(osascript ...)` with no Linux branch. Fixed to `spawnSync('notify-send', ...)` on Linux, `spawnSync('osascript', ...)` on macOS (no shell, no injection).-- `refreshSingleToken()`: vault write was macOS `security add-generic-password` with shell interpolation. Fixed to platform-aware: Linux writes to `LINUX_CRED_PATH` JSON store, macOS uses `spawnSync('security', [...])` with args array (no shell).-- `readState()`: added `STATE_KEY_MIGRATIONS` (same as rotate.mjs) for consistent key normalization on both platforms.++- `notify()`: was `execSync(osascript ...)` with no Linux branch. Fixed to+ `spawnSync('notify-send', ...)` on Linux, `spawnSync('osascript', ...)` on macOS+ (no shell, no injection risk).+- `refreshSingleToken()`: vault write was macOS `security add-generic-password` with+ shell interpolation. Fixed to platform-aware: Linux writes to `LINUX_CRED_PATH` JSON+ store, macOS uses `spawnSync('security', [...])` with args array (no shell).+- `readState()`: added `STATE_KEY_MIGRATIONS` (same as rotate.mjs) for consistent key+ normalization on both platforms.### 5. Naming consistency in logs+**File:** `daemon.mjs`-The rescue log line used `taggedEmail` (raw email address, e.g. `[email protected]`) instead of the canonical `probeKey` (label, e.g. `account-team`). Changed to `${probeKey} (${taggedEmail})` so the canonical key is always primary and the email is context.+The rescue log line used the raw email address instead of the canonical `probeKey`+(label or email). Changed to `${probeKey} (${taggedEmail})` so the canonical key is+always primary and the raw email is context.---## Per-Session Account Routing (foundation, feature-flagged)**File:** `session-router.mjs` (new)-**Activation:** `CLAUDE_SESSION_ROUTING=1` env var (unset = disabled, existing global-keychain behavior unchanged)+**Activation:** `CLAUDE_SESSION_ROUTING=1` env var (unset = disabled, existing+global-keychain behavior unchanged)### Why the global keychain is insufficient at scale-When 8+ concurrent sessions all share one keychain entry, they all use the same account and hit its rate limit together. A keychain swap helps the NEXT tool call but all sessions then pile onto the new account simultaneously.++When many concurrent sessions share one keychain entry, they all use the same account+and hit its rate limit together. A keychain swap helps the NEXT tool call but all+sessions then pile onto the new account simultaneously.### Architecture+```session-leases.json ← persistent lease map: { sessionId → { accountKey, ts, pid } }-+pickAccountForSession(sessionId, config, state)→ finds least-utilized account not leased to another live session→ returns accountKey | null (null = use global keychain)@@ -97,15 +140,23 @@ spawnWithAccount(args, config, state, opts)```### Why CLAUDE_CODE_OAUTH_TOKEN and not a separate credential file-Claude Code reads `CLAUDE_CODE_OAUTH_TOKEN` from env at startup — this is the cleanest per-process isolation path that doesn't require touching the shared keychain. Each session gets its own env, sessions are completely isolated.++Claude Code reads `CLAUDE_CODE_OAUTH_TOKEN` from env at startup — this is the cleanest+per-process isolation path that doesn't require touching the shared keychain. Each+session gets its own env; sessions are completely isolated.### What's NOT implemented (needs live auth test — left branch-only)-- Daemon auto-spawning sessions with routing (requires knowing the session's final command line before it starts — not available at daemon level today).-- Migrating existing sessions mid-flight to a new token (safe only if the session is idle; risky to do mid-tool-call — left as future work with explicit `needs input:` gate).++- Daemon auto-spawning sessions with routing (requires knowing the session's final+ command line before it starts — not available at daemon level today).+- Migrating existing sessions mid-flight to a new token (safe only if the session is+ idle; risky to do mid-tool-call — left as future work with explicit `needs input:` gate).- Dashboard integration (`--session-leases` CLI flag in rotate.mjs).### Safe to deploy-`session-router.mjs` is import-only. Nothing calls it unless `CLAUDE_SESSION_ROUTING=1` is set. The global keychain path is completely unaffected.++`session-router.mjs` is import-only. Nothing calls it unless `CLAUDE_SESSION_ROUTING=1`+is set. The global keychain path is completely unaffected.---@@ -113,8 +164,8 @@ Claude Code reads `CLAUDE_CODE_OAUTH_TOKEN` from env at startup — this is the| File | Change ||---|---|-| `rotate.mjs` | Bug 1: `findClaudeSessions()` ps command + parser. Bug 2 naming: `STATE_KEY_MIGRATIONS` in `readState()`. |-| `daemon.mjs` | Bug 2: `require()` → `readActiveKeychainToken()`. Bug 3: `_parkedUntil` park map + park logic in `shouldRotate()`. Bug 4: `notify()` Linux branch, `refreshSingleToken()` platform-aware vault write, `readState()` key migration. Bug 5: log line uses `probeKey` not raw `taggedEmail`. |+| `rotate.mjs` | Bug 1: `findClaudeSessions()` ps command + parser. Naming: `STATE_KEY_MIGRATIONS` in `readState()`. |+| `daemon.mjs` | Bug 2: `require()` → `readActiveKeychainToken()`. Bug 3: `_parkedUntil` park map + park logic in `shouldRotate()`. Bug 4: `notify()` Linux branch, `refreshSingleToken()` platform-aware vault write, `readState()` key migration. Bug 5: log line uses `probeKey` not raw email. || `session-router.mjs` | NEW: per-session routing foundation (feature-flagged, no existing behavior changed). || `NOTES-rotation-consistency.md` | This file. |diff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjsindex fee0acfd..2affcfdf 100644--- a/claude-ops/scripts/account-rotation/daemon.mjs+++ b/claude-ops/scripts/account-rotation/daemon.mjs@@ -23,18 +23,8 @@* node daemon.mjs --status # Show daemon status*/-import {- readFileSync,- writeFileSync,- existsSync,- unlinkSync,- appendFileSync,- statSync,-} from 'fs';-import {- persistBedrockClaudeSettings,- clearHardcodedModelsForOAuthClaudeSettings,-} from './claude-settings-mode.mjs';+import { readFileSync, writeFileSync, existsSync, unlinkSync, appendFileSync, statSync } from 'fs';+import { persistBedrockClaudeSettings, clearHardcodedModelsForOAuthClaudeSettings } from './claude-settings-mode.mjs';import {destinationUtilHardBlock,DAEMON_SAFE_5H_PCT,@@ -155,7 +145,14 @@ function readConfig() {const st = JSON.parse(readFileSync(STATE_PATH, 'utf8'));keepKey = st.activeAccount || null;} catch {}- return applyAccountLeases(config, { keepKey, log: (m) => { try { log(m); } catch {} } });+ return applyAccountLeases(config, {+ keepKey,+ log: (m) => {+ try {+ log(m);+ } catch {}+ },+ });}// Legacy account-key renames: old label → new canonical key.// Applied once per readState() call to keep state.json consistent as labels evolve.@@ -193,7 +190,9 @@ function readState() {}}if (migrated) {- try { writeFileSync(STATE_PATH, JSON.stringify(state, null, 2)); } catch {}+ try {+ writeFileSync(STATE_PATH, JSON.stringify(state, null, 2));+ } catch {}}return state;}@@ -532,7 +531,9 @@ async function shouldRotate(config, state) {log(`[anti-thrash] file says ${rl.reason} but active ${state.activeAccount} live 5h=${live.pct5h}% 7d=${live.pct7d}% — skipping (stale .rate-limits.json)`,);- try { unlinkSync(RATE_LIMITS_FILE); } catch {}+ try {+ unlinkSync(RATE_LIMITS_FILE);+ } catch {}}// Mismatched + not hot = just a low-util parallel session; silent skip.return { should: false };@@ -545,8 +546,11 @@ async function shouldRotate(config, state) {if (liveMax >= PARK_THRESHOLD_PCT) {// Prefer the 5h reset (shorter) so the park clears as soon as possible.const resetEpoch = live.reset5h || live.reset7d || null;- parkAccount(probeKey, resetEpoch,- `live ${liveMax.toFixed(0)}% >= ${PARK_THRESHOLD_PCT}% exhausted (5h=${live.pct5h.toFixed(0)}% 7d=${live.pct7d.toFixed(0)}%)`);+ parkAccount(+ probeKey,+ resetEpoch,+ `live ${liveMax.toFixed(0)}% >= ${PARK_THRESHOLD_PCT}% exhausted (5h=${live.pct5h.toFixed(0)}% 7d=${live.pct7d.toFixed(0)}%)`,+ );return { should: false };}log(@@ -565,7 +569,9 @@ async function shouldRotate(config, state) {const sinceLast = Date.now() - lastRotMs;if (lastRotMs && sinceLast < FILE_ROTATION_MIN_INTERVAL) {const remaining = Math.ceil((FILE_ROTATION_MIN_INTERVAL - sinceLast) / 1000);- log(`[anti-thrash] utilization-rotation cap: skipping "${rl.reason}" (last rotation ${Math.floor(sinceLast / 1000)}s ago, ${remaining}s until cap clears)`);+ log(+ `[anti-thrash] utilization-rotation cap: skipping "${rl.reason}" (last rotation ${Math.floor(sinceLast / 1000)}s ago, ${remaining}s until cap clears)`,+ );return { should: false };}}@@ -621,7 +627,9 @@ async function shouldRotate(config, state) {}tokenToWrite = JSON.stringify(freshParsed);}- } catch (_mergeErr) { /* merge failed — fall through to raw write */ }+ } catch (_mergeErr) {+ /* merge failed — fall through to raw write */+ }// Write via platform-aware path: Linux credentials file or macOS keychain.if (IS_LINUX) {// On Linux the active token lives in LINUX_CRED_PATH as a flat@@ -629,15 +637,23 @@ async function shouldRotate(config, state) {// other fields (mcpOAuth, etc.) already present in the file.try {let existing = {};- try { existing = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8')); } catch {}+ try {+ existing = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));+ } catch {}const merged = { ...existing, ...JSON.parse(tokenToWrite) };writeFileSync(LINUX_CRED_PATH, JSON.stringify(merged, null, 2), { mode: 0o600 });- } catch (_writeErr) { /* non-fatal — best-effort */ }+ } catch (_writeErr) {+ /* non-fatal — best-effort */+ }} else {// macOS: use spawnSync (no shell, no injection) instead of execSync.- spawnSync('security', ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', tokenToWrite], {- timeout: 5000,- });+ spawnSync(+ 'security',+ ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', tokenToWrite],+ {+ timeout: 5000,+ },+ );}log('[active-refresh] Active keychain updated with mcpOAuth preserved — sessions will auto-recover');}@@ -791,9 +807,7 @@ async function findValidRotationTarget(config, state) {continue;}if (cachedAge > 30) {- log(- `[pre-rotate] ${key}: live query FAILED + cache stale (${cachedAge.toFixed(0)}min) — REFUSING (safety)`,- );+ log(`[pre-rotate] ${key}: live query FAILED + cache stale (${cachedAge.toFixed(0)}min) — REFUSING (safety)`);continue;}log(@@ -871,7 +885,9 @@ async function allCandidatesExhausted(config, state) {if (now - cached.ts > 15 * 60_000) return false;if (cached.pct < EXHAUSTED_THRESHOLD) return false;}- log('[allCandidatesExhausted] cached-evidence path: live unreachable but cached + rate-limit signal confirm exhaustion');+ log(+ '[allCandidatesExhausted] cached-evidence path: live unreachable but cached + rate-limit signal confirm exhaustion',+ );return true;}@@ -1120,7 +1136,9 @@ async function refreshSingleToken(account) {if (IS_LINUX) {try {let store = {};- try { store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8')); } catch {}+ try {+ store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));+ } catch {}store[svc] = tokenStr;writeFileSync(LINUX_CRED_PATH, JSON.stringify(store, null, 2), { mode: 0o600 });} catch (writeErr) {@@ -1420,7 +1438,9 @@ async function mainLoop() {// excluding it. Best-effort / fail-open (S3 down => no-op). (Sam 2026-06-06)if (state.activeAccount && Date.now() - lastLeaseBeat > 180_000) {lastLeaseBeat = Date.now();- try { writeLease(state.activeAccount, (m) => log(m)); } catch {}+ try {+ writeLease(state.activeAccount, (m) => log(m));+ } catch {}}// Drift detection — every 2 min, find the actual live account.diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex 0e6d15f3..65e9b579 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -170,7 +170,14 @@ function readConfig() {const st = JSON.parse(readFileSync(STATE_PATH, 'utf8'));keepKey = st.activeAccount || null;} catch {}- return applyAccountLeases(config, { keepKey, log: (m) => { try { log(m); } catch {} } });+ return applyAccountLeases(config, {+ keepKey,+ log: (m) => {+ try {+ log(m);+ } catch {}+ },+ });}// All accounts' Claude login emails forward to ONE Gmail inbox, so every@@ -215,7 +222,10 @@ function readState() {}}if (migrated) {- try { writeFileSync(STATE_PATH + '.tmp.' + process.pid, JSON.stringify(state, null, 2)); renameSync(STATE_PATH + '.tmp.' + process.pid, STATE_PATH); } catch {}+ try {+ writeFileSync(STATE_PATH + '.tmp.' + process.pid, JSON.stringify(state, null, 2));+ renameSync(STATE_PATH + '.tmp.' + process.pid, STATE_PATH);+ } catch {}}return state;}@@ -543,12 +553,8 @@ function pickNextAccount(config, state, liveUtil = {}) {// Empty when allowExtraUsage (they already live in the pools above). Tried after// every non-EU pool, so an overage account is only ever picked when nothing else// is viable — better a paid token than a fully stalled session on an exhausted key.- const euNormal = config.accounts.filter(- (a) => a.priority !== 'low' && !excludeKey(a) && blockExtra(a),- );- const euLow = config.accounts.filter(- (a) => a.priority === 'low' && !excludeKey(a) && blockExtra(a),- );+ const euNormal = config.accounts.filter((a) => a.priority !== 'low' && !excludeKey(a) && blockExtra(a));+ const euLow = config.accounts.filter((a) => a.priority === 'low' && !excludeKey(a) && blockExtra(a));// Hard refusal for rotation *destination*: max(5h,7d) must stay below this.// Default 95 (matches EXHAUSTED for Bedrock). Lower with@@ -563,7 +569,7 @@ function pickNextAccount(config, state, liveUtil = {}) {// Per-account destination cap: an account may set `maxUtilPercent` in config to be// refused as a rotation target at a STRICTER threshold than the global UTIL_HARD_BLOCK.// min() ensures it can only tighten, never loosen, the global hard block.- // (Sam 2026-05-30: never rotate TO / use [email protected] once it's ≥50% on max(5h,7d).)+ // An account may set maxUtilPercent to cap it stricter than the global block (e.g. ≥50%).const capFor = (a) => Math.min(UTIL_HARD_BLOCK, a.maxUtilPercent ?? Infinity);const viable = candidates.filter((a) => score(a) < capFor(a));// Primary key: utilization score (freshest first). Tie-breaker: when two@@ -667,10 +673,7 @@ function recommendAccount(config, state, liveUtil) {return Math.max(u.five_hour_pct, u.seven_day_pct) >= EXHAUSTED_THRESHOLD;});const destinationCapStuck =- !pick &&- !onlyActiveViable &&- !allExhausted &&- allNonActiveLiveConfirmedOverDestinationCap(config, state, liveUtil);+ !pick && !onlyActiveViable && !allExhausted && allNonActiveLiveConfirmedOverDestinationCap(config, state, liveUtil);return { pick, allExhausted, allHaveLive, onlyActiveViable, destinationCapStuck };}@@ -735,10 +738,7 @@ async function activateBedrockFallback(reason, dryRun = false) {log(`⚠ settings.json Bedrock persist failed: ${(e.message || e).toString().slice(0, 120)}`);}log(`✅ BEDROCK FALLBACK ACTIVATED region=${region} reason=${reason}`);- notify(- 'Bedrock Fallback Active',- `All Anthropic accounts exhausted — switched to Bedrock (${region}).`,- );+ notify('Bedrock Fallback Active', `All Anthropic accounts exhausted — switched to Bedrock (${region}).`);console.log('');console.log('━━━ BEDROCK FALLBACK ACTIVE ━━━');console.log(`Reason : ${reason}`);@@ -772,16 +772,24 @@ function _linuxReadCred(svc) {function _linuxWriteCred(svc, json) {let store = {};- try { store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8')); } catch {}+ try {+ store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));+ } catch {}if (svc === KEYCHAIN_SERVICE) {// Main slot: merge claudeAiOauth only, preserve mcpOAuthtry {const incoming = JSON.parse(json);store.claudeAiOauth = incoming.claudeAiOauth || incoming;- } catch { store[svc] = json; }+ } catch {+ store[svc] = json;+ }} else {// Per-account vault slot- try { store[svc] = JSON.parse(json); } catch { store[svc] = json; }+ try {+ store[svc] = JSON.parse(json);+ } catch {+ store[svc] = json;+ }}writeFileSync(LINUX_CRED_PATH, JSON.stringify(store, null, 2), { mode: 0o600 });}@@ -878,7 +886,9 @@ function hasStoredToken(account) {// retries its handshake.function ensureSnapshotsDir() {- try { mkdirSync(OAUTH_SNAPSHOTS_DIR, { recursive: true }); } catch {}+ try {+ mkdirSync(OAUTH_SNAPSHOTS_DIR, { recursive: true });+ } catch {}}function snapshotPathFor(key) {@@ -926,13 +936,7 @@ function isChromeProfileRunning(profileDir) {}}-const CHROME_PROFILES_BASE = join(- process.env.HOME || '',- 'Library',- 'Application Support',- 'Google',- 'Chrome',-);+const CHROME_PROFILES_BASE = join(process.env.HOME || '', 'Library', 'Application Support', 'Google', 'Chrome');function chromeProfilePath(profileDir) {return join(CHROME_PROFILES_BASE, profileDir);@@ -1010,10 +1014,10 @@ function writeChromeLocalStateAtomic(obj) {}// Human-friendly display name from an accountKey. Best-effort:-// `[email protected]` → `My-Project Support`-// `[email protected]` → `Example`-// `account-main` → `Account-Main`-// `[email protected]` → `Account-Main Foundation`+// `[email protected]` → `Example Support`+// `[email protected]` → `Myorg`+// `team-label` → `Team-Label`+// `[email protected]` → `Example Foundation`function displayNameFor(account) {const key = accountKey(account);if (account.displayName) return account.displayName;@@ -1022,9 +1026,9 @@ function displayNameFor(account) {}const [local, domain] = key.split('@');const domainParts = (domain || '').split('.');- // For [email protected] → "Account-A"- // For [email protected] → "Example"- // For [email protected] → "My-Project Support"+ // For [email protected] → "Example"+ // For [email protected] → "Myorg"+ // For [email protected] → "Example Support"const orgRaw = domainParts[0] || '';// CamelCase split of org: "example" → "Example"const org = orgRaw@@ -1037,7 +1041,7 @@ function displayNameFor(account) {return `${org} ${local.charAt(0).toUpperCase() + local.slice(1)}`;}// For personal mailboxes (sam@…), use Org only if org is meaningful, else email local- return org || (local.charAt(0).toUpperCase() + local.slice(1));+ return org || local.charAt(0).toUpperCase() + local.slice(1);}function launchChromeProfile(profileDir, url) {@@ -1075,8 +1079,12 @@ function readClaudeJson() {function writeClaudeJsonAtomic(obj) {const tmp = `${CLAUDE_JSON_PATH}.tmp.${process.pid}.${Date.now()}`;writeFileSync(tmp, JSON.stringify(obj, null, 2));- try { renameSync(tmp, CLAUDE_JSON_PATH); } catch (e) {- try { unlinkSync(tmp); } catch {}+ try {+ renameSync(tmp, CLAUDE_JSON_PATH);+ } catch (e) {+ try {+ unlinkSync(tmp);+ } catch {}throw e;}}@@ -1129,7 +1137,9 @@ function captureOauthSnapshot(accountEmail) {function loadOauthSnapshot(accountKeyOrEmail) {const direct = snapshotPathFor(accountKeyOrEmail);if (existsSync(direct)) {- try { return JSON.parse(readFileSync(direct, 'utf8')); } catch {}+ try {+ return JSON.parse(readFileSync(direct, 'utf8'));+ } catch {}}// Fallback: resolve via config (label↔email)const cfg = readConfig();@@ -1141,7 +1151,9 @@ function loadOauthSnapshot(accountKeyOrEmail) {if (acct) {const alt = snapshotPathFor(accountKey(acct));if (existsSync(alt)) {- try { return JSON.parse(readFileSync(alt, 'utf8')); } catch {}+ try {+ return JSON.parse(readFileSync(alt, 'utf8'));+ } catch {}}}return null;@@ -1184,7 +1196,9 @@ function restoreOauthBlocksFromBackup() {const backup = JSON.parse(readFileSync(BROWSER_PIN_BACKUP_PATH, 'utf8'));const applied = applyOauthSnapshotToClaudeJson({ blocks: backup.blocks });if (applied) log(`[oauth-snapshot] restored backup oauthAccount=${backup.email}`);- try { unlinkSync(BROWSER_PIN_BACKUP_PATH); } catch {}+ try {+ unlinkSync(BROWSER_PIN_BACKUP_PATH);+ } catch {}return applied;} catch (e) {log(`[oauth-snapshot] backup restore failed: ${e.message?.slice(0, 100)}`);@@ -1325,7 +1339,9 @@ async function refreshExpiredStoredToken(account, tokenJson) {});const body = await res.json().catch(() => ({}));if (!res.ok || !body.access_token) {- log(`[refresh] ${accountKey(account)}: refresh_token grant failed — ${body?.error?.message || `HTTP ${res.status}`}`);+ log(+ `[refresh] ${accountKey(account)}: refresh_token grant failed — ${body?.error?.message || `HTTP ${res.status}`}`,+ );return null;}const updated = {@@ -1375,7 +1391,13 @@ async function swapToken(account) {const swapConfig = readConfig();const sourceAccount = swapConfig.accounts.find((a) => accountKey(a) === sourceKey);if (sourceAccount) {- const currentJson = (() => { try { return readKeychain(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT); } catch { return null; } })();+ const currentJson = (() => {+ try {+ return readKeychain(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);+ } catch {+ return null;+ }+ })();if (currentJson && currentJson.includes('claudeAiOauth')) {try {const parsed = JSON.parse(currentJson);@@ -1959,7 +1981,9 @@ async function makePlaywrightDriver() {if (attached) break;}if (!attached) {- log(`[playwright] Chrome Beta CDP didn't come up on :${CDP_PORT} within 15s — falling back to bundled Chromium`);+ log(+ `[playwright] Chrome Beta CDP didn't come up on :${CDP_PORT} within 15s — falling back to bundled Chromium`,+ );}} else {log('[playwright] No Chrome Beta / Chrome binary found — falling back to bundled Chromium');@@ -2259,7 +2283,9 @@ async function pollGmailForMagicLink(accountEmail, maxWaitMs = 120_000) {const inbox = magicLinkInbox();const acctArgs = inbox ? ['--account', inbox] : [];if (!inbox) {- log(`[magic-link] WARNING: no Gmail inbox configured (set CLAUDE_ROT_GMAIL_ACCOUNT or config.magicLinkGmailAccount)`);+ log(+ `[magic-link] WARNING: no Gmail inbox configured (set CLAUDE_ROT_GMAIL_ACCOUNT or config.magicLinkGmailAccount)`,+ );}while (Date.now() - startTime < maxWaitMs) {@@ -2267,7 +2293,15 @@ async function pollGmailForMagicLink(accountEmail, maxWaitMs = 120_000) {// Pull up to 10 recent matches so a stale top-result doesn't block us.const searchResult = execFileSync('gog',- ['gmail', 'search', 'subject:"Secure link to log in to Claude" newer_than:5m', '--max', '10', '-j', ...acctArgs],+ [+ 'gmail',+ 'search',+ 'subject:"Secure link to log in to Claude" newer_than:5m',+ '--max',+ '10',+ '-j',+ ...acctArgs,+ ],{ timeout: 15_000, stdio: ['ignore', 'pipe', 'pipe'] },).toString()@@ -2496,7 +2530,11 @@ async function runAuthFlow(driver, account) {// stall detector, otherwise AI-brain burns multiple decisions waiting for a// verification code that the deterministic Gmail poller can resolve or fail.if (account.useMagicLink && url.includes('claude.ai')) {- if (await handleClaudeMagicLinkEmailPrompt(url.includes('/oauth/authorize') ? 'OAuth page rendered login prompt' : 'Login prompt')) {+ if (+ await handleClaudeMagicLinkEmailPrompt(+ url.includes('/oauth/authorize') ? 'OAuth page rendered login prompt' : 'Login prompt',+ )+ ) {stallCount = 0;continue;}@@ -2941,7 +2979,10 @@ async function runAuthFlow(driver, account) {// the authorize page. If we're on /oauth/code/success or any non-claude.ai// URL, auth is done — stop hunting for a button that no longer exists.const currentUrl = await driver.currentUrl().catch(() => '');- if (currentUrl.includes('/oauth/code/success') || (currentUrl && !currentUrl.includes('claude.ai') && !currentUrl.includes('claude.com'))) {+ if (+ currentUrl.includes('/oauth/code/success') ||+ (currentUrl && !currentUrl.includes('claude.ai') && !currentUrl.includes('claude.com'))+ ) {log(`Auth already succeeded — URL moved to ${currentUrl.substring(0, 80)}`);authorized = true;break;@@ -3072,7 +3113,9 @@ async function runAuthFlow(driver, account) {}continue;}- log(`[magic-link] No magic link found in Gmail — magic-link-only, will re-poll next step (no Google fallback)`);+ log(+ `[magic-link] No magic link found in Gmail — magic-link-only, will re-poll next step (no Google fallback)`,+ );}}}@@ -3277,10 +3320,9 @@ 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'`,- { timeout: 5000 },- )+ const psOut = execSync(`ps -eo pid,args | grep -E '[c]laude.*--dangerously-skip-permissions' | grep -v 'grep'`, {+ timeout: 5000,+ }).toString().trim();if (!psOut) return sessions;@@ -3524,16 +3566,16 @@ async function rotate(targetEmail, opts = {}) {};}}- try { writeState(state); } catch {}+ try {+ writeState(state);+ } catch {}const bedrockOnExhausted = opts.bedrockOnExhausted !== false; // default ONif (!targetEmail) {const { pick, allExhausted, onlyActiveViable, destinationCapStuck } = recommendAccount(config, state, liveUtil);if (!pick) {if (onlyActiveViable) {- log(- 'Rotation skipped — already on the only viable Max account (API headroom; other accounts exhausted).',- );+ log('Rotation skipped — already on the only viable Max account (API headroom; other accounts exhausted).');return true;}if (allExhausted || destinationCapStuck) {@@ -3544,10 +3586,11 @@ async function rotate(targetEmail, opts = {}) {`Every live-confirmed non-active account is ≥${destinationUtilHardBlock(config)}% max(5h,7d) — no rotation target; engaging Bedrock fallback`,);}- if (bedrockOnExhausted) await activateBedrockFallback(- allExhausted ? 'all_accounts_exhausted_picker_null' : 'destination_cap_no_headroom',- dryRun,- );+ if (bedrockOnExhausted)+ await activateBedrockFallback(+ allExhausted ? 'all_accounts_exhausted_picker_null' : 'destination_cap_no_headroom',+ dryRun,+ );} else {log('No account available (see utilization / query logs above)');}@@ -3878,7 +3921,11 @@ async function rotate(targetEmail, opts = {}) {// Claim the cross-machine lease for the account we just activated so the other// machine's rotation excludes it. Best-effort / fail-open. Skip on dry-run.- if (!dryRun) { try { writeLease(key, (m) => log(m)); } catch {} }+ if (!dryRun) {+ try {+ writeLease(key, (m) => log(m));+ } catch {}+ }notify('Claude Account Rotation', `${verified ? '✓' : '⚠'} Now using ${key}`);@@ -4029,7 +4076,9 @@ async function setup() {}if (magicLinkMode && account.autoAuthDisabled === true && !filter) {- console.log(`⏭ Skipped: automated reauth disabled (${account.autoAuthDisabledReason || 'manual reauth required'}).`);+ console.log(+ `⏭ Skipped: automated reauth disabled (${account.autoAuthDisabledReason || 'manual reauth required'}).`,+ );results.push({ key, ok: true, skipped: true, reason: 'auto-auth-disabled' });continue;}@@ -4107,7 +4156,9 @@ async function setup() {// rotation would never save a single account whenever the profile API// is throttled (which is common mid-rotation).if (token && token.includes('claudeAiOauth') && !tokenExpired(token)) {- console.log(`⚠ Identity unverified (${profErr || 'no email'}) — token valid & unexpired, saving with caveat.`);+ console.log(+ `⚠ Identity unverified (${profErr || 'no email'}) — token valid & unexpired, saving with caveat.`,+ );} else {console.error(`\n❌ Verify failed (${profErr || 'no email'}) and token invalid/expired. Skipping save.`);results.push({ key, ok: false, reason: `verify-failed:${profErr || 'no-email'}` });@@ -4490,7 +4541,7 @@ if (args.includes('--setup')) {}// Exit codes: 0 = viable pick available, 2 = Bedrock path (exhausted or destination-cap stuck),// 3 = no viable pick but not confirmed for Bedrock (some queries failed — investigate).- process.exit(pick || onlyActiveViable ? 0 : (allExhausted || destinationCapStuck ? 2 : 3));+ process.exit(pick || onlyActiveViable ? 0 : allExhausted || destinationCapStuck ? 2 : 3);} else if (args.includes('--status')) {await showStatus();} else if (args.includes('--capture')) {@@ -4513,9 +4564,7 @@ if (args.includes('--setup')) {email = acct?.email || null;} catch {}if (!email) {- email =- process.env.CLAUDE_PIN_BROWSER_DEFAULT ||- (readConfig().accounts[0]?.email ?? null);+ email = process.env.CLAUDE_PIN_BROWSER_DEFAULT || (readConfig().accounts[0]?.email ?? null);}if (!email) {log('[pin-browser-active] no resolvable active account — skipping');@@ -4560,7 +4609,9 @@ if (args.includes('--setup')) {writeState(st);log(`[pin-browser] CLI pinned to ${accountKey(acct)}`);} else {- log(`[pin-browser] swapToken false for ${accountKey(acct)} (vault token missing/expired) — likely already active; pinning anyway`);+ log(+ `[pin-browser] swapToken false for ${accountKey(acct)} (vault token missing/expired) — likely already active; pinning anyway`,+ );}// Sync .claude.json oauthAccount/chromeExtension blocks to match.const targetKey = accountKey(acct);@@ -4610,7 +4661,10 @@ if (args.includes('--setup')) {}// Always (re)write the freeze sentinel so the daemon won't rotate away while// the browser bridge is in use. The hook refreshes this on every tool call.- writeFileSync(BROWSER_PIN_PATH, JSON.stringify({ email: pinEmail, until: Date.now() + ttlSec * 1000, ts: Date.now() }));+ writeFileSync(+ BROWSER_PIN_PATH,+ JSON.stringify({ email: pinEmail, until: Date.now() + ttlSec * 1000, ts: Date.now() }),+ );} catch (e) {log(`[pin-browser] error (non-fatal): ${(e.message || e).toString().slice(0, 120)}`);}@@ -4624,7 +4678,9 @@ if (args.includes('--setup')) {restoreOauthBlocksFromBackup();}if (existsSync(BROWSER_PIN_PATH)) {- try { unlinkSync(BROWSER_PIN_PATH); } catch {}+ try {+ unlinkSync(BROWSER_PIN_PATH);+ } catch {}}} catch (e) {log(`[release-browser-pin] error (non-fatal): ${(e.message || e).toString().slice(0, 120)}`);@@ -4705,7 +4761,9 @@ if (args.includes('--setup')) {continue;}let pf;- try { pf = JSON.parse(probe.stdout); } catch (e) {+ try {+ pf = JSON.parse(probe.stdout);+ } catch (e) {console.error(`[skip] ${acct.email}: /oauth/profile non-JSON response`);failCount++;continue;@@ -4767,7 +4825,10 @@ if (args.includes('--setup')) {// per-account profile gets a clear display name + distinct theme color in// Chrome's profile picker. Chrome must be QUIT first — it rewrites Local// State on shutdown, clobbering changes made while it is running.- if (isChromeProfileRunning('ClaudeCode') || readdirSync(CHROME_PROFILES_BASE).some((d) => d.startsWith('ClaudeCode') && isChromeProfileRunning(d))) {+ if (+ isChromeProfileRunning('ClaudeCode') ||+ readdirSync(CHROME_PROFILES_BASE).some((d) => d.startsWith('ClaudeCode') && isChromeProfileRunning(d))+ ) {console.error('[colorize] Chrome is running with a ClaudeCode profile. Quit all of them first:');console.error(' pkill -f "profile-directory=ClaudeCode"');process.exit(2);diff --git a/claude-ops/scripts/account-rotation/session-router.mjs b/claude-ops/scripts/account-rotation/session-router.mjsindex cbf761b5..ef6c531a 100644--- a/claude-ops/scripts/account-rotation/session-router.mjs+++ b/claude-ops/scripts/account-rotation/session-router.mjs@@ -71,7 +71,10 @@ function pruneLeases(leases) {// Also check if the pid is still alivelet alive = false;if (entry.pid) {- try { process.kill(entry.pid, 0); alive = true; } catch {}+ try {+ process.kill(entry.pid, 0);+ alive = true;+ } catch {}}if (!alive) {delete leases[sid];@@ -292,7 +295,10 @@ export function listSessionLeases() {const ageMins = ((now - (entry.ts || 0)) / 60_000).toFixed(1);let alive = false;if (entry.pid) {- try { process.kill(entry.pid, 0); alive = true; } catch {}+ try {+ process.kill(entry.pid, 0);+ alive = true;+ } catch {}}result.push({sessionId: sid,