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
feat(crs): opt-in magic-link autoloop reconciler (#710)
Aurora Capitald4d308f7c41e
diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.jsonindex c6ae9a5e..c059927c 100644--- a/claude-ops/scripts/account-rotation/config.example.json+++ b/claude-ops/scripts/account-rotation/config.example.json@@ -65,6 +65,10 @@"tokenRefreshEnabled": false,"_tokenRefreshEnabled_note": "Off by default (or $CRS_TOKEN_REFRESH_ENABLED=1). Turns on crs-401-refresher.mjs, which proactively refreshes each CRS account's OAuth access token via POST /admin/claude-accounts/:id/refresh before it expires, reviving sidelined accounts on success and flagging a dead refresh_token as needs-reauth on failure. Own state file at <stateDir>/crs-401-state.json. Before reviving an account it checks cooldownStatePath (read-only) so it never re-enables one crs-429-cooldown.mjs is genuinely holding for a live rate limit.","tokenRefreshWindowMs": 1800000,- "_tokenRefreshWindowMs_note": "Refresh an account's token once it's within this many ms of expiry (default 30m)."+ "_tokenRefreshWindowMs_note": "Refresh an account's token once it's within this many ms of expiry (default 30m).",+ "enableMagicLinkRecovery": false,+ "_enableMagicLinkRecovery_note": "Off by default (or $CRS_ENABLE_MAGIC_LINK=1). Turns on magic-link-autoloop.mjs, which dispatches an UNATTENDED browser-based re-auth (rotate.mjs --setup --auto) for ONE account per tick that crs-401-refresher.mjs (or, if that's disabled, a direct vault check) has flagged as needing reauth — i.e. a confirmed dead refresh_token, not just an expiring one. Serial, single-flight, and skips entirely if a manual rotation is already in progress. Uses the same Gmail-via-gog flow /ops:rotate-setup already uses; nothing account-specific is hardcoded. Leave off if you'd rather a human always handles re-auth.",+ "magicLinkRetryCooldownMs": 21600000,+ "_magicLinkRetryCooldownMs_note": "Minimum time between unattended retry attempts for the SAME account, success or failure, so a persistently-broken account isn't retried in a tight loop (default 6h)."}}diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjsnew file mode 100644index 00000000..7d90adee--- /dev/null+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs@@ -0,0 +1,256 @@+#!/usr/bin/env node+/**+ * magic-link-autoloop.mjs — opt-in unattended re-auth reconciler.+ *+ * Fills a gap crs-401-refresher.mjs deliberately leaves for a human: when an+ * account's refresh_token is confirmed dead (not just expiring), the+ * refresher flags it needs-reauth and stops — someone has to log back in.+ * This reconciler, if enabled, takes that one further step: it dispatches+ * `rotate.mjs --setup --only=<key> --auto --skip-valid` (the same generic,+ * already-Gmail-via-`gog` setup flow `/ops:rotate-setup` uses) for ONE+ * needs-reauth account per tick, serially, with a per-account cooldown so a+ * genuinely broken account isn't retried in a tight loop.+ *+ * OPT-IN. Does nothing (exits 0) unless crs.enableMagicLinkRecovery is true+ * (or $CRS_ENABLE_MAGIC_LINK=1) — installing this plugin never silently+ * starts unattended re-auth attempts.+ *+ * Provider note: this reconciler's own logic (candidate detection, locking,+ * cooldowns) has no email-provider dependency at all — it only decides WHICH+ * account to retry and WHEN. The actual email polling happens inside+ * rotate.mjs's setup flow, which is Gmail-via-`gog` today. Making THAT+ * provider-agnostic (e.g. IMAP) is a rotate.mjs-internals change, tracked+ * separately (see AUR-1555) — this reconciler will pick up such a change for+ * free once it lands, since it only calls rotate.mjs's public --setup+ * interface and never touches its internals.+ *+ * Concurrency (hard rules, ported from a documented incident where two+ * autoloop ticks raced the same account's browser session):+ * 1. Single-flight lock (crs-reconciler-state.mjs) — one tick fleet-wide.+ * 2. Exactly ONE account per tick, always serial.+ * 3. Skips the tick entirely (no error) if rotate.mjs's own .rotating lock+ * is held — never contends with a live manual rotation.+ *+ * CONFIG (config.json "crs" block; every key overridable by env — see+ * config.example.json for the full annotated schema):+ * enableMagicLinkRecovery default false — must be true (or+ * $CRS_ENABLE_MAGIC_LINK=1) to do anything.+ * magicLinkRetryCooldownMs default 21600000 (6h) — minimum time between+ * retry attempts for the SAME account, success+ * or failure, so a persistently-broken account+ * doesn't get hammered.+ *+ * CLI: (none)=one tick · --dry-run=log the candidate, don't dispatch · --status+ */+import { spawn } from 'child_process';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { homedir, platform } from 'os';+import { existsSync, readFileSync } from 'fs';+import { loadRotationConfig, buildCrsNameMaps, crsFileVaultPath } from './crs-pool-config.mjs';+import { loadJsonState, saveJsonStateAtomic, withOwnStateLock } from './crs-reconciler-state.mjs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const args = new Set(process.argv.slice(2));+const DRY = args.has('--dry-run');+const STATUS = args.has('--status');++const C = loadRotationConfig()?.crs || {};+const ENABLED = process.env.CRS_ENABLE_MAGIC_LINK === '1' || C.enableMagicLinkRecovery === true;+const RETRY_COOLDOWN_MS = Number(process.env.CRS_MAGIC_LINK_RETRY_COOLDOWN_MS ?? C.magicLinkRetryCooldownMs ?? 21_600_000);+const ROTATE_TIMEOUT_MS = Number(process.env.CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS ?? 12 * 60_000);++function expandHome(p) {+ if (!p) return p;+ return p.startsWith('~') ? join(homedir(), p.slice(1)) : p;+}++const DEFAULT_DATA_DIR =+ process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');+const STATE_DIR = expandHome(process.env.CRS_STATE_DIR || C.stateDir) || join(DEFAULT_DATA_DIR, 'account-rotation');+const STATE_PATH = join(STATE_DIR, 'crs-magic-link-state.json');+const REFRESHER_STATE_PATH = join(STATE_DIR, 'crs-401-state.json');+const ROTATE_SCRIPT = join(__dirname, 'rotate.mjs');+const ROTATING_LOCK = join(__dirname, '.rotating');++function log(msg) {+ console.log(`[${new Date().toISOString()}] [magic-link-autoloop] ${msg}`);+}++function pidAlive(pid) {+ if (!pid) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++/** rotate.mjs owns this lock file for any live manual/scripted rotation — never contend with it. */+function rotatingLockBusy() {+ if (!existsSync(ROTATING_LOCK)) return false;+ try {+ const raw = readFileSync(ROTATING_LOCK, 'utf8').trim().split(/\s+/);+ const pid = parseInt(raw[1] || raw[raw.length - 1] || '0', 10) || 0;+ return pidAlive(pid);+ } catch {+ return false;+ }+}++/** Read crs-401-refresher's own state file, READ-ONLY, for accounts it flagged needs-reauth. */+function needsReauthKeysFromRefresher() {+ const state = loadJsonState(REFRESHER_STATE_PATH, log);+ const out = new Set();+ for (const [key, entry] of Object.entries(state || {})) {+ if (entry && typeof entry === 'object' && entry.needsReauth) out.add(key);+ }+ return out;+}++/** Fallback candidate source when crs-401-refresher isn't enabled: vault expiry, generic. */+function needsReauthKeysFromVault(vaultKeys) {+ const cfg = loadRotationConfig();+ const vaultPath = crsFileVaultPath(cfg) || join(homedir(), '.claude', '.credentials.json');+ if (!existsSync(vaultPath)) return new Set();+ let vault;+ try {+ vault = JSON.parse(readFileSync(vaultPath, 'utf8'));+ } catch {+ return new Set();+ }+ const out = new Set();+ for (const key of vaultKeys) {+ const entry = vault?.[`Claude-Rotation-${key}`] || vault?.[key];+ const oauth = entry?.claudeAiOauth || entry?.oauth || entry;+ const hasRefresh = !!(oauth?.refreshToken || oauth?.refresh_token);+ if (!entry || !hasRefresh) out.add(key);+ }+ return out;+}++function pickCandidate(now, state) {+ const cfg = loadRotationConfig();+ const maps = buildCrsNameMaps(cfg);+ const byKey = maps?.nameByVaultKey || cfg?.crs?.nameByVaultKey || {};+ const vaultKeys = Object.keys(byKey);+ if (!vaultKeys.length) return null;++ const fromRefresher = needsReauthKeysFromRefresher();+ const needy = fromRefresher.size ? fromRefresher : needsReauthKeysFromVault(vaultKeys);++ const eligible = [...needy].filter((key) => {+ const last = state[key];+ if (last?.lastAttemptAt && now - last.lastAttemptAt < RETRY_COOLDOWN_MS) return false;+ return true;+ });+ if (!eligible.length) return null;++ // Oldest-attempted (or never-attempted) first — no account-name heuristics.+ eligible.sort((a, b) => (state[a]?.lastAttemptAt || 0) - (state[b]?.lastAttemptAt || 0));+ return eligible[0];+}++function spawnRotateSetup(vaultKey) {+ return new Promise((resolve) => {+ const args = [ROTATE_SCRIPT, '--setup', `--only=${vaultKey}`, '--auto', '--skip-valid'];+ log(`spawn: node ${args.join(' ')}`);+ const child = spawn(process.execPath, args, {+ cwd: __dirname,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let out = '';+ child.stdout.on('data', (d) => {+ out += d.toString();+ });+ child.stderr.on('data', (d) => {+ out += d.toString();+ });+ const timer = setTimeout(() => {+ log(`timeout — killing rotate.mjs setup for ${vaultKey}`);+ try {+ child.kill('SIGTERM');+ } catch {}+ }, ROTATE_TIMEOUT_MS);+ child.on('exit', (code) => {+ clearTimeout(timer);+ resolve({ code, out });+ });+ });+}++async function tick() {+ if (rotatingLockBusy()) {+ log('rotate.mjs .rotating lock busy — skip tick (never contend with a live rotation)');+ return;+ }++ const now = Date.now();+ const { skipped, result } = await withOwnStateLock(+ STATE_PATH,+ async () => {+ const state = loadJsonState(STATE_PATH, log);+ const candidate = pickCandidate(now, state);+ if (!candidate) {+ log('no eligible candidates (none flagged needs-reauth, or all on cooldown)');+ return { dispatched: false };+ }++ if (DRY) {+ log(`[dry-run] would dispatch rotate.mjs --setup for ${candidate}`);+ return { dispatched: false, candidate };+ }++ state[candidate] = { ...(state[candidate] || {}), lastAttemptAt: now };+ saveJsonStateAtomic(STATE_PATH, state);++ const { code, out } = await spawnRotateSetup(candidate);+ const ok = code === 0 && /"ok"\s*:\s*true/i.test(out);+ state[candidate] = {+ ...(state[candidate] || {}),+ lastAttemptAt: now,+ lastCode: code,+ lastOkAt: ok ? now : state[candidate]?.lastOkAt,+ };+ saveJsonStateAtomic(STATE_PATH, state);+ log(`done ${candidate} exit=${code} ok=${ok}`);+ return { dispatched: true, candidate, ok };+ },+ log,+ );++ if (skipped) log('another tick already holds the lock — skipping (fleet-wide single-flight)');+ return result;+}++function printStatus() {+ const state = loadJsonState(STATE_PATH, log);+ const rows = Object.entries(state);+ console.log(`enabled=${ENABLED} retryCooldownMs=${RETRY_COOLDOWN_MS} stateDir=${STATE_DIR}`);+ if (!rows.length) {+ console.log('(no attempts recorded yet)');+ return;+ }+ for (const [key, s] of rows) {+ const lastAt = s.lastAttemptAt ? new Date(s.lastAttemptAt).toISOString() : 'never';+ console.log(` ${key}: lastAttempt=${lastAt} lastCode=${s.lastCode ?? '?'} lastOk=${s.lastOkAt ? new Date(s.lastOkAt).toISOString() : 'never'}`);+ }+}++async function main() {+ if (STATUS) {+ printStatus();+ return;+ }+ if (!ENABLED) {+ log('disabled (crs.enableMagicLinkRecovery is false) — no-op, exiting');+ return;+ }+ await tick();+}++main().catch((e) => {+ log(`fatal: ${e.message || e}`);+ process.exitCode = 1;+});diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.sh b/claude-ops/scripts/account-rotation/magic-link-autoloop.shnew file mode 100755index 00000000..da0528d2--- /dev/null+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.sh@@ -0,0 +1,22 @@+#!/bin/bash+# magic-link-autoloop.sh — single-flight wrapper for magic-link-autoloop.mjs.+# Invoked once-per-tick by launchd/systemd (recommended: every 600s — this+# reconciler dispatches a real unattended re-auth attempt per tick, so it+# should stay infrequent relative to magicLinkRetryCooldownMs).+set -uo pipefail++source "$HOME/.claude/scripts/lib/once.sh" 2>/dev/null || true+type claude_once >/dev/null 2>&1 && { claude_once magic-link-autoloop 60 || exit 0; }++DIR="$HOME/.claude/scripts/account-rotation"+LOG="$DIR/magic-link-autoloop.log"+NODE="$(command -v node || echo /opt/homebrew/bin/node)"++export CLAUDE_PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/ops-marketplace/claude-ops}"++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++"$NODE" "$DIR/magic-link-autoloop.mjs" >> "$LOG" 2>&1diff --git a/claude-ops/scripts/install-crs-reconcilers-agent.sh b/claude-ops/scripts/install-crs-reconcilers-agent.shindex 7ac1e1f9..1c864ba5 100755--- a/claude-ops/scripts/install-crs-reconcilers-agent.sh+++ b/claude-ops/scripts/install-crs-reconcilers-agent.sh@@ -1,11 +1,11 @@#!/usr/bin/env bash-# install-crs-reconcilers-agent.sh — Install the CRS 429-cooldown and/or-# 401-refresher reconcilers as launchd LaunchAgents (macOS).+# install-crs-reconcilers-agent.sh — Install the CRS 429-cooldown, 401-refresher,+# and/or magic-link-autoloop reconcilers as launchd LaunchAgents (macOS).#-# Reads crs.cooldownEnabled / crs.tokenRefreshEnabled from the rotator config-# and installs only the ones that are true — this script is safe to re-run-# any time config changes (idempotent: re-renders + reloads what's enabled,-# uninstalls what's been turned back off).+# Reads crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery+# from the rotator config and installs only the ones that are true — this+# script is safe to re-run any time config changes (idempotent: re-renders ++# reloads what's enabled, uninstalls what's been turned back off).## Pre-req: same CRS admin credentials as install-crs-priority-agent.sh.# Config (stateDir, logDir, thresholds) lives in the rotator config.json@@ -27,24 +27,34 @@ command -v jq >/dev/null 2>&1 || { echo "error: jq not found in PATH" >&2; exitCOOLDOWN_ENABLED="false"TOKEN_REFRESH_ENABLED="false"+MAGIC_LINK_ENABLED="false"if [[ -f "$CFG" ]]; thenCOOLDOWN_ENABLED="$(jq -r '.crs.cooldownEnabled // false' "$CFG" 2>/dev/null || echo false)"TOKEN_REFRESH_ENABLED="$(jq -r '.crs.tokenRefreshEnabled // false' "$CFG" 2>/dev/null || echo false)"+ MAGIC_LINK_ENABLED="$(jq -r '.crs.enableMagicLinkRecovery // false' "$CFG" 2>/dev/null || echo false)"fi[[ "${CRS_COOLDOWN_ENABLED:-}" == "1" ]] && COOLDOWN_ENABLED="true"[[ "${CRS_TOKEN_REFRESH_ENABLED:-}" == "1" ]] && TOKEN_REFRESH_ENABLED="true"+[[ "${CRS_ENABLE_MAGIC_LINK:-}" == "1" ]] && MAGIC_LINK_ENABLED="true"-if [[ "$COOLDOWN_ENABLED" != "true" && "$TOKEN_REFRESH_ENABLED" != "true" ]]; then- echo "skip: neither crs.cooldownEnabled nor crs.tokenRefreshEnabled is true in $CFG"- echo " set one (or \$CRS_COOLDOWN_ENABLED=1 / \$CRS_TOKEN_REFRESH_ENABLED=1) and re-run"+if [[ "$COOLDOWN_ENABLED" != "true" && "$TOKEN_REFRESH_ENABLED" != "true" && "$MAGIC_LINK_ENABLED" != "true" ]]; then+ echo "skip: none of crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery is true in $CFG"+ echo " set one (or \$CRS_COOLDOWN_ENABLED=1 / \$CRS_TOKEN_REFRESH_ENABLED=1 / \$CRS_ENABLE_MAGIC_LINK=1) and re-run"exit 0fi+if [[ "$MAGIC_LINK_ENABLED" == "true" ]]; then+ echo "note: crs.enableMagicLinkRecovery is true — magic-link-autoloop will attempt UNATTENDED"+ echo " browser-based re-auth for confirmed dead-refresh-token accounts. Review"+ echo " config.example.json's _enableMagicLinkRecovery_note if this is unexpected."+fi+if [[ "$(uname -s)" != "Darwin" ]]; thenecho "skip: launchd is macOS-only."echo "Linux: install a systemd user timer for each enabled reconciler:"- [[ "$COOLDOWN_ENABLED" == "true" ]] && echo " crs-429-cooldown: ExecStart=/bin/bash $PLUGIN_ROOT/scripts/account-rotation/crs-429-cooldown.sh OnUnitActiveSec=60s"- [[ "$TOKEN_REFRESH_ENABLED" == "true" ]] && echo " crs-401-refresher: ExecStart=/bin/bash $PLUGIN_ROOT/scripts/account-rotation/crs-401-refresher.sh OnUnitActiveSec=300s"+ [[ "$COOLDOWN_ENABLED" == "true" ]] && echo " crs-429-cooldown: ExecStart=/bin/bash $PLUGIN_ROOT/scripts/account-rotation/crs-429-cooldown.sh OnUnitActiveSec=60s"+ [[ "$TOKEN_REFRESH_ENABLED" == "true" ]] && echo " crs-401-refresher: ExecStart=/bin/bash $PLUGIN_ROOT/scripts/account-rotation/crs-401-refresher.sh OnUnitActiveSec=300s"+ [[ "$MAGIC_LINK_ENABLED" == "true" ]] && echo " magic-link-autoloop: ExecStart=/bin/bash $PLUGIN_ROOT/scripts/account-rotation/magic-link-autoloop.sh OnUnitActiveSec=600s"echo "Then: systemctl --user enable --now <unit>.timer"exit 0fi@@ -89,8 +99,17 @@ elseuninstall "crs-401-refresher"fi+if [[ "$MAGIC_LINK_ENABLED" == "true" ]]; then+ render_and_install "magic-link-autoloop" \+ "$PLUGIN_ROOT/scripts/account-rotation/magic-link-autoloop.sh" \+ "$PLUGIN_ROOT/templates/com.claude-ops.magic-link-autoloop.plist"+else+ uninstall "magic-link-autoloop"+fi+echoecho "verify: node \"$PLUGIN_ROOT/scripts/account-rotation/crs-429-cooldown.mjs\" --status"echo " node \"$PLUGIN_ROOT/scripts/account-rotation/crs-401-refresher.mjs\" --status"-echo "logs: $LOG_DIR/crs-429-cooldown.log , $LOG_DIR/crs-401-refresher.log"-echo "uninstall both: launchctl bootout \"gui/\$(id -u)/com.claude-ops.crs-429-cooldown\" \"gui/\$(id -u)/com.claude-ops.crs-401-refresher\""+echo " node \"$PLUGIN_ROOT/scripts/account-rotation/magic-link-autoloop.mjs\" --status"+echo "logs: $LOG_DIR/crs-429-cooldown.log , $LOG_DIR/crs-401-refresher.log , $LOG_DIR/magic-link-autoloop.log"+echo "uninstall all: launchctl bootout \"gui/\$(id -u)/com.claude-ops.crs-429-cooldown\" \"gui/\$(id -u)/com.claude-ops.crs-401-refresher\" \"gui/\$(id -u)/com.claude-ops.magic-link-autoloop\""diff --git a/claude-ops/skills/ops-rotate-setup/SKILL.md b/claude-ops/skills/ops-rotate-setup/SKILL.mdindex 1eac0e48..5c8bc7f1 100644--- a/claude-ops/skills/ops-rotate-setup/SKILL.md+++ b/claude-ops/skills/ops-rotate-setup/SKILL.md@@ -296,6 +296,54 @@ On anything but `[Skip]`:macOS → launchd, 60s / 300s cadence (RunAtLoad fires the first tick).Linux → the installer prints the equivalent systemd-timer snippets.+## Step 4.7 — Magic-link autoloop (optional, unattended re-auth)++Only offer this if Step 4.6's 401-refresher was enabled — this reconciler+reads its needs-reauth flags. Unlike the other reconcilers, this one+dispatches a REAL browser-based re-auth attempt (via `rotate.mjs --setup`,+the same Gmail-via-`gog` flow this wizard itself uses in Step 4) — make sure+the user understands that before enabling it.++`AskUserQuestion`:++```+Enable unattended re-auth for accounts with a confirmed dead token?+ [Yes — enable] — magic-link-autoloop dispatches rotate.mjs --setup automatically+ [Not now] — a human handles re-auth manually when 401-refresher flags an account+ [What is this?] — one-paragraph explainer, then re-ask+```++On **[Yes]**:++1. **Write the config flag.**+ ```bash+ CFG="$USER_CFG"+ jq '.crs = ((.crs // {}) + {enableMagicLinkRecovery:true})' \+ "$CFG" > "$CFG.tmp" && mv "$CFG.tmp" "$CFG"+ ```+ Optional: ask for a non-default `crs.magicLinkRetryCooldownMs` (default 6h) —+ see `config.example.json`.++2. **Smoke-test** (no writes, no dispatch):+ ```bash+ node "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/magic-link-autoloop.mjs" --status+ ```++3. **Install** (folded into the same idempotent installer as Step 4.6):+ ```bash+ bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-crs-reconcilers-agent.sh"+ ```+ macOS → launchd, 600s cadence, `RunAtLoad=false` (does NOT fire immediately+ on install, unlike the other reconcilers — first tick waits for the normal+ schedule so a fresh install never triggers a surprise browser launch).+ Linux → the installer prints the equivalent systemd-timer snippet.++Note on provider scope: this reconciler's own logic (which account, when, how+often) has no email-provider dependency — it only decides what to retry and+delegates the actual OAuth+email-poll work to `rotate.mjs --setup`, which is+Gmail-via-`gog` today. A fully provider-agnostic email backend (e.g. IMAP)+would be a `rotate.mjs`-internals change, out of scope here.+## Step 5 — Summary```@@ -312,17 +360,19 @@ On anything but `[Skip]`:CRS priority daemon: ✓ installed (every 120s) | ✗ not configuredCRS 429-cooldown: ✓ installed (every 60s) | ✗ not enabledCRS 401-refresher: ✓ installed (every 300s) | ✗ not enabled+ Magic-link autoloop: ✓ installed (every 600s) | ✗ not enabledTo enable automatic rotation, open /plugins → claude-ops → settings andtoggle "Multi-account Claude rotator" (account_rotation_enabled).──────────────────────────────────────────────────────```-(Show the CRS priority-daemon line only if Step 4.5 ran; show the two-reconciler lines only if Step 4.6 ran. All three CRS daemons are independent-of the `account_rotation_enabled` toggle — each is gated by its own config-flag (`crs.enabled`, `crs.cooldownEnabled`, `crs.tokenRefreshEnabled`) plus-whether its launchd/systemd timer is installed.)+(Show the CRS priority-daemon line only if Step 4.5 ran; show the two Step 4.6+reconciler lines only if Step 4.6 ran; show the magic-link line only if Step+4.7 ran. All four CRS daemons are independent of the `account_rotation_enabled`+toggle — each is gated by its own config flag (`crs.enabled`,+`crs.cooldownEnabled`, `crs.tokenRefreshEnabled`, `crs.enableMagicLinkRecovery`)+plus whether its launchd/systemd timer is installed.)Exit. Do NOT auto-enable `account_rotation_enabled` — that decision belongsto the user, made explicitly through the plugin settings UI.@@ -333,7 +383,7 @@ to the user, made explicitly through the plugin settings UI.- `--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), then **Step 4.6** (offer the reconciler add-ons), skipping the keychain-account OAuth steps.-- `--reconcilers`: jump straight to **Step 4.6** (offer/reconfigure the 429-cooldown and 401-refresher reconcilers) — requires Step 4.5 already configured (`crs.enabled=true`); if not, print the same message as `--crs` needing configuration first and exit.+- `--reconcilers`: jump straight to **Step 4.6** (offer/reconfigure the 429-cooldown and 401-refresher reconcilers, then Step 4.7's magic-link autoloop offer) — requires Step 4.5 already configured (`crs.enabled=true`); if not, print the same message as `--crs` needing configuration first and exit.## Failure modes@@ -348,3 +398,5 @@ to the user, made explicitly through the plugin settings UI.| 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)` || CRS reconciler `--status` errors | wrong admin creds or CRS unreachable (same creds as priority daemon) | Re-check Step 4.5's CRS creds; `curl $CRS_URL/health` || CRS reconciler installed but no effect | `crs.cooldownEnabled`/`crs.tokenRefreshEnabled` false, or no account currently needs it | Check the relevant flag in config; `tail logs/crs-429-cooldown.log` or `crs-401-refresher.log` — both are safe no-ops when nothing needs action |+| magic-link-autoloop never dispatches | `crs.enableMagicLinkRecovery` false, 401-refresher not enabled/hasn't flagged anyone, or account is on `magicLinkRetryCooldownMs` cooldown | `node magic-link-autoloop.mjs --status`; confirm 401-refresher is enabled and has a `needsReauth` entry |+| magic-link-autoloop dispatches too often | `magicLinkRetryCooldownMs` too low for a persistently-broken account | Raise the cooldown in config; each attempt is a real browser-automation run, not free |diff --git a/claude-ops/skills/ops-rotate/SKILL.md b/claude-ops/skills/ops-rotate/SKILL.mdindex 6e41f20d..a3f8eeda 100644--- a/claude-ops/skills/ops-rotate/SKILL.md+++ b/claude-ops/skills/ops-rotate/SKILL.md@@ -130,8 +130,8 @@ This is the only mutating subcommand. Walk the user through:## crs (relay-pool status)Show the claude-relay-service pool's per-account schedulable state + the priority-daemon's health, plus the two optional reconcilers (429-cooldown, 401-refresher)-if enabled. Read-only.+daemon's health, plus the three optional reconcilers (429-cooldown, 401-refresher,+magic-link-autoloop) if enabled. Read-only.```WRAP="$ROT_SRC/crs-priority-daemon.sh"@@ -139,11 +139,13 @@ bash "$WRAP" --status 2>&1 | head -40 # prints "● name sched=true 5h=NN% <slaunchctl 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-# Only if crs.cooldownEnabled / crs.tokenRefreshEnabled are true in config:+# Only if crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery are true in config:node "$ROT_SRC/crs-429-cooldown.mjs" --status 2>&1launchctl list 2>/dev/null | grep com.claude-ops.crs-429-cooldown || echo "crs-429-cooldown: not loaded"node "$ROT_SRC/crs-401-refresher.mjs" --status 2>&1launchctl list 2>/dev/null | grep com.claude-ops.crs-401-refresher || echo "crs-401-refresher: not loaded"+node "$ROT_SRC/magic-link-autoloop.mjs" --status 2>&1+launchctl list 2>/dev/null | grep com.claude-ops.magic-link-autoloop || echo "magic-link-autoloop: not loaded"```Render a compact panel:@@ -155,6 +157,7 @@ CRS POOL (http://127.0.0.1:3000)daemon : ✓ running (every 120s) | ✗ not loaded — run /ops:rotate-setup429-cooldown: ✓ running (every 60s) | ✗ not loaded | – not enabled (crs.cooldownEnabled=false)401-refresher: ✓ running (every 300s) | ✗ not loaded | – not enabled (crs.tokenRefreshEnabled=false)+ magic-link : ✓ running (every 600s) | ✗ not loaded | – not enabled (crs.enableMagicLinkRecovery=false)```If CRS `/health` is unreachable, say so and point to ops-rotate-setup. If the daemondiff --git a/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist b/claude-ops/templates/com.claude-ops.magic-link-autoloop.plistnew file mode 100644index 00000000..01d7059f--- /dev/null+++ b/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist@@ -0,0 +1,57 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ Magic-link autoloop reconciler (opt-in unattended re-auth for confirmed+ dead-refresh-token accounts).++ Schedule: every 600s. Equivalent systemd: OnUnitActiveSec=600s.+ The installer (scripts/install-crs-reconcilers-agent.sh) substitutes+ __WRAPPER_PATH__, __LOG_DIR__, __HOME__ and writes the rendered copy to+ ~/Library/LaunchAgents/com.claude-ops.magic-link-autoloop.plist before:+ launchctl bootstrap "gui/$(id -u)" <plist>++ To uninstall:+ launchctl bootout "gui/$(id -u)/com.claude-ops.magic-link-autoloop"+ rm ~/Library/LaunchAgents/com.claude-ops.magic-link-autoloop.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.magic-link-autoloop</string>++ <key>ProgramArguments</key>+ <array>+ <string>/bin/bash</string>+ <string>__WRAPPER_PATH__</string>+ </array>++ <key>StartInterval</key>+ <integer>600</integer>++ <key>ThrottleInterval</key>+ <integer>60</integer>++ <key>RunAtLoad</key>+ <false/>++ <key>StandardOutPath</key>+ <string>__LOG_DIR__/magic-link-autoloop-launchd.log</string>+ <key>StandardErrorPath</key>+ <string>__LOG_DIR__/magic-link-autoloop-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>