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(crs): config-driven pool scheduler and token-feed improvements (#633)
Aurora Capitalfa791ea0c7d5
diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.mdindex 2aa43d5e..2980f4ea 100644--- a/claude-ops/scripts/account-rotation/README.md+++ b/claude-ops/scripts/account-rotation/README.md@@ -53,6 +53,24 @@ Each account entry:| `dashlaneTokenPath` | no | If you store the token in Dashlane: `dl://<vault-name>/password`. || `extraUsageEnabled` | no | Set to `true` ONLY if the account has paid overage on. Triggers safety margin. || `capacityMultiplier` | no | Override per-account threshold (default 1.0 = standard Max 20x quota). |+| `crsAccountName` | no | CRS admin account name this vault entry maps to (for crs-token-feed / crs-priority). |++## CRS pool (optional)++If you run [claude-relay-service](https://github.com/anthropics/claude-relay-service) (CRS) alongside the rotator:++1. Add `crsAccountName` on each account (must match the account `name` in the CRS admin UI), or supply `crs.nameByVaultKey` in `config.json`.+2. Set `crs.enabled`, `crs.baseUrl`, and install the priority daemon: `scripts/install-crs-priority-agent.sh`.+3. On Linux/EC2, `crs-token-feed.mjs` propagates vault tokens into CRS (systemd timer when installed).+4. On macOS clients that reach a **remote** CRS via SSH, install the tunnel (requires `CRS_TUNNEL_SSH_HOST`):++ ```bash+ CRS_TUNNEL_SSH_HOST=your-remote-host bash scripts/install-crs-fra-tunnel.sh+ ```++ Point Claude Code at `http://127.0.0.1:3005/api` (or your `CRS_TUNNEL_LOCAL_PORT`).++See `config.example.json` → `crs` block for all tunables (`policy`, `fileVaultPath`, `containerName`, thresholds).## Keychain layoutdiff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.jsonindex 92ff251b..d2035388 100644--- a/claude-ops/scripts/account-rotation/config.example.json+++ b/claude-ops/scripts/account-rotation/config.example.json@@ -4,6 +4,7 @@"_account_schema_example": {"email": "[email protected]","label": "optional-disambiguator",+ "crsAccountName": "pool-example","orgName": "Optional Workspace Name","orgUuid": "optional-workspace-uuid","dashlaneTokenPath": "dl://[email protected]/password",@@ -28,17 +29,25 @@"refreshSession": false,"notifyOnRotation": true,"crs": {- "_comment": "Optional: auto-prioritization for a claude-relay-service (CRS) pool. CRS load-balances across many Claude accounts at once and exposes a per-account 'schedulable' flag. The crs-priority daemon flips that flag from live utilization so the pool avoids near-maxed accounts and re-enables them on recovery. Off by default — set enabled=true and install via scripts/install-crs-priority-agent.sh. Admin password is NOT stored here: set $CRS_ADMIN_PASSWORD or `lib/credential-store.sh set CRS-Admin-<adminUser> \"$USER\" '<pw>'`.",+ "_comment": "Optional: claude-relay-service (CRS) pool integration. Off by default — set enabled=true and install via scripts/install-crs-priority-agent.sh. Map each rotator account to its CRS row with crsAccountName on the account entry (or crs.nameByVaultKey). Admin password is NOT stored here: set $CRS_ADMIN_PASSWORD or credential-store CRS-Admin-<adminUser>.","enabled": false,- "baseUrl": "http://127.0.0.1:3000",+ "policy": "conservative",+ "_policy_note": "conservative (default) deprioritizes on utilization/session warnings; max-out keeps accounts schedulable until genuine rate-limit or overload (util % is telemetry only). Override with $CRS_POLICY.",+ "baseUrl": "http://127.0.0.1:3005",+ "fileVaultPath": "~/.claude/.credentials.json",+ "containerName": "crs-claude-relay-1","adminUser": "cradmin","adminPasswordEnv": "CRS_ADMIN_PASSWORD",+ "policy": "conservative",+ "nameByVaultKey": {+ "[email protected]": "pool-example"+ },"off5h": 90,"off7d": 95,"on5h": 70,"on7d": 85,"floor": 3,"freshMinutes": 15,- "_thresholds_note": "off* = deprioritize when fresh 5h/7d utilization reaches these; on* = re-enable only when all utilization drops below these (hysteresis prevents flapping). floor = minimum usable (schedulable, not-rate-limited) accounts kept even under soft pressure. freshMinutes = max age of claudeUsage data trusted for proactive deprioritize (stale/absent usage never drives a re-enable; real-time sessionWindowStatus + rate-limit + overload always do)."+ "_thresholds_note": "Legacy conservative thresholds (off/on/floor) apply only when policy=conservative. Default max-out policy keeps accounts schedulable until genuine rate-limit or overload; utilization % is telemetry only. freshMinutes = max age of claudeUsage trusted for secondary signals."}}diff --git a/claude-ops/scripts/account-rotation/crs-health-watch.mjs b/claude-ops/scripts/account-rotation/crs-health-watch.mjsindex 1037e669..dbed4666 100644--- a/claude-ops/scripts/account-rotation/crs-health-watch.mjs+++ b/claude-ops/scripts/account-rotation/crs-health-watch.mjs@@ -52,7 +52,7 @@ const HEALTH_URL = process.env.CRS_HEALTH_URL || ROUTE_CRS.healthUrl || CRS_BASEconst CRS_SMOKE_URL = process.env.CRS_SMOKE_URL || `${CRS_BASE}/v1/messages?beta=true`;const CRS_SMOKE_MODEL = process.env.CRS_SMOKE_MODEL || 'claude-sonnet-4-6';const DOWN_STRIKES = +(process.env.CRS_DOWN_STRIKES || 3); // ~3 min at 60s tick-const UP_STRIKES = +(process.env.CRS_UP_STRIKES || 3);+const UP_STRIKES = +(process.env.CRS_UP_STRIKES || 1);const ts = () => new Date().toISOString().slice(11, 19);const log = (m) => console.log(`${ts()} [crs-health-watch] ${m}`);diff --git a/claude-ops/scripts/account-rotation/crs-pool-config.mjs b/claude-ops/scripts/account-rotation/crs-pool-config.mjsnew file mode 100644index 00000000..15fa102b--- /dev/null+++ b/claude-ops/scripts/account-rotation/crs-pool-config.mjs@@ -0,0 +1,115 @@+#!/usr/bin/env node+/**+ * crs-pool-config.mjs — shared CRS + rotation config resolution for public installs.+ *+ * Vault key ↔ CRS account name mapping is NEVER hardcoded in repo scripts.+ * Configure per account via `crsAccountName` and/or optional `crs.nameByVaultKey`.+ */++import { readFileSync, existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { homedir } from 'os';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || join(__dirname, '..', '..');+const DATA_DIR =+ process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');++export const CONFIG_CANDIDATES = [+ process.env.CRS_CONFIG,+ join(DATA_DIR, 'account-rotation', 'config.json'),+ join(homedir(), '.claude', 'plugins', 'data', 'ops', 'account-rotation', 'config.json'),+ join(PLUGIN_ROOT, 'scripts', 'account-rotation', 'config.json'),+ join(__dirname, 'config.json'),+].filter(Boolean);++export function resolveConfigPath() {+ for (const p of CONFIG_CANDIDATES) {+ if (existsSync(p)) return p;+ }+ return null;+}++export function loadRotationConfig() {+ const path = resolveConfigPath();+ if (!path) return { crs: {}, accounts: [] };+ try {+ return { crs: {}, accounts: [], ...JSON.parse(readFileSync(path, 'utf8')) };+ } catch {+ return { crs: {}, accounts: [] };+ }+}++/**+ * @returns {{ nameByVaultKey: Record<string,string>, vaultKeyByCrsName: Record<string,string> }}+ */+export function buildCrsNameMaps(config = loadRotationConfig()) {+ const nameByVaultKey = {};+ const vaultKeyByCrsName = {};++ const overrides = config.crs?.nameByVaultKey;+ if (overrides && typeof overrides === 'object') {+ for (const [vaultKey, crsName] of Object.entries(overrides)) {+ if (!vaultKey || !crsName) continue;+ nameByVaultKey[vaultKey] = crsName;+ if (!vaultKeyByCrsName[crsName]) vaultKeyByCrsName[crsName] = vaultKey;+ }+ }++ for (const a of config.accounts || []) {+ const crsName = a.crsAccountName || a.crsName;+ if (!crsName) continue;+ const keys = [];+ if (a.email) keys.push(a.email);+ if (a.label) keys.push(a.label);+ for (const k of keys) {+ if (!k) continue;+ nameByVaultKey[k] = crsName;+ }+ if (!vaultKeyByCrsName[crsName]) {+ vaultKeyByCrsName[crsName] = a.email || a.label || null;+ }+ }++ for (const [vaultKey, crsName] of Object.entries(nameByVaultKey)) {+ if (crsName && !vaultKeyByCrsName[crsName]) vaultKeyByCrsName[crsName] = vaultKey;+ }++ return { nameByVaultKey, vaultKeyByCrsName };+}++export function crsBaseUrl(config = loadRotationConfig()) {+ return process.env.CRS_BASE || config.crs?.baseUrl || 'http://127.0.0.1:3005';+}++export function crsFileVaultPath(config = loadRotationConfig()) {+ const fromEnv = process.env.CRS_FILE_VAULT;+ if (fromEnv) return fromEnv.replace(/^~(?=$|\/)/, homedir());+ const fromCfg = config.crs?.fileVaultPath;+ if (fromCfg) return fromCfg.replace(/^~(?=$|\/)/, homedir());+ return join(homedir(), '.claude', '.credentials.json');+}++export function crsPolicy(config = loadRotationConfig()) {+ const raw = String(process.env.CRS_POLICY || config.crs?.policy || 'conservative')+ .trim()+ .toLowerCase()+ .replace(/_/g, '-');+ if (raw === 'maxout' || raw === 'max-out') return 'max-out';+ return 'conservative';+}++export function vaultLookupKeysForEmail(email, accounts = []) {+ const keys = new Set();+ if (email) keys.add(email);+ for (const a of accounts) {+ const label = a.label || a.email;+ const addr = a.email || a.label;+ if (addr === email || label === email) {+ if (label) keys.add(label);+ if (addr) keys.add(addr);+ }+ }+ return [...keys];+}diff --git a/claude-ops/scripts/account-rotation/crs-pool-config.test.mjs b/claude-ops/scripts/account-rotation/crs-pool-config.test.mjsnew file mode 100644index 00000000..4a941aa2--- /dev/null+++ b/claude-ops/scripts/account-rotation/crs-pool-config.test.mjs@@ -0,0 +1,19 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { buildCrsNameMaps, crsPolicy } from './crs-pool-config.mjs';++test('buildCrsNameMaps uses crsAccountName and nameByVaultKey', () => {+ const config = {+ accounts: [{ email: '[email protected]', crsAccountName: 'pool-a' }],+ crs: { nameByVaultKey: { legacy: 'pool-legacy' } },+ };+ const { nameByVaultKey, vaultKeyByCrsName } = buildCrsNameMaps(config);+ assert.equal(nameByVaultKey['[email protected]'], 'pool-a');+ assert.equal(nameByVaultKey.legacy, 'pool-legacy');+ assert.equal(vaultKeyByCrsName['pool-a'], '[email protected]');+});++test('crsPolicy defaults to conservative', () => {+ assert.equal(crsPolicy({ crs: {} }), 'conservative');+ assert.equal(crsPolicy({ crs: { policy: 'max-out' } }), 'max-out');+});diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjsindex 9aa71d77..1f46585b 100755--- a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs@@ -18,19 +18,19 @@// sessionWindow.sessionWindowStatus (allowed | allowed_warning | …)// claudeUsage.{fiveHour,sevenDay,sevenDayOpus}.utilization (fresh secondary only)//-// POLICY:-// DEPRIORITIZE (schedulable=false) when any of:-// rate-limited | overloaded | sessionWindowStatus∈WARN | FRESH util ≥ OFF_*-// RE-ENABLE (schedulable=true) only when ALL of:-// not rate-limited & not overloaded & sessionWindowStatus∈{allowed,absent}-// & (util stale/absent OR all util < ON_*)-// else hold (hysteresis band). FLOOR keeps ≥N usable accounts (soft-offs are-// reverted lowest-util-first; hard rate-limited/overloaded are never reverted).+// POLICY (configurable via crs.policy or $CRS_POLICY):+// conservative (default) — deprioritize on fresh high utilization, sessionWindow+// warnings, rate limits, and overload; FLOOR keeps minimum pool size; dedup by+// organizationUuid (same claude.ai quota pool).+// max-out — schedulable=TRUE for every account with a fresh OAuth token unless+// CRS would get a hard error (genuine rate-limit or 529 after stale-cache scrub).+// Util % and sessionWindow are telemetry only; dedup by login email.//// CONFIG (config.json "crs" block; every key overridable by env):-// enabled, baseUrl, adminUser, adminPasswordEnv, off5h, off7d, on5h, on7d,-// floor, freshMinutes. Admin password resolves from (1) $CRS_ADMIN_PASSWORD,-// (2) the configured env var, (3) credential-store `CRS-Admin-<adminUser>`.+// enabled, policy, baseUrl, adminUser, adminPasswordEnv, off5h, off7d, on5h, on7d,+// floor, freshMinutes. Per-account crsAccountName (or crs.nameByVaultKey) maps vault+// keys to CRS admin account names for token-feed + live quota lookup. Admin password+// resolves from (1) $CRS_ADMIN_PASSWORD, (2) the configured env var, (3) credential-store.//// CLI: (none)=one live tick · --dry-run=log decisions, no writes · --status=print// current schedulable + utilization table and exit · --once (alias for tick).@@ -39,10 +39,31 @@ import { execFileSync } from 'child_process';import { readFileSync, existsSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { homedir } from 'os';+import { homedir, platform } from 'os';+import {+ buildCrsNameMaps,+ crsBaseUrl,+ crsFileVaultPath,+ crsPolicy,+ loadRotationConfig,+ vaultLookupKeysForEmail,+} from './crs-pool-config.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || join(__dirname, '..', '..');+const CRED_STORE_CANDIDATES = [+ process.env.OPS_CREDENTIAL_STORE,+ join(homedir(), '.claude', 'plugins', 'cache', 'ops-marketplace', 'ops', 'current', 'lib', 'credential-store.sh'),+ join(homedir(), '.claude', 'plugins', 'marketplaces', 'ops-marketplace', 'claude-ops', 'lib', 'credential-store.sh'),+ join(PLUGIN_ROOT, 'lib', 'credential-store.sh'),+].filter(Boolean);+function credentialStorePath() {+ for (const p of CRED_STORE_CANDIDATES) {+ if (existsSync(p)) return p;+ }+ return CRED_STORE_CANDIDATES[CRED_STORE_CANDIDATES.length - 1];+}+const EXEC_QUIET = { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] };const DATA_DIR =process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');@@ -54,28 +75,12 @@ const ts = () => new Date().toISOString().slice(11, 19);const log = (m) => console.log(`${ts()} [crs-priority] ${m}`);// ── config ───────────────────────────────────────────────────────────────────-function loadConfig() {- const candidates = [- process.env.CRS_CONFIG,- join(DATA_DIR, 'account-rotation', 'config.json'),- join(homedir(), '.claude', 'plugins', 'data', 'ops', 'account-rotation', 'config.json'),- join(PLUGIN_ROOT, 'scripts', 'account-rotation', 'config.json'),- ].filter(Boolean);- for (const p of candidates) {- try {- if (existsSync(p)) return { crs: {}, ...JSON.parse(readFileSync(p, 'utf8')) };- } catch {}- }- return { crs: {} };-}-const cfg = loadConfig();+const cfg = loadRotationConfig();const C = cfg.crs || {};+const { vaultKeyByCrsName } = buildCrsNameMaps(cfg);const num = (v, d) => (v === undefined || v === null || v === '' || Number.isNaN(+v) ? d : +v);-// CRS_BASE is normally exported by the .sh wrapper after it probes the live host-// port (:3005 or :3000). config.json "crs".baseUrl overrides next; the literal is-// only a last resort and matches this fleet's published port (...:3005->3000).-const BASE = process.env.CRS_BASE || C.baseUrl || 'http://127.0.0.1:3005';+const BASE = crsBaseUrl(cfg);const ADMIN_USER = process.env.CRS_ADMIN_USER || C.adminUser || 'cradmin';const OFF_5H = num(process.env.CRS_OFF_5H ?? C.off5h, 90);const OFF_7D = num(process.env.CRS_OFF_7D ?? C.off7d, 95);@@ -83,20 +88,44 @@ const ON_5H = num(process.env.CRS_ON_5H ?? C.on5h, 70);const ON_7D = num(process.env.CRS_ON_7D ?? C.on7d, 85);const FLOOR = num(process.env.CRS_FLOOR ?? C.floor, 3);const FRESH_MIN = num(process.env.CRS_FRESH_MIN ?? C.freshMinutes, 15);+const CRS_POLICY = crsPolicy(cfg);+const TOKEN_MIN_FRESH_MS = num(process.env.CRS_TOKEN_MIN_FRESH_MS ?? C.tokenMinFreshMs, 5 * 60_000);+const STALE_RL_MAX_MINS = num(process.env.CRS_STALE_RL_MINUTES, 300);+const LIVE_USAGE_TTL_MS = num(process.env.CRS_LIVE_USAGE_TTL_MS, 90_000);+const IS_LINUX = platform() === 'linux';+const liveUsageCache = new Map();+const LINUX_CRED_PATH = crsFileVaultPath(cfg);+const CRS_CONTAINER = process.env.CRS_CONTAINER || C.containerName || 'crs-claude-relay-1';++function adminPasswordFromDocker() {+ if (!IS_LINUX) return null;+ try {+ const out = execFileSync(+ 'docker',+ ['inspect', CRS_CONTAINER, '--format', '{{range .Config.Env}}{{println .}}{{end}}'],+ EXEC_QUIET,+ );+ const m = out.match(/^ADMIN_PASSWORD=(.+)$/m);+ return m?.[1]?.trim() || null;+ } catch {+ return null;+ }+}function adminPassword() {if (process.env.CRS_ADMIN_PASSWORD) return process.env.CRS_ADMIN_PASSWORD;const envName = C.adminPasswordEnv || process.env.CRS_ADMIN_PASSWORD_ENV;if (envName && process.env[envName]) return process.env[envName];- // credential-store: service CRS-Admin-<adminUser>, account $USER+ const dockerPw = adminPasswordFromDocker();+ if (dockerPw) return dockerPw;try {- const cred = join(PLUGIN_ROOT, 'lib', 'credential-store.sh');+ const cred = credentialStorePath();const acct = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';- return execFileSync('bash', [cred, 'get', `CRS-Admin-${ADMIN_USER}`, acct], { encoding: 'utf8' }).trim();+ return execFileSync('bash', [cred, 'get', `CRS-Admin-${ADMIN_USER}`, acct], EXEC_QUIET).trim();} catch {}throw new Error(`CRS admin password unavailable — set $CRS_ADMIN_PASSWORD, or store it via:\n` +- ` bash "${join(PLUGIN_ROOT, 'lib', 'credential-store.sh')}" set CRS-Admin-${ADMIN_USER} "$USER" '<password>'`,+ ` bash "${credentialStorePath()}" set CRS-Admin-${ADMIN_USER} "$USER" '<password>'`,);}@@ -107,21 +136,41 @@ function adminPassword() {// to the cache/sessionWindowStatus when no token / 401 / timeout. Tokens live at// `Claude-Rotation-<email>` (rotator schema); CRS account → token by subscription email.const USAGE_TOKEN_SVC = process.env.CRS_USAGE_TOKEN_PREFIX || 'Claude-Rotation-';++function accountVaultKey(a) {+ return a.subscriptionInfo?.email || vaultKeyByCrsName[a.name] || null;+}++function vaultLookupKeys(email) {+ return vaultLookupKeysForEmail(email, cfg.accounts || []);+}++function readOauthTokenFromFileVault(email) {+ if (!email || !existsSync(LINUX_CRED_PATH)) return null;+ try {+ const store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));+ for (const key of vaultLookupKeys(email)) {+ const t = store[`${USAGE_TOKEN_SVC}${key}`]?.claudeAiOauth?.accessToken;+ if (t) return t;+ }+ } catch {}+ return null;+}+function readOauthToken(email) {if (!email) return null;+ const fileTok = readOauthTokenFromFileVault(email);+ if (fileTok) return fileTok;const acct = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';- // try credential-store first (cross-platform), then macOS security directly+ const cred = credentialStorePath();for (const get of [+ () => execFileSync('bash', [cred, 'get', `${USAGE_TOKEN_SVC}${email}`, acct], EXEC_QUIET),() =>execFileSync(- 'bash',- [join(PLUGIN_ROOT, 'lib', 'credential-store.sh'), 'get', `${USAGE_TOKEN_SVC}${email}`, acct],- { encoding: 'utf8' },+ 'security',+ ['find-generic-password', '-a', acct, '-s', `${USAGE_TOKEN_SVC}${email}`, '-w'],+ EXEC_QUIET,),- () =>- execFileSync('security', ['find-generic-password', '-a', acct, '-s', `${USAGE_TOKEN_SVC}${email}`, '-w'], {- encoding: 'utf8',- }),]) {try {const j = JSON.parse(get().trim());@@ -129,9 +178,62 @@ function readOauthToken(email) {if (t) return t;} catch {}}+ for (const key of vaultLookupKeys(email)) {+ if (key === email) continue;+ for (const get of [+ () => execFileSync('bash', [cred, 'get', `${USAGE_TOKEN_SVC}${key}`, acct], EXEC_QUIET),+ () =>+ execFileSync(+ 'security',+ ['find-generic-password', '-a', acct, '-s', `${USAGE_TOKEN_SVC}${key}`, '-w'],+ EXEC_QUIET,+ ),+ ]) {+ try {+ const j = JSON.parse(get().trim());+ const t = j?.claudeAiOauth?.accessToken;+ if (t) return t;+ } catch {}+ }+ }return null;}++function accountTokenFresh(a, now = Date.now()) {+ const tokenExp = Number(a.tokenExpiresAt || a.expiresAt || 0);+ return Number.isFinite(tokenExp) && tokenExp > now + TOKEN_MIN_FRESH_MS;+}++function rateLimitLooksStale(a, now = Date.now()) {+ if (a.status === 'error' && accountTokenFresh(a, now)) return true;++ const inspect = (st, resetAtFallback) => {+ if (!st?.isRateLimited) return false;+ const resetAt = st.resetAt || resetAtFallback;+ const resetMs = resetAt ? Date.parse(resetAt) : NaN;+ const mins = st.minutesRemaining ?? null;+ if (Number.isFinite(resetMs) && resetMs <= now) return true;+ if (mins === 0) return true;+ if (typeof mins === 'number' && mins > STALE_RL_MAX_MINS) return true;+ if (accountTokenFresh(a, now) && typeof mins === 'number' && mins > 60) return true;+ return false;+ };++ if (inspect(a.rateLimitStatus, a.rateLimitResetAt)) return true;+ if (inspect(a.opusRateLimitStatus, a.opusRateLimitStatus?.resetAt)) return true;++ const ov = a.overloadStatus;+ if (ov?.isOverloaded) {+ const resetMs = ov.resetAt ? Date.parse(ov.resetAt) : NaN;+ if (Number.isFinite(resetMs) && resetMs <= now) return true;+ if (accountTokenFresh(a, now)) return true;+ }+ return false;+}async function liveUsage(email) {+ if (!email) return null;+ const cached = liveUsageCache.get(email);+ if (cached && Date.now() - cached.at < LIVE_USAGE_TTL_MS) return cached.data;const token = readOauthToken(email);if (!token) return null;try {@@ -140,14 +242,32 @@ async function liveUsage(email) {headers: { Authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20' },signal: AbortSignal.timeout(5000),});- if (!r.ok) return null; // 401 (stale token) / 429 → fall back to cache + sessionWindowStatus+ if (!r.ok) return cached?.data ?? null;const d = await r.json();- return { u5: d?.five_hour?.utilization ?? null, u7: d?.seven_day?.utilization ?? null };+ const data = { u5: d?.five_hour?.utilization ?? null, u7: d?.seven_day?.utilization ?? null };+ liveUsageCache.set(email, { at: Date.now(), data });+ return data;} catch {- return null;+ return cached?.data ?? null;}}+function genuineRateLimit(a, now = Date.now()) {+ const flagged = !!a.rateLimitStatus?.isRateLimited || !!a.opusRateLimitStatus?.isRateLimited;+ return flagged && !rateLimitLooksStale(a, now);+}++function genuineOverload(a, now = Date.now()) {+ if (!a.overloadStatus?.isOverloaded) return false;+ const resetMs = a.overloadStatus.resetAt ? Date.parse(a.overloadStatus.resetAt) : NaN;+ if (Number.isFinite(resetMs) && resetMs <= now) return false;+ if (accountTokenFresh(a, now)) {+ const mins = a.overloadStatus.minutesRemaining;+ if (typeof mins === 'number' && mins > STALE_RL_MAX_MINS) return false;+ }+ return true;+}+// ── http ─────────────────────────────────────────────────────────────────────async function jfetch(path, opts = {}) {const r = await fetch(`${BASE}${path}`, opts);@@ -178,30 +298,105 @@ async function getAccounts(auth) {return list.filter((a) => a.platform === 'claude' && a.isActive !== false);}+async function clearStaleCooldowns(auth, accts) {+ const now = Date.now();+ let cleared = 0;+ for (const a of accts) {+ if (!rateLimitLooksStale(a, now)) continue;+ const mins = a.rateLimitStatus?.minutesRemaining ?? '?';+ if (DRY) {+ log(`[dry] clear stale RL ${a.name} (mins=${mins})`);+ cleared++;+ continue;+ }+ const res = await jfetch(`/admin/claude-accounts/${a.id}/reset-status`, { method: 'POST', headers: auth });+ if (res.status >= 200 && res.status < 300) {+ cleared++;+ log(`${a.name}: cleared stale RL/error cache (was mins=${mins})`);+ }+ }+ return cleared;+}++async function recoverSchedulableAfterClear(auth, accts) {+ const now = Date.now();+ let enabled = 0;+ for (const a of accts) {+ if (a.schedulable !== false) continue;+ if (a.rateLimitStatus?.isRateLimited || a.opusRateLimitStatus?.isRateLimited) continue;+ if (a.overloadStatus?.isOverloaded) continue;+ if (!accountTokenFresh(a, now)) continue;+ if (DRY) {+ log(`[dry] re-enable ${a.name} after stale clear`);+ enabled++;+ continue;+ }+ const put = await jfetch(`/admin/claude-accounts/${a.id}/toggle-schedulable`, {+ method: 'PUT',+ headers: auth,+ body: JSON.stringify({ schedulable: true }),+ });+ if (put.status >= 200 && put.status < 300) {+ enabled++;+ log(`${a.name}: re-enabled schedulable after stale-cache recovery`);+ }+ }+ return enabled;+}+// ── policy ───────────────────────────────────────────────────────────────────const WARN_STATUSES = new Set(['allowed_warning', 'warning', 'blocked', 'exceeded', 'limited', 'stopped']);-function decide(accts) {- const nowMs = Date.now();+function decideMaxOut(accts, nowMs) {+ return accts.map((a) => {+ const cu = a.claudeUsage || {};+ const lu = a._liveUsage;+ const u5 = lu?.u5 ?? cu.fiveHour?.utilization;+ const u7 = lu?.u7 ?? cu.sevenDay?.utilization;+ const sw = a.sessionWindow?.sessionWindowStatus || null;+ const cur = a.schedulable !== false;+ const tokenExpiresAt = Number(a.tokenExpiresAt || a.expiresAt || 0);+ const staleToken =+ !Number.isFinite(tokenExpiresAt) || tokenExpiresAt <= 0 || tokenExpiresAt <= nowMs + TOKEN_MIN_FRESH_MS;+ const rl = genuineRateLimit(a, nowMs);+ const overloaded = genuineOverload(a, nowMs);++ let desired = true;+ let reason = `max-out (5h=${u5 ?? '?'} 7d=${u7 ?? '?'} sw=${sw ?? 'none'})`;+ if (staleToken) {+ desired = false;+ reason = tokenExpiresAt ? `stale-token ${new Date(tokenExpiresAt).toISOString()}` : 'stale-token missing-expiry';+ } else if (rl) {+ desired = false;+ reason = 'rate-limited (live)';+ } else if (overloaded) {+ desired = false;+ reason = 'overloaded(529 live)';+ }+ return { a, cur, desired, reason, soft: false, sw, u5: u5 ?? '?', rl, overloaded };+ });+}++function decideConservative(accts, nowMs) {const decisions = accts.map((a) => {const cu = a.claudeUsage || {};- const lu = a._liveUsage; // authoritative direct-from-Anthropic /oauth/usage, or null+ const lu = a._liveUsage;const updMs = cu.updatedAt ? Date.parse(cu.updatedAt) : NaN;const fresh = !!lu || (Number.isFinite(updMs) && (nowMs - updMs) / 60000 < FRESH_MIN);const u5 = lu?.u5 ?? cu.fiveHour?.utilization;const u7 = lu?.u7 ?? cu.sevenDay?.utilization;- const u7o = cu.sevenDayOpus?.utilization; // oauth/usage doesn't split opus — keep cache- const rl = !!a.rateLimitStatus?.isRateLimited || !!a.opusRateLimitStatus?.isRateLimited;- const overloaded = !!a.overloadStatus?.isOverloaded;+ const u7o = cu.sevenDayOpus?.utilization;const sw = a.sessionWindow?.sessionWindowStatus || null;const cur = a.schedulable !== false;+ const rl = genuineRateLimit(a, nowMs);+ const overloaded = genuineOverload(a, nowMs);const utilBreach = fresh && ((u5 ?? 0) >= OFF_5H || (u7 ?? 0) >= OFF_7D || (u7o ?? 0) >= OFF_7D);const utilClear = !fresh || ((u5 ?? 0) < ON_5H && (u7 ?? 0) < ON_7D && (u7o ?? 0) < ON_7D);- let desired = cur,- reason = 'hold',- soft = false;+ let desired = cur;+ let reason = 'hold';+ let soft = false;if (rl) {desired = false;reason = 'rate-limited';@@ -223,7 +418,6 @@ function decide(accts) {return { a, cur, desired, reason, soft, sw, u5: u5 ?? '?', rl, overloaded };});- // FLOOR: never starve the pool via SOFT deprioritizationslet usable = decisions.filter((d) => d.desired && !d.rl && !d.overloaded).length;if (usable < FLOOR) {const unum = (d) => (typeof d.u5 === 'number' ? d.u5 : 50);@@ -241,29 +435,51 @@ function decide(accts) {log(`WARNING: only ${final} usable account(s) (< floor ${FLOOR}) — pool is capacity-constrained`);}- // DEDUP — accounts sharing an organizationUuid are the SAME claude.ai quota pool- // (e.g. two CRS pool entries for one account). Leaving both schedulable makes CRS- // double-load that single account → it saturates twice as fast. Keep only ONE- // schedulable per uuid (healthiest: sw=allowed, then lowest known util); force the- // rest off. Team-vs-personal seats have DIFFERENT uuids, so they are NOT deduped.const byUuid = {};for (const d of decisions) {const uuid = d.a.subscriptionInfo?.organizationUuid;if (!uuid || !d.desired) continue;(byUuid[uuid] ||= []).push(d);}- for (const [uuid, group] of Object.entries(byUuid)) {+ for (const group of Object.values(byUuid)) {if (group.length < 2) continue;const unum = (d) => (typeof d.u5 === 'number' ? d.u5 : 50);group.sort((x, y) => (x.sw === 'allowed' ? 0 : 1) - (y.sw === 'allowed' ? 0 : 1) || unum(x) - unum(y));for (const d of group.slice(1)) {d.desired = false;- d.reason = `dedup: same org ${uuid.slice(0, 8)} as ${group[0].a.name} (one quota pool)`;+ d.reason = `dedup: same org ${group[0].a.subscriptionInfo.organizationUuid.slice(0, 8)} as ${group[0].a.name}`;}}return decisions;}+function dedupByLogin(decisions) {+ const byLogin = {};+ for (const d of decisions) {+ const login = accountVaultKey(d.a);+ if (!login || !d.desired) continue;+ (byLogin[login] ||= []).push(d);+ }+ for (const [login, group] of Object.entries(byLogin)) {+ if (group.length < 2) continue;+ const unum = (d) => (typeof d.u5 === 'number' ? d.u5 : 100);+ group.sort((x, y) => unum(x) - unum(y));+ for (const d of group.slice(1)) {+ d.desired = false;+ d.reason = `dedup: same login ${login} as ${group[0].a.name}`;+ }+ }+ return decisions;+}++function decide(accts) {+ const nowMs = Date.now();+ if (CRS_POLICY === 'max-out' || CRS_POLICY === 'maxout') {+ return dedupByLogin(decideMaxOut(accts, nowMs));+ }+ return decideConservative(accts, nowMs);+}+// ── main ─────────────────────────────────────────────────────────────────────async function main() {if (C.enabled === false && !STATUS && !DRY) {@@ -271,16 +487,26 @@ async function main() {return;}const auth = await login();- const accts = await getAccounts(auth);+ let accts = await getAccounts(auth);if (!accts.length) {log('no active claude accounts');return;}+ const cleared = await clearStaleCooldowns(auth, accts);+ if (cleared) {+ accts = await getAccounts(auth);+ log(`stale-cooldown: cleared ${cleared} account(s), reloaded pool`);+ const reenabled = await recoverSchedulableAfterClear(auth, accts);+ if (reenabled) {+ accts = await getAccounts(auth);+ log(`stale-cooldown: re-enabled ${reenabled} schedulable account(s)`);+ }+ }// Authoritative quota: query Anthropic /oauth/usage directly per account (parallel,// read-only). Falls back to CRS cache + sessionWindowStatus when a token is absent/stale.await Promise.all(accts.map(async (a) => {- a._liveUsage = await liveUsage(a.subscriptionInfo?.email);+ a._liveUsage = await liveUsage(accountVaultKey(a));}),);const liveN = accts.filter((a) => a._liveUsage).length;diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.sh b/claude-ops/scripts/account-rotation/crs-priority-daemon.shindex 6cd38160..e92095de 100755--- a/claude-ops/scripts/account-rotation/crs-priority-daemon.sh+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.sh@@ -1,58 +1,38 @@-#!/usr/bin/env bash+#!/bin/bash# crs-priority-daemon.sh — single-flight wrapper for crs-priority-daemon.mjs.-# Invoked once per tick by the launchd/systemd timer (StartInterval). Holds an-# atomic mkdir lock so ticks never stack (macOS has no flock), skips silently-# when CRS is down, rotates its own log, then runs ONE node tick.+# Invoked once-per-tick by launchd/systemd (StartInterval/OnCalendar).set -uo pipefail-SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$SELF_DIR/../.." && pwd)}"-DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"-LOG_DIR="$DATA_DIR/logs"-LOG="$LOG_DIR/crs-priority.log"-NODE="${CRS_NODE_BIN:-$(command -v node || echo /opt/homebrew/bin/node)}"-# CRS's container port (:3000) is published on the host at either :3000 or :3005-# depending on the deploy (this fleet maps ...:3005->3000). Honor an explicit-# CRS_BASE; otherwise probe the known candidates and pick the first that answers-# /health, so a host port-mapping change can't silently freeze the daemon (it-# used to default to :3000, get 000 against a :3005-mapped relay, and exit 0-# every tick — priority scheduling dead until someone noticed).-BASE="${CRS_BASE:-}"+source "$HOME/.claude/scripts/lib/once.sh" 2>/dev/null || true+type claude_once >/dev/null 2>&1 && { claude_once crs-priority-daemon 30 || exit 0; }-mkdir -p "$LOG_DIR"+DIR="$HOME/.claude/scripts/account-rotation"+LOG="$DIR/crs-priority-daemon.log"+NODE="$(command -v node || echo /opt/homebrew/bin/node)"+CRS_CONTAINER="${CRS_CONTAINER:-crs-claude-relay-1}"-# Atomic single-flight lock (auto-released on exit). Stale locks >10m are reclaimed.-LOCK="${TMPDIR:-/tmp}/crs-priority-daemon.lock"-if ! mkdir "$LOCK" 2>/dev/null; then- if [ -n "$(find "$LOCK" -maxdepth 0 -mmin +10 2>/dev/null)" ]; then- rmdir "$LOCK" 2>/dev/null && mkdir "$LOCK" 2>/dev/null || exit 0- else- exit 0 # another tick is running+export CLAUDE_PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/ops-marketplace/claude-ops}"+CRED_STORE="$CLAUDE_PLUGIN_ROOT/lib/credential-store.sh"+KEYCHAIN_ACCOUNT="${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-$USER}"++if [ -z "${CRS_ADMIN_PASSWORD:-}" ]; then+ if [ -f "$CRED_STORE" ]; then+ CRS_ADMIN_PASSWORD="$(bash "$CRED_STORE" get "CRS-Admin-cradmin" "$KEYCHAIN_ACCOUNT" 2>/dev/null || true)"+ fi+ if [ -z "${CRS_ADMIN_PASSWORD:-}" ] && command -v security >/dev/null 2>&1; then+ CRS_ADMIN_PASSWORD="$(security find-generic-password -a "$USER" -s CRS-Admin-cradmin -w 2>/dev/null || true)"fi+ if [ -z "${CRS_ADMIN_PASSWORD:-}" ] && command -v docker >/dev/null 2>&1; then+ CRS_ADMIN_PASSWORD="$(docker inspect "$CRS_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | sed -n 's/^ADMIN_PASSWORD=//p' | head -1 || true)"+ fi+ export CRS_ADMIN_PASSWORDfi-trap 'rmdir "$LOCK" 2>/dev/null' EXIT-# Skip silently if CRS isn't reachable (don't spam the log while the relay is down).-# Auto-detect the host port unless CRS_BASE was set explicitly.-if [ -n "$BASE" ]; then- curl -sf -o /dev/null --max-time 5 "$BASE/health" || exit 0-else- for cand in http://127.0.0.1:3005 http://127.0.0.1:3000; do- if curl -sf -o /dev/null --max-time 5 "$cand/health"; then BASE="$cand"; break; fi- done- [ -n "$BASE" ] || exit 0 # relay unreachable on every candidate-fi-export CRS_BASE="$BASE" # hand the resolved base to the node tick+curl -sf -o /dev/null --max-time 5 http://127.0.0.1:3005/health || exit 0-# Rotate log past ~2MB.-if [ -f "$LOG" ] && [ "$(wc -c < "$LOG" 2>/dev/null || echo 0)" -gt 2097152 ]; then- mv "$LOG" "$LOG.1"+if [ -f "$LOG" ]; then+ LOGSIZE="$(stat -c%s "$LOG" 2>/dev/null || stat -f%z "$LOG" 2>/dev/null || echo 0)"+ [ "$LOGSIZE" -gt 2097152 ] && mv "$LOG" "$LOG.1"fi-# A transient node failure (e.g. CRS login timeout under a 529 storm) is logged-# but must NOT surface as a launchd job failure — the next tick recovers. Always-# exit 0 so launchctl status stays clean; real errors are in the log.-CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT" CLAUDE_PLUGIN_DATA_DIR="$DATA_DIR" \- "$NODE" "$SELF_DIR/crs-priority-daemon.mjs" "$@" >> "$LOG" 2>&1 || \- echo "$(date -u +%H:%M:%S) [crs-priority] tick failed (transient — see above); recovering next tick" >> "$LOG"-exit 0+"$NODE" "$DIR/crs-priority-daemon.mjs" >> "$LOG" 2>&1diff --git a/claude-ops/scripts/account-rotation/crs-token-feed.mjs b/claude-ops/scripts/account-rotation/crs-token-feed.mjsindex 52ffd8f5..dfea8764 100644--- a/claude-ops/scripts/account-rotation/crs-token-feed.mjs+++ b/claude-ops/scripts/account-rotation/crs-token-feed.mjs@@ -1,24 +1,13 @@#!/usr/bin/env node/**- * crs-token-feed.mjs — "rotator feeds CRS" (Linux/EC2).+ * crs-token-feed.mjs — propagate rotation vault tokens into a local CRS pool.*- * The hourly claude-token-refresh.service (refresh-tokens.mjs) is a NO-OP on- * Linux (it reads the macOS `security` keychain, which doesn't exist here), and- * nothing ever propagated fresh vault tokens into the local claude-relay-service- * (CRS) pool — so CRS accounts silently rotted to status=error as their access- * tokens expired (CRS stores no refresh tokens: hasRefresh=false on every acct).+ * On headless Linux hosts the macOS keychain refresh path is unavailable; this+ * feeder reads ~/.claude/.credentials.json (or crs.fileVaultPath), optionally+ * refreshes expiring tokens, and PUTs claudeAiOauth into mapped CRS accounts.*- * This feeder closes both gaps, contention-tolerantly:- * 1. Read each account's token from the Linux file vault (~/.claude/.credentials.json).- * 2. If expiring within BUFFER, best-effort OAuth refresh; persist the rotated- * refresh_token back to the file vault atomically. On HTTP 400 (refresh- * token already rotated by the Mac/daemon — cross-machine contention) we- * SKIP quietly — no browser re-auth (doomed headless) — and just propagate- * whatever fresh token the vault currently holds.- * 3. PUT the fresh claudeAiOauth into the mapped CRS account + reset-status.- *- * Single refresher-of-record stays the existing pipeline; this is best-effort- * top-up + the missing propagation. Runs via crs-token-feed.timer.+ * Map each rotator account to a CRS admin account name via crsAccountName in+ * config.json (or crs.nameByVaultKey). Runs via crs-token-feed.timer when installed.** node crs-token-feed.mjs # refresh-if-needed + propagate all* node crs-token-feed.mjs --dry-run # report only@@ -27,34 +16,24 @@import { readFileSync, writeFileSync, renameSync, appendFileSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { execSync } from 'child_process';+import { execSync, spawnSync } from 'child_process';import { foreignActiveKeys } from './account-leases.mjs';+import { assertCrsInvariant } from './route-state.mjs';+import { acquireRefreshLock } from './crs-refresh-lock.mjs';+import {+ buildCrsNameMaps,+ crsBaseUrl,+ crsFileVaultPath,+ loadRotationConfig,+ resolveConfigPath,+} from './crs-pool-config.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = join(__dirname, 'config.json');const LOG_PATH = join(__dirname, 'rotation.log');-const FILE_VAULT = join(process.env.HOME || '', '.claude', '.credentials.json');-const CRS_BASE = process.env.CRS_BASE || 'http://127.0.0.1:3005';-const CRS_CONTAINER = process.env.CRS_CONTAINER || 'crs-claude-relay-1';const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';const TOKEN_ENDPOINT = 'https://platform.claude.com/v1/oauth/token';const BUFFER_MS = 2 * 3_600_000; // refresh if expiring within 2hconst INTER_DELAY_MS = 1_500;-const <USER>_EMAIL = process.env.CLAUDE_ROTATOR_<USER>_EMAIL || ['<OWNER_NAME>', 'gmail.com'].join('@');--// vault key (label || email) -> CRS account name-const CRS_NAME_BY_KEY = {- 'chairman@<OWNER_BRAND>.org': 'pool-chairman',- '[email protected]': 'canary-support',- <OWNER_BRAND>: 'pool-<OWNER_BRAND>-personal',- '<OWNER_BRAND>-team': 'pool-<OWNER_BRAND>-team',- '<WORK_EMAIL>': 'pool-<OWNER_BRAND>',- [<USER>_EMAIL]: 'pool-<USER>',- '[email protected]': 'pool-aurora',- '<WORK_EMAIL>': 'pool-foundation',- 'sponsors@<OWNER_BRAND>.org': 'canary-sponsors',- '[email protected]': 'canary-lifecycle',-};const args = process.argv.slice(2);const DRY = args.includes('--dry-run');@@ -70,20 +49,25 @@ function log(msg) {function accountKey(a) {return a.label || a.email;}-function fvLoad() {- try {- return JSON.parse(readFileSync(FILE_VAULT, 'utf8'));- } catch {- return {};- }-}-function fvSave(v) {- const t = `${FILE_VAULT}.tmp.${process.pid}`;- writeFileSync(t, JSON.stringify(v, null, 2));- renameSync(t, FILE_VAULT);-}const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+function makeVaultOps(fileVaultPath) {+ return {+ load() {+ try {+ return JSON.parse(readFileSync(fileVaultPath, 'utf8'));+ } catch {+ return {};+ }+ },+ save(v) {+ const t = `${fileVaultPath}.tmp.${Date.now()}`;+ writeFileSync(t, JSON.stringify(v, null, 2));+ renameSync(t, fileVaultPath);+ },+ };+}+async function oauthRefresh(refreshToken) {try {const res = await fetch(TOKEN_ENDPOINT, {@@ -110,11 +94,11 @@ async function oauthRefresh(refreshToken) {}}-async function crsLogin() {+async function crsLogin(crsBase, crsContainer, adminUser = 'cradmin') {let pw = '';try {pw = execSync(- `docker inspect ${CRS_CONTAINER} --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^ADMIN_PASSWORD=//p'`,+ `docker inspect ${crsContainer} --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^ADMIN_PASSWORD=//p'`,{ timeout: 8000 },).toString()@@ -122,10 +106,10 @@ async function crsLogin() {} catch {}if (!pw) return null;try {- const r = await fetch(`${CRS_BASE}/web/auth/login`, {+ const r = await fetch(`${crsBase}/web/auth/login`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ username: 'cradmin', password: pw }),+ body: JSON.stringify({ username: adminUser, password: pw }),}).then((x) => x.json());const tok = r.token || r.data?.token;return tok ? { 'Content-Type': 'application/json', Authorization: `Bearer ${tok}` } : null;@@ -135,13 +119,25 @@ async function crsLogin() {}async function main() {- const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));- const H = await crsLogin();+ assertCrsInvariant(process.env, 'crs-token-feed:main');+ const configPath = resolveConfigPath();+ if (!configPath) {+ log('no rotation config found — set CRS_CONFIG or install account-rotation config.json');+ process.exit(1);+ }+ const config = loadRotationConfig();+ const { nameByVaultKey } = buildCrsNameMaps(config);+ const fileVault = crsFileVaultPath(config);+ const crsBase = crsBaseUrl(config);+ const crsContainer = process.env.CRS_CONTAINER || config.crs?.containerName || 'crs-claude-relay-1';+ const adminUser = process.env.CRS_ADMIN_USER || config.crs?.adminUser || 'cradmin';+ const vault = makeVaultOps(fileVault);+ const H = await crsLogin(crsBase, crsContainer, adminUser);if (!H) {log('CRS login failed (relay down or no admin pw) — aborting');process.exit(1);}- const acctsResp = await fetch(`${CRS_BASE}/admin/claude-accounts`, { headers: H }).then((r) => r.json());+ const acctsResp = await fetch(`${crsBase}/admin/claude-accounts`, { headers: H }).then((r) => r.json());const byName = Object.fromEntries((acctsResp.data || acctsResp.accounts || acctsResp).map((a) => [a.name, a]));const now = Date.now();// Contention guard: never refresh an account the OTHER host holds the lease on@@ -157,8 +153,8 @@ async function main() {if (STATUS) {for (const a of config.accounts) {const key = accountKey(a);- const crsName = CRS_NAME_BY_KEY[key];- const e = fvLoad()[`Claude-Rotation-${key}`]?.claudeAiOauth;+ const crsName = nameByVaultKey[key];+ const e = vault.load()[`Claude-Rotation-${key}`]?.claudeAiOauth;const min = e?.expiresAt ? Math.floor((e.expiresAt - now) / 60000) : 'n/a';const crs = byName[crsName];console.log(@@ -175,15 +171,15 @@ async function main() {for (let i = 0; i < config.accounts.length; i++) {const a = config.accounts[i];const key = accountKey(a);- const crsName = CRS_NAME_BY_KEY[key];+ const crsName = nameByVaultKey[key];if (!crsName || !byName[crsName]) {missing++;continue;}const crs = byName[crsName];- const vault = fvLoad();- const entry = vault[`Claude-Rotation-${key}`]?.claudeAiOauth;+ const vaultData = vault.load();+ const entry = vaultData[`Claude-Rotation-${key}`]?.claudeAiOauth;if (!entry?.accessToken) {log(`${key}: no vault token — skip`);skipped++;@@ -196,20 +192,29 @@ async function main() {log(`${key}: expiring but foreign-leased — refresh deferred to owner host, propagating current token`);} else if (expiring && oauth.refreshToken && !DRY) {if (i > 0) await sleep(INTER_DELAY_MS);- const r = await oauthRefresh(oauth.refreshToken);- if (r.ok) {- oauth = { ...oauth, ...r.oauth, scopes: oauth.scopes || [] };- vault[`Claude-Rotation-${key}`] = {- claudeAiOauth: oauth,- mcpOAuth: vault[`Claude-Rotation-${key}`]?.mcpOAuth || {},- };- fvSave(vault);- refreshed++;- log(`${key}: refreshed (min_left=${Math.floor((oauth.expiresAt - now) / 60000)})`);- } else if (r.status === 400) {- log(`${key}: refresh 400 (rotated elsewhere) — propagating existing vault token`);+ const release = acquireRefreshLock(key);+ if (!release) {+ log(`${key}: refresh lock held elsewhere — propagate-only`);} else {- log(`${key}: refresh failed (${r.error}) — propagating existing vault token`);+ try {+ const r = await oauthRefresh(oauth.refreshToken);+ if (r.ok) {+ oauth = { ...oauth, ...r.oauth, scopes: oauth.scopes || [] };+ vaultData[`Claude-Rotation-${key}`] = {+ claudeAiOauth: oauth,+ mcpOAuth: vaultData[`Claude-Rotation-${key}`]?.mcpOAuth || {},+ };+ vault.save(vaultData);+ refreshed++;+ log(`${key}: refreshed (min_left=${Math.floor((oauth.expiresAt - now) / 60000)})`);+ } else if (r.status === 400) {+ log(`${key}: refresh 400 (rotated elsewhere) — propagating existing vault token`);+ } else {+ log(`${key}: refresh failed (${r.error}) — propagating existing vault token`);+ }+ } finally {+ release();+ }}}@@ -224,16 +229,15 @@ async function main() {continue;}try {- const put = await fetch(`${CRS_BASE}/admin/claude-accounts/${crs.id}`, {+ const put = await fetch(`${crsBase}/admin/claude-accounts/${crs.id}`, {method: 'PUT',headers: H,- body: JSON.stringify({ claudeAiOauth: oauth, schedulable: true }),+ body: JSON.stringify({ claudeAiOauth: oauth }),});if (put.ok) {- if (crs.status === 'error')- await fetch(`${CRS_BASE}/admin/claude-accounts/${crs.id}/reset-status`, { method: 'POST', headers: H }).catch(- () => {},- );+ await fetch(`${crsBase}/admin/claude-accounts/${crs.id}/reset-status`, { method: 'POST', headers: H }).catch(+ () => {},+ );propagated++;} else {log(`${key}: CRS PUT ${put.status}`);@@ -243,6 +247,15 @@ async function main() {}}log(`feed complete: ${refreshed} refreshed, ${propagated} propagated, ${skipped} skipped, ${missing} unmapped`);+ if (!DRY && propagated > 0 && process.env.CRS_FEED_SKIP_PRIORITY !== '1') {+ const pr = spawnSync(process.execPath, [join(__dirname, 'crs-priority-daemon.mjs')], {+ env: { ...process.env, CRS_ADMIN_PASSWORD: process.env.CRS_ADMIN_PASSWORD || '' },+ timeout: 120_000,+ encoding: 'utf8',+ });+ if (pr.status === 0) log('priority tick after feed: ok');+ else log(`priority tick after feed: exit=${pr.status} ${(pr.stderr || pr.stdout || '').slice(0, 200)}`);+ }}main().catch((e) => {log(`fatal: ${e.message}`);diff --git a/claude-ops/scripts/install-crs-fra-tunnel.sh b/claude-ops/scripts/install-crs-fra-tunnel.shindex 52fd26e0..33ec5bfb 100755--- a/claude-ops/scripts/install-crs-fra-tunnel.sh+++ b/claude-ops/scripts/install-crs-fra-tunnel.sh@@ -1,10 +1,11 @@#!/usr/bin/env bash-# Install the macOS launchd tunnel that forwards local CRS traffic to FRA.+# Install a macOS launchd SSH tunnel: local CRS port → remote host running CRS.+# Set CRS_TUNNEL_SSH_HOST (or legacy CRS_FRA_SSH_HOST) to your SSH target, e.g. [email protected]set -euo pipefailif [[ "$(uname -s)" != "Darwin" ]]; then- echo "skip: CRS FRA tunnel is macOS-only (launchd)" >&2+ echo "skip: CRS remote tunnel is macOS-only (launchd)" >&2exit 0fi@@ -13,9 +14,14 @@ LABEL="com.claude-ops.crs-fra-tunnel"TPL="$PLUGIN_ROOT/templates/${LABEL}.plist"DEST="$HOME/Library/LaunchAgents/${LABEL}.plist"LOG_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"-SSH_HOST="${CRS_FRA_SSH_HOST:-fra-direct}"-LOCAL_PORT="${CRS_FRA_LOCAL_PORT:-3000}"-REMOTE_PORT="${CRS_FRA_REMOTE_PORT:-3005}"+SSH_HOST="${CRS_TUNNEL_SSH_HOST:-${CRS_FRA_SSH_HOST:-}}"+LOCAL_PORT="${CRS_TUNNEL_LOCAL_PORT:-${CRS_FRA_LOCAL_PORT:-3005}}"+REMOTE_PORT="${CRS_TUNNEL_REMOTE_PORT:-${CRS_FRA_REMOTE_PORT:-3005}}"++if [[ -z "$SSH_HOST" ]]; then+ echo "error: set CRS_TUNNEL_SSH_HOST (SSH target for remote CRS, e.g. user@host)" >&2+ exit 1+fifor f in "$TPL"; do[[ -f "$f" ]] || { echo "error: missing template $f" >&2; exit 1; }@@ -32,4 +38,4 @@ sed \launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || truelaunchctl bootstrap "gui/$(id -u)" "$DEST"-echo "✓ installed $LABEL"+echo "✓ installed $LABEL → 127.0.0.1:$LOCAL_PORT via $SSH_HOST:$REMOTE_PORT"diff --git a/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist b/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plistindex 750d8ddc..88accbef 100644--- a/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist+++ b/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist@@ -32,9 +32,9 @@<true/><key>StandardOutPath</key>- <string>__LOG_DIR__/crs-fra-tunnel.out.log</string>+ <string>__LOG_DIR__/crs-remote-tunnel.out.log</string><key>StandardErrorPath</key>- <string>__LOG_DIR__/crs-fra-tunnel.err.log</string>+ <string>__LOG_DIR__/crs-remote-tunnel.err.log</string></dict></plist>