Skip to content

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.

feat(rotate): CRS relay-pool priority daemon (auto-prioritization, dedup, quota-aware) (#585)

Aurora Capital5b23b57da1fe
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 0d3cdf4a..1b8c0aeb 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [2.32.0] - 2026-06-14
+
+### Added
+CRS relay-pool auto-prioritization: a new `crs-priority` daemon (opt-in, off by default) that manages per-account `schedulable` flags on a claude-relay-service pool from live signals (`sessionWindowStatus` + rate-limit + overload, with `claudeUsage` utilization as a fresh-only secondary), so the relay avoids near-maxed accounts and re-enables them on recovery — the relay-pool analogue of the keychain rotator. Hysteresis bands prevent flapping; a floor guarantees the pool never starves itself; stale/absent usage never drives a re-enable. Ships `scripts/account-rotation/crs-priority-daemon.{mjs,sh}`, a `templates/com.claude-ops.crs-priority.plist` launchd template + `scripts/install-crs-priority-agent.sh` installer (120s cadence, single-flight locked), a `crs` config block, and wires `/ops:rotate crs|crs-tick` (status/manual tick) + an `/ops:rotate-setup --crs` install step. Admin password resolves from `$CRS_ADMIN_PASSWORD` or the credential store (`CRS-Admin-<adminUser>`), never config.
+
+
## [2.31.0] - 2026-06-14
### Changed
diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.json
index bf994d3a..92ff251b 100644
--- a/claude-ops/scripts/account-rotation/config.example.json
+++ b/claude-ops/scripts/account-rotation/config.example.json
@@ -26,5 +26,19 @@
"maxHoursPerAccount": 4,
"autoRotate": true,
"refreshSession": false,
- "notifyOnRotation": true
+ "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>'`.",
+ "enabled": false,
+ "baseUrl": "http://127.0.0.1:3000",
+ "adminUser": "cradmin",
+ "adminPasswordEnv": "CRS_ADMIN_PASSWORD",
+ "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)."
+ }
}
diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs
new file mode 100755
index 00000000..dd9bfaf5
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs
@@ -0,0 +1,264 @@
+#!/usr/bin/env node
+// crs-priority-daemon.mjs — utilization-driven account prioritization for a
+// claude-relay-service (CRS) pool.
+//
+// CRS load-balances Claude requests across many claude.ai accounts at once. Each
+// account carries a `schedulable` flag; CRS only routes to schedulable accounts.
+// This daemon flips that flag from LIVE signals so the pool AVOIDS near-maxed
+// accounts (cutting 429/529s) and RE-ENABLES them once their windows recover —
+// the relay-pool analogue of the keychain rotator's "rotate to the coolest
+// account". One tick per invocation; a launchd/systemd timer drives the cadence
+// (see scripts/install-crs-priority-agent.sh). The wrapper crs-priority-daemon.sh
+// holds the single-flight lock.
+//
+// SIGNALS (real-time first — claudeUsage.* is often null/stale for pool accounts
+// and must NEVER drive a re-enable on its own):
+// rateLimitStatus.isRateLimited / opusRateLimitStatus.isRateLimited (hard cap hit)
+// overloadStatus.isOverloaded (upstream 529)
+// 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).
+//
+// 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>`.
+//
+// CLI: (none)=one live tick · --dry-run=log decisions, no writes · --status=print
+// current schedulable + utilization table and exit · --once (alias for tick).
+
+import { execFileSync } from 'child_process';
+import { readFileSync, existsSync } from 'fs';
+import { dirname, join } 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');
+
+const args = new Set(process.argv.slice(2));
+const DRY = args.has('--dry-run') || process.env.CRS_DRY === '1';
+const STATUS = args.has('--status');
+
+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 C = cfg.crs || {};
+const num = (v, d) => (v === undefined || v === null || v === '' || Number.isNaN(+v) ? d : +v);
+
+const BASE = process.env.CRS_BASE || C.baseUrl || 'http://127.0.0.1:3000';
+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);
+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);
+
+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
+ try {
+ const cred = join(PLUGIN_ROOT, 'lib', 'credential-store.sh');
+ 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();
+ } 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>'`
+ );
+}
+
+// ── authoritative per-account quota (api.anthropic.com/api/oauth/usage) ────────
+// CRS's cached claudeUsage is often null/stale, so for accurate prioritization we
+// read each account's OAuth token from the credential store and query Anthropic's
+// usage endpoint directly (read-only GET — does NOT rotate the token). Falls back
+// 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 readOauthToken(email) {
+ if (!email) return null;
+ const acct = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';
+ // try credential-store first (cross-platform), then macOS security directly
+ for (const get of [
+ () => execFileSync('bash', [join(PLUGIN_ROOT, 'lib', 'credential-store.sh'), 'get', `${USAGE_TOKEN_SVC}${email}`, acct], { encoding: 'utf8' }),
+ () => execFileSync('security', ['find-generic-password', '-a', acct, '-s', `${USAGE_TOKEN_SVC}${email}`, '-w'], { encoding: 'utf8' }),
+ ]) {
+ try { const j = JSON.parse(get().trim()); const t = j?.claudeAiOauth?.accessToken; if (t) return t; } catch {}
+ }
+ return null;
+}
+async function liveUsage(email) {
+ const token = readOauthToken(email);
+ if (!token) return null;
+ try {
+ const r = await fetch('https://api.anthropic.com/api/oauth/usage', {
+ method: 'GET',
+ 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
+ const d = await r.json();
+ return { u5: d?.five_hour?.utilization ?? null, u7: d?.seven_day?.utilization ?? null };
+ } catch { return null; }
+}
+
+// ── http ─────────────────────────────────────────────────────────────────────
+async function jfetch(path, opts = {}) {
+ const r = await fetch(`${BASE}${path}`, opts);
+ const txt = await r.text();
+ let body; try { body = JSON.parse(txt); } catch { body = txt; }
+ return { status: r.status, body };
+}
+
+async function login() {
+ const r = await jfetch('/web/auth/login', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username: ADMIN_USER, password: adminPassword() }),
+ });
+ if (r.status !== 200 || !r.body?.token) throw new Error(`login failed (HTTP ${r.status})`);
+ return { Authorization: `Bearer ${r.body.token}`, 'Content-Type': 'application/json' };
+}
+
+async function getAccounts(auth) {
+ const r = await jfetch('/admin/claude-accounts', { headers: auth });
+ if (r.status !== 200) throw new Error(`GET claude-accounts failed (HTTP ${r.status})`);
+ const list = Array.isArray(r.body) ? r.body : r.body.data || r.body.accounts || [];
+ return list.filter((a) => a.platform === 'claude' && a.isActive !== false);
+}
+
+// ── policy ───────────────────────────────────────────────────────────────────
+const WARN_STATUSES = new Set(['allowed_warning', 'warning', 'blocked', 'exceeded', 'limited', 'stopped']);
+
+function decide(accts) {
+ const nowMs = Date.now();
+ const decisions = accts.map((a) => {
+ const cu = a.claudeUsage || {};
+ const lu = a._liveUsage; // authoritative direct-from-Anthropic /oauth/usage, or null
+ 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 sw = a.sessionWindow?.sessionWindowStatus || null;
+ const cur = a.schedulable !== false;
+
+ 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;
+ if (rl) { desired = false; reason = 'rate-limited'; }
+ else if (overloaded) { desired = false; reason = 'overloaded(529)'; }
+ else if (sw && WARN_STATUSES.has(sw)) { desired = false; reason = `sessionWindow=${sw}`; soft = true; }
+ else if (utilBreach) { desired = false; reason = `util 5h=${u5} 7d=${u7} 7dOpus=${u7o} ≥ off`; soft = true; }
+ else if ((sw === 'allowed' || sw === null) && utilClear) {
+ desired = true;
+ reason = `healthy (sw=${sw ?? 'none'}${fresh ? `, 5h=${u5}` : ', usage stale/absent'})`;
+ }
+ return { a, cur, desired, reason, soft, sw, u5: u5 ?? '?', rl, overloaded };
+ });
+
+ // FLOOR: never starve the pool via SOFT deprioritizations
+ let usable = decisions.filter((d) => d.desired && !d.rl && !d.overloaded).length;
+ if (usable < FLOOR) {
+ const unum = (d) => (typeof d.u5 === 'number' ? d.u5 : 50);
+ const revertable = decisions
+ .filter((d) => d.desired === false && d.soft && !d.rl && !d.overloaded)
+ .sort((x, y) => unum(x) - unum(y));
+ for (const d of revertable) {
+ if (usable >= FLOOR) break;
+ d.desired = true; d.reason = `FLOOR(${FLOOR}): held schedulable despite ${d.reason}`; usable++;
+ }
+ const final = decisions.filter((d) => d.desired && !d.rl && !d.overloaded).length;
+ if (final < FLOOR) 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)) {
+ 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)`;
+ }
+ }
+ return decisions;
+}
+
+// ── main ─────────────────────────────────────────────────────────────────────
+async function main() {
+ if (C.enabled === false && !STATUS && !DRY) { log('crs.enabled=false — skipping tick'); return; }
+ const auth = await login();
+ const accts = await getAccounts(auth);
+ if (!accts.length) { log('no active claude accounts'); return; }
+ // 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); }));
+ const liveN = accts.filter((a) => a._liveUsage).length;
+ const decisions = decide(accts);
+
+ if (STATUS) {
+ console.log(`CRS pool @ ${BASE} — ${decisions.filter((d) => d.cur).length}/${decisions.length} schedulable`);
+ for (const d of decisions.sort((a, b) => (a.cur === b.cur ? 0 : a.cur ? -1 : 1))) {
+ const flags = [d.rl && 'RL', d.overloaded && 'OVERLOAD', d.sw].filter(Boolean).join(' ');
+ console.log(` ${d.cur ? '●' : '○'} ${d.a.name.padEnd(26)} sched=${d.cur} 5h=${String(d.u5).padStart(3)}% ${flags}`);
+ }
+ return;
+ }
+
+ let changed = 0;
+ for (const d of decisions) {
+ if (d.desired === d.cur) continue;
+ changed++;
+ if (DRY) { log(`[dry] ${d.a.name}: ${d.cur}→${d.desired} (${d.reason})`); continue; }
+ const put = await jfetch(`/admin/claude-accounts/${d.a.id}/toggle-schedulable`, {
+ method: 'PUT', headers: auth, body: JSON.stringify({ schedulable: d.desired }),
+ });
+ log(`${d.a.name}: schedulable ${d.cur}→${d.desired} (${d.reason}) [HTTP ${put.status}]`);
+ }
+ const on = decisions.filter((d) => d.desired).map((d) => d.a.name);
+ const off = decisions.filter((d) => !d.desired).map((d) => `${d.a.name}(${d.sw || (d.rl ? 'RL' : '?')})`);
+ log(`tick: ${changed} change(s). live-quota=${liveN}/${decisions.length} schedulable=${on.length} [${on.join(',')}] | off=[${off.join(',')}]`);
+}
+
+main().catch((e) => { log(`ERROR: ${e.message}`); process.exit(1); });
diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.sh b/claude-ops/scripts/account-rotation/crs-priority-daemon.sh
new file mode 100755
index 00000000..279c60b4
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.sh
@@ -0,0 +1,43 @@
+#!/usr/bin/env 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.
+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)}"
+BASE="${CRS_BASE:-http://127.0.0.1:3000}"
+
+mkdir -p "$LOG_DIR"
+
+# 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
+ fi
+fi
+trap 'rmdir "$LOCK" 2>/dev/null' EXIT
+
+# Skip silently if CRS isn't reachable (don't spam the log while the relay is down).
+curl -sf -o /dev/null --max-time 5 "$BASE/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"
+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
diff --git a/claude-ops/scripts/install-crs-priority-agent.sh b/claude-ops/scripts/install-crs-priority-agent.sh
new file mode 100755
index 00000000..bfe789ca
--- /dev/null
+++ b/claude-ops/scripts/install-crs-priority-agent.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# install-crs-priority-agent.sh — Install the CRS account-priority daemon as a
+# launchd LaunchAgent (macOS) that ticks every 120s.
+#
+# Renders templates/com.claude-ops.crs-priority.plist with absolute paths to the
+# wrapper + log dir, then bootstraps it under the current user's GUI session.
+# Idempotent: re-running re-renders and reloads. Linux users: see the systemd
+# hint printed below.
+#
+# Pre-req: the CRS admin password must be reachable by the daemon — either
+# export CRS_ADMIN_PASSWORD=… (then it lives only in the plist env if you add it), or
+# bash "$PLUGIN_ROOT/lib/credential-store.sh" set CRS-Admin-<adminUser> "$USER" '<pw>'
+# Config (base URL, adminUser, thresholds) lives in the rotator config.json "crs" block.
+
+set -euo pipefail
+
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+[[ -d "$PLUGIN_ROOT" ]] || { echo "error: could not resolve CLAUDE_PLUGIN_ROOT" >&2; exit 1; }
+
+WRAPPER="$PLUGIN_ROOT/scripts/account-rotation/crs-priority-daemon.sh"
+DAEMON="$PLUGIN_ROOT/scripts/account-rotation/crs-priority-daemon.mjs"
+PLIST_TEMPLATE="$PLUGIN_ROOT/templates/com.claude-ops.crs-priority.plist"
+PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.crs-priority.plist"
+DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
+LOG_DIR="$DATA_DIR/logs"
+
+for f in "$WRAPPER" "$DAEMON" "$PLIST_TEMPLATE"; do
+ [[ -f "$f" ]] || { echo "error: required file not found: $f" >&2; exit 1; }
+done
+chmod +x "$WRAPPER" "$DAEMON" 2>/dev/null || true
+
+command -v node >/dev/null 2>&1 || { echo "error: node not found in PATH (need Node 20+)" >&2; exit 1; }
+
+if [[ "$(uname -s)" != "Darwin" ]]; then
+ echo "skip: launchd is macOS-only."
+ echo "Linux: install a systemd user timer that runs every 120s:"
+ echo " ExecStart=/bin/bash $WRAPPER (service, Type=oneshot)"
+ echo " OnBootSec=60s / OnUnitActiveSec=120s (timer)"
+ echo "Then: systemctl --user enable --now crs-priority.timer"
+ exit 0
+fi
+
+mkdir -p "$LOG_DIR" "$(dirname "$PLIST_DEST")"
+
+PLIST_TEMPLATE_PATH="$PLIST_TEMPLATE" \
+WRAPPER_PATH="$WRAPPER" \
+LOG_DIR_PATH="$LOG_DIR" \
+CRS_HOME="$HOME" \
+node -e \
+ 'const fs=require("fs");const e=(s)=>String(s??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");const t=fs.readFileSync(process.env.PLIST_TEMPLATE_PATH,"utf8");process.stdout.write(t.replace(/__WRAPPER_PATH__/g,e(process.env.WRAPPER_PATH)).replace(/__LOG_DIR__/g,e(process.env.LOG_DIR_PATH)).replace(/__HOME__/g,e(process.env.CRS_HOME)));' \
+ > "$PLIST_DEST"
+
+launchctl bootout "gui/$(id -u)/com.claude-ops.crs-priority" 2>/dev/null || true
+launchctl bootstrap "gui/$(id -u)" "$PLIST_DEST"
+
+echo "ok: crs-priority daemon installed"
+echo " plist: $PLIST_DEST"
+echo " wrapper: $WRAPPER"
+echo " logs: $LOG_DIR/crs-priority.log"
+echo " cadence: every 120s (RunAtLoad fires the first tick now)"
+echo
+echo "verify: bash \"$WRAPPER\" --status # prints current schedulable + utilization"
+echo "uninstall: launchctl bootout \"gui/\$(id -u)/com.claude-ops.crs-priority\" && rm \"$PLIST_DEST\""
diff --git a/claude-ops/skills/ops-rotate-setup/SKILL.md b/claude-ops/skills/ops-rotate-setup/SKILL.md
index fdfedc3f..d2af8e93 100644
--- a/claude-ops/skills/ops-rotate-setup/SKILL.md
+++ b/claude-ops/skills/ops-rotate-setup/SKILL.md
@@ -1,7 +1,7 @@
---
name: ops-rotate-setup
description: Interactive OAuth init wizard for the multi-account Claude rotator. Walks through every account in the rotation config and, for any account missing a valid keychain token, delegates to the proven `rotate.mjs` magic-link flow (browser-driver cascade + Gmail polling), which writes the verified OAuth token to `Claude-Rotation-<key>` (key = account label or email, keychain account `$USER`). Re-runnable any time. Standalone alias of the same step inside `/ops:setup`.
-argument-hint: "[--all|--account <email>|--add]"
+argument-hint: "[--all|--account <email>|--add|--crs]"
allowed-tools:
- Bash
- Read
@@ -178,6 +178,62 @@ Result for <email>:
If success and no more accounts remain, jump to **Step 5**.
+## Step 4.5 — CRS relay-pool priority daemon (optional)
+
+If the user runs a **claude-relay-service** (CRS) pool (load-balances Claude
+requests across many accounts at once, exposing a per-account `schedulable`
+flag), offer to install the **priority daemon** that auto-deprioritizes
+near-maxed accounts and re-enables them on recovery. This is independent of the
+keychain rotator above — skip it for keychain-only setups.
+
+`AskUserQuestion`:
+
+```
+Do you run a claude-relay-service (CRS) pool you want auto-prioritized?
+ [Yes — configure + install] — set base URL + admin creds, install the 120s daemon
+ [Not now] — skip (you can run /ops:rotate-setup again later)
+ [What is this?] — one-paragraph explainer, then re-ask
+```
+
+On **[Yes]**:
+
+1. **Base URL + admin user.** Ask for the CRS base URL (default
+ `http://127.0.0.1:3000`) and admin username (default `cradmin`). Write them
+ into the rotator config's `crs` block (create from `config.example.json` if
+ missing), and set `crs.enabled=true`:
+ ```bash
+ CFG="$USER_CFG"
+ jq --arg url "$CRS_URL" --arg u "$CRS_USER" \
+ '.crs = ((.crs // {}) + {enabled:true, baseUrl:$url, adminUser:$u})' \
+ "$CFG" > "$CFG.tmp" && mv "$CFG.tmp" "$CFG"
+ ```
+2. **Admin password → credential store** (never written to config). Ask the user
+ to paste the CRS admin password, then:
+ ```bash
+ CRED="${CLAUDE_PLUGIN_ROOT}/lib/credential-store.sh"
+ ACCT="${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-$USER}"
+ printf '%s' "$CRS_ADMIN_PW" | bash "$CRED" set-stdin "CRS-Admin-$CRS_USER" "$ACCT"
+ ```
+ (The CRS admin password is printed once in the container's
+ `data/init.json` — `adminUsername`/`adminPassword` — on first boot.)
+3. **Smoke-test before installing.** Confirm the creds + reachability with a
+ dry-run tick (no writes):
+ ```bash
+ bash "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/crs-priority-daemon.sh" --status
+ ```
+ If it errors (login failed / unreachable), surface the message and let the
+ user re-enter creds — do NOT install a broken daemon.
+4. **Install the timer** (background-friendly):
+ ```bash
+ bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-crs-priority-agent.sh"
+ ```
+ macOS → launchd every 120s (RunAtLoad fires the first tick). Linux → the
+ installer prints the equivalent systemd-timer snippet.
+
+Tuning (optional, `crs` block): `off5h`/`off7d` (deprioritize thresholds),
+`on5h`/`on7d` (re-enable thresholds, hysteresis), `floor` (min usable accounts),
+`freshMinutes` (max age of utilization data trusted for proactive deprioritize).
+
## Step 5 — Summary
```
@@ -191,12 +247,17 @@ If success and no more accounts remain, jump to **Step 5**.
Config: ~/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json
Keychain: Claude-Rotation-<key> (account: $USER) · key = label or email
+ CRS priority daemon: ✓ installed (every 120s) | ✗ not configured
To enable automatic rotation, open /plugins → claude-ops → settings and
toggle "Multi-account Claude rotator" (account_rotation_enabled).
──────────────────────────────────────────────────────
```
+(Show the CRS line only if Step 4.5 ran. The CRS daemon is independent of the
+`account_rotation_enabled` toggle — it is gated by `crs.enabled` in config +
+whether its launchd/systemd timer is installed.)
+
Exit. Do NOT auto-enable `account_rotation_enabled` — that decision belongs
to the user, made explicitly through the plugin settings UI.
@@ -205,6 +266,7 @@ to the user, made explicitly through the plugin settings UI.
- `--all` (default): full wizard as described above.
- `--account <email>`: skip Step 2; only init the matching account.
- `--add`: skip token check; jump straight to Step 2 add loop, then init.
+- `--crs`: jump straight to **Step 4.5** (configure + install the CRS priority daemon), skipping the keychain-account OAuth steps.
## Failure modes
@@ -215,3 +277,5 @@ to the user, made explicitly through the plugin settings UI.
| token still `✗` after success | account `label`/`email` mismatch vs config | Confirm the config `key` (`label // email`) matches the `Claude-Rotation-<key>` service name |
| no CDP browser available | no Chrome on `:9222` and none installed | rotate.mjs falls back to bundled Chromium, which Turnstile may block — install/launch Chrome so the cascade can attach |
| Google SSO / 2FA prompt | Workspace-domain account needs interactive Google login | Let the user complete login in the cascade's visible Chrome; do NOT auto-solve 2FA |
+| CRS `--status` "login failed" | wrong admin user/password or CRS not reachable | Re-enter creds (Step 4.5); admin creds are in the CRS container `data/init.json`; verify `curl $CRS_URL/health` |
+| CRS daemon installed but no effect | `crs.enabled=false`, or all accounts already correctly flagged | Check `crs.enabled` in config; `tail logs/crs-priority.log`; a steady-state tick logs `0 change(s)` |
diff --git a/claude-ops/skills/ops-rotate/SKILL.md b/claude-ops/skills/ops-rotate/SKILL.md
index 9ed0b867..e094765c 100644
--- a/claude-ops/skills/ops-rotate/SKILL.md
+++ b/claude-ops/skills/ops-rotate/SKILL.md
@@ -1,7 +1,7 @@
---
name: ops-rotate
-description: Multi-account Claude Max rotator. Status, manual rotation, account list, add-account wizard. Requires account_rotation_enabled=true in plugin settings.
-argument-hint: "[status|rotate-now|list|add-account]"
+description: Multi-account Claude Max rotator. Status, manual rotation, account list, add-account wizard, and CRS relay-pool auto-prioritization. Requires account_rotation_enabled=true in plugin settings.
+argument-hint: "[status|rotate-now|list|add-account|crs|crs-tick]"
allowed-tools:
- Bash
- Read
@@ -25,6 +25,21 @@ Manage the optional multi-account Claude Max rotator. Off by default — flip
| `rotate-now` | Force rotation to the most-cooled candidate (or `--to <email>`) |
| `list` | List every configured account with token state + last util |
| `add-account` | Interactive wizard: collect email, OAuth into rotator vault |
+| `crs` | Show the CRS relay-pool schedulable state + priority-daemon health |
+| `crs-tick` | Run one CRS priority tick now (append `--dry-run` to preview, no writes) |
+
+## Two rotation models
+
+This skill manages **two complementary** account-management systems:
+
+- **Keychain rotator** (`status`/`rotate-now`/`list`/`add-account`) — for **direct-auth**
+ sessions. One active claude.ai OAuth token in the keychain at a time; the daemon swaps
+ to the coolest account when the active one heats up.
+- **CRS priority daemon** (`crs`/`crs-tick`) — for a **claude-relay-service** pool, which
+ load-balances across *many* accounts simultaneously. Instead of swapping one token, it
+ toggles each account's `schedulable` flag from live utilization so the relay avoids
+ near-maxed accounts and re-enables them on recovery. Off by default; see
+ **ops-rotate-setup** to configure + install.
## Pre-flight (every invocation)
@@ -112,6 +127,42 @@ This is the only mutating subcommand. Walk the user through:
```
6. **Verify.** Run `status` subcommand inline.
+## crs (relay-pool status)
+
+Show the claude-relay-service pool's per-account schedulable state + the priority
+daemon's health. Read-only.
+
+```
+WRAP="$ROT_SRC/crs-priority-daemon.sh"
+bash "$WRAP" --status 2>&1 | head -40 # prints "● name sched=true 5h=NN% <status>"
+launchctl list 2>/dev/null | grep com.claude-ops.crs-priority || echo "crs-priority daemon: not loaded"
+tail -n 5 "${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs/crs-priority.log" 2>/dev/null
+```
+
+Render a compact panel:
+
+```
+CRS POOL (http://127.0.0.1:3000)
+ schedulable : 7 / 10
+ off : canary-sponsors (rate-limited), pool-chairman (warning), pool-foundation (warning)
+ daemon : ✓ running (every 120s) | ✗ not loaded — run /ops:rotate-setup
+```
+
+If CRS `/health` is unreachable, say so and point to ops-rotate-setup. If the daemon
+isn't loaded but `crs.enabled` is true, suggest `/ops:rotate-setup`.
+
+## crs-tick (run one tick now)
+
+Apply (or, with `--dry-run`, preview) one prioritization pass immediately — useful
+right after changing thresholds or to confirm the policy.
+
+```
+bash "$ROT_SRC/crs-priority-daemon.sh" ${ARGS:-} # ARGS="--dry-run" to preview
+```
+
+This is the same code the launchd timer runs; the daemon only ever toggles
+`schedulable` (fully reversible) and never deletes or mutates account credentials.
+
## Optional npm dep
`rotate.mjs` uses Playwright only for the browser fallback. It is declared as
diff --git a/claude-ops/templates/com.claude-ops.crs-priority.plist b/claude-ops/templates/com.claude-ops.crs-priority.plist
new file mode 100644
index 00000000..aecc78e8
--- /dev/null
+++ b/claude-ops/templates/com.claude-ops.crs-priority.plist
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ CRS account-priority daemon (claude-relay-service pool auto-prioritization).
+
+ Schedule: every 120s. Equivalent systemd: OnUnitActiveSec=120s.
+ The installer (scripts/install-crs-priority-agent.sh) substitutes
+ __WRAPPER_PATH__, __LOG_DIR__, __HOME__ and writes the rendered copy to
+ ~/Library/LaunchAgents/com.claude-ops.crs-priority.plist before:
+ launchctl bootstrap "gui/$(id -u)" <plist>
+
+ To uninstall:
+ launchctl bootout "gui/$(id -u)/com.claude-ops.crs-priority"
+ rm ~/Library/LaunchAgents/com.claude-ops.crs-priority.plist
+-->
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.claude-ops.crs-priority</string>
+
+ <key>ProgramArguments</key>
+ <array>
+ <string>/bin/bash</string>
+ <string>__WRAPPER_PATH__</string>
+ </array>
+
+ <key>StartInterval</key>
+ <integer>120</integer>
+
+ <key>ThrottleInterval</key>
+ <integer>30</integer>
+
+ <key>RunAtLoad</key>
+ <true/>
+
+ <key>StandardOutPath</key>
+ <string>__LOG_DIR__/crs-priority-launchd.log</string>
+ <key>StandardErrorPath</key>
+ <string>__LOG_DIR__/crs-priority-launchd.log</string>
+
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key>
+ <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
+ <key>HOME</key>
+ <string>__HOME__</string>
+ <key>NODE_NO_WARNINGS</key>
+ <string>1</string>
+ </dict>
+
+ <key>ProcessType</key>
+ <string>Background</string>
+ <key>LowPriorityIO</key>
+ <true/>
+</dict>
+</plist>