Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
Fix account recovery race handling (#798)
Aurora Capital63df3ac9e39b
diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.mdindex 64292cd7..7d9cc3b5 100644--- a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md@@ -101,8 +101,8 @@ the plugin). External CRS remains advanced-only.- `crs-priority-daemon.mjs` — pool priority / schedulable policy- `crs-429-cooldown.mjs` — rate-limit cooldown-- `crs-401-refresher.mjs` — proactive refresh-- `crs-token-feed.mjs` — vault → pool+- `refresh-tokens.mjs` — identity-verified proactive vault refresh+- `crs-token-feed.mjs` — identity-verified vault → pool publication- `crs-pool-config.mjs`, `crs-health-watch.mjs`, `crs-bedrock-guard.mjs` — optionalThese currently *call* CRS admin APIs. Dual-mode target:diff --git a/claude-ops/scripts/account-rotation/__tests__/model-args.test.mjs b/claude-ops/scripts/account-rotation/__tests__/model-args.test.mjsindex 238e9816..e6b86d7a 100644--- a/claude-ops/scripts/account-rotation/__tests__/model-args.test.mjs+++ b/claude-ops/scripts/account-rotation/__tests__/model-args.test.mjs@@ -1,11 +1,12 @@#!/usr/bin/env nodeimport assert from 'node:assert/strict';-import { chmodSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { spawnSync } from 'node:child_process';import { normalizeClaudeModelArgs, normalizeClaudeModelValue } from '../model-args.mjs';+import { effectiveRouteMatches, routeCredentialFingerprint } from '../bg-respawn.mjs';const accountRotationDir = dirname(fileURLToPath(import.meta.url));const scriptsDir = dirname(accountRotationDir);@@ -67,12 +68,142 @@ assert.ok('launcher normalizes raw CLI args before spawning Claude',);-const respawnSource = readFileSync(join(scriptsDir, 'bg-respawn.mjs'), 'utf8');-assert.match(respawnSource, /const flags = originalFlags \? normalizeClaudeModelArgs\(originalFlags\) : null;/);-assert.ok(- respawnSource.indexOf('state.respawnFlags = flags') <- respawnSource.indexOf("execFileSync(claudeBin(), ['respawn', String(session.id)]"),- 'background respawn persists normalized flags before claude respawn',+function runRespawnCase(mode) {+ const exitCode = mode === 'spawn-failure' ? 7 : 0;+ const home = mkdtempSync(join(tmpdir(), `bg-respawn-${mode}-`));+ const id = `respawn-${process.pid}-${mode}`;+ const jobsDir = join(home, '.claude', 'jobs', id);+ const statePath = join(jobsDir, 'state.json');+ const capturePath = join(home, 'respawn-capture.json');+ const fakeRespawn = join(home, 'bin', 'claude');+ const deferred = `/tmp/claude-respawn-deferred-${id}`;+ const respawned = `/tmp/claude-rotation-respawned-${id}`;+ mkdirSync(jobsDir, { recursive: true });+ mkdirSync(dirname(fakeRespawn), { recursive: true });+ writeFileSync(+ statePath,+ JSON.stringify({ respawnFlags: ['--model', 'claude-fable-5[1m]', '--effort', 'high'] }, null, 2),+ { mode: 0o600 },+ );+ writeFileSync(deferred, 'deferred', { mode: 0o600 });+ rmSync(respawned, { force: true });+ writeFileSync(+ fakeRespawn,+ `#!/bin/sh\nRESPAWN_ARGS="$*" node - <<'NODE'\nconst fs=require('fs');\nconst cp=require('child_process');\nconst path=require('path');\nconst state=JSON.parse(fs.readFileSync(process.env.STATE_PATH,'utf8'));\nfs.writeFileSync(process.env.CAPTURE_PATH, JSON.stringify({ args: process.env.RESPAWN_ARGS.split(' '), state }));\nconst mode=process.env.RESPAWN_TEST_MODE;\nif (mode !== 'spawn-failure' && mode !== 'no-session') {\n let pid=999999;\n if (mode !== 'stale-pid') {\n const child=cp.spawn(process.execPath,['-e','setTimeout(()=>{},10000)'],{detached:true,stdio:'ignore',env:process.env});\n child.unref();\n pid=child.pid;\n fs.writeFileSync(process.env.CHILD_PID_PATH,String(pid));\n }\n const expectedRoute=JSON.parse(process.env.CLAUDE_OPS_EXPECTED_ROUTE);\n const effectiveRoute=mode === 'wrong-route'\n ? {...expectedRoute,mode:'crs'}\n : mode === 'wrong-endpoint'\n ? {...expectedRoute,baseUrl:'https://wrong-relay.example/api'}\n : mode === 'mismatched-credential'\n ? {...expectedRoute,credentialFingerprint:'0'.repeat(64)}\n : expectedRoute;\n fs.mkdirSync(process.env.SESSIONS_DIR,{recursive:true});\n fs.writeFileSync(path.join(process.env.SESSIONS_DIR,pid+'.json'),JSON.stringify({kind:'bg',jobId:process.env.SESSION_ID,pid,status:'waiting',effectiveRoute}));\n}\nNODE\nexit ${exitCode}\n`,+ { mode: 0o700 },+ );+ const result = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import { doRespawn } from ${JSON.stringify(new URL('../bg-respawn.mjs', import.meta.url).href)};\n` ++ `const logs=[]; const ok=doRespawn({id:${JSON.stringify(id)},pid:999999,status:'waiting'}, (m)=>logs.push(m));\n` ++ `console.log(JSON.stringify({ok,logs}));`,+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ HOME: home,+ CLAUDE_BIN: fakeRespawn,+ STATE_PATH: statePath,+ CAPTURE_PATH: capturePath,+ RESPAWN_TEST_MODE: mode,+ SESSION_ID: id,+ SESSIONS_DIR: join(home, '.claude', 'sessions'),+ CHILD_PID_PATH: join(home, 'child.pid'),+ CLAUDE_ROTATION_SESSION_STAGGER_MS: '0',+ CLAUDE_CODE_OAUTH_TOKEN: 'direct-test-token',+ },+ },+ );+ assert.equal(result.status, 0, result.stderr);+ const outcome = JSON.parse(result.stdout.trim().split('\n').at(-1));+ const captured = JSON.parse(readFileSync(capturePath, 'utf8'));+ const childPidPath = join(home, 'child.pid');+ const childPid = existsSync(childPidPath) ? Number(readFileSync(childPidPath, 'utf8')) : null;+ return {+ outcome,+ captured,+ deferred,+ respawned,+ childPid,+ };+}++const failure = runRespawnCase('spawn-failure');+assert.equal(failure.outcome.ok, false);+assert.deepEqual(failure.captured.args, ['respawn', 'respawn-' + process.pid + '-spawn-failure']);+assert.equal(failure.captured.state.respawnFlags.includes('gpt-5.4'), true);+assert.equal(+ failure.captured.state.respawnFlags.some((flag) => /fable/i.test(flag)),+ false,);+assert.equal(existsSync(failure.deferred), true);+assert.equal(existsSync(failure.respawned), false);+assert.equal(+ failure.outcome.logs.some((line) => line.includes('respawned bg session')),+ false,+);+rmSync(failure.deferred, { force: true });++for (const mode of ['no-session', 'stale-pid', 'wrong-route', 'wrong-endpoint', 'mismatched-credential']) {+ const invalid = runRespawnCase(mode);+ assert.equal(invalid.outcome.ok, false, mode);+ assert.equal(existsSync(invalid.deferred), true, mode);+ assert.equal(existsSync(invalid.respawned), false, mode);+ if (invalid.childPid) {+ try {+ process.kill(invalid.childPid, 'SIGTERM');+ } catch {}+ }+ rmSync(invalid.deferred, { force: true });+}++const directToken = 'direct-test-token';+const directRoute = {+ mode: 'direct',+ baseUrl: null,+ credentialSource: 'session-oauth',+ credentialFingerprint: routeCredentialFingerprint(directToken),+ settings: null,+};+const crsRoute = {+ mode: 'crs',+ baseUrl: 'http://127.0.0.1:3005/api',+ credentialSource: 'crs-relay',+ credentialFingerprint: routeCredentialFingerprint('cr_test-relay'),+ settings: '/tmp/crs-session-settings.json',+};+assert.equal(effectiveRouteMatches({ ...crsRoute, baseUrl: 'http://127.0.0.1:3002/api' }, crsRoute), false);+assert.equal(+ effectiveRouteMatches({ ...crsRoute, credentialFingerprint: routeCredentialFingerprint(directToken) }, crsRoute),+ false,+);+assert.equal(effectiveRouteMatches({ ...directRoute, credentialSource: 'keychain' }, directRoute), false);+assert.equal(effectiveRouteMatches({ ...directRoute, credentialFingerprint: null }, directRoute), false);+assert.equal(effectiveRouteMatches({ ...crsRoute }, crsRoute), true);+assert.equal(effectiveRouteMatches({ ...directRoute }, directRoute), true);++const success = runRespawnCase('success');+assert.equal(success.outcome.ok, true);+assert.equal(success.captured.state.respawnFlags.includes('gpt-5.4'), true);+assert.equal(+ success.captured.state.respawnFlags.some((flag) => /fable/i.test(flag)),+ false,+);+assert.equal(existsSync(success.deferred), false);+assert.equal(existsSync(success.respawned), true);+assert.equal(+ success.outcome.logs.some((line) => line.includes('respawned bg session')),+ true,+);+if (success.childPid) {+ try {+ process.kill(success.childPid, 'SIGTERM');+ } catch {}+}+rmSync(success.respawned, { force: true });console.log('Claude model argument normalization tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/production-recovery.test.mjs b/claude-ops/scripts/account-rotation/__tests__/production-recovery.test.mjsnew file mode 100644index 00000000..208b5b30--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/production-recovery.test.mjs@@ -0,0 +1,259 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { retryAfterDelayMs } from '../retry-after.mjs';++const cooldownScript = new URL('../crs-429-cooldown.mjs', import.meta.url);+const priorityScript = new URL('../crs-priority-daemon.mjs', import.meta.url);+const retired401Script = new URL('../crs-401-refresher.mjs', import.meta.url);++function run(script, env, args = []) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [script.pathname, ...args], { env: { ...process.env, ...env } });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (chunk) => (stdout += chunk));+ child.stderr.on('data', (chunk) => (stderr += chunk));+ child.once('error', reject);+ child.once('close', (status) => resolve({ status, stdout, stderr }));+ });+}++function startFixture(initialAccounts, toggleStatuses = []) {+ let accounts = structuredClone(initialAccounts);+ const toggles = [];+ const queuedToggleStatuses = [...toggleStatuses];+ const server = createServer(async (req, res) => {+ let body = '';+ for await (const chunk of req) body += chunk;+ const json = (status, value) => {+ const text = JSON.stringify(value);+ res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(text) });+ res.end(text);+ };+ if (req.url === '/web/auth/login' && req.method === 'POST') return json(200, { token: 'fixture-admin' });+ if (req.url === '/admin/claude-accounts' && req.method === 'GET') return json(200, accounts);+ const toggle = req.url?.match(/^\/admin\/claude-accounts\/([^/]+)\/toggle-schedulable$/);+ if (toggle && req.method === 'PUT') {+ const update = JSON.parse(body || '{}');+ const status = queuedToggleStatuses.shift() ?? 200;+ toggles.push({ id: toggle[1], update, status });+ if (status >= 200 && status < 300) {+ accounts = accounts.map((account) =>+ account.id === toggle[1]+ ? {+ ...account,+ schedulable: update.schedulable,+ rateLimitEndAt: update.rateLimitEndAt ?? account.rateLimitEndAt,+ rateLimitReason: update.rateLimitReason ?? account.rateLimitReason,+ }+ : account,+ );+ }+ return json(status, { success: status >= 200 && status < 300 });+ }+ if (req.url?.endsWith('/reset-status') && req.method === 'POST') return json(200, { success: true });+ if (req.url?.startsWith('/admin/claude-accounts/') && req.method === 'PUT') return json(200, { success: true });+ return json(404, { error: 'not found' });+ });+ return new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ resolve({+ base: `http://127.0.0.1:${server.address().port}`,+ close: () => new Promise((done) => server.close(done)),+ toggles,+ });+ });+ });+}++assert.equal(retryAfterDelayMs('7', 0), 9_000);+assert.equal(retryAfterDelayMs(new Date(12_000).toUTCString(), 0), 14_000);+assert.equal(retryAfterDelayMs('invalid-date', 0), 60_000);+assert.equal(retryAfterDelayMs(null, 0), null);++function fixtureEnv(root, base, config) {+ const configPath = join(root, 'config.json');+ writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });+ return {+ HOME: root,+ CLAUDE_ROTATOR_CONFIG: configPath,+ CLAUDE_PLUGIN_DATA_DIR: join(root, 'data'),+ CRS_BASE: base,+ CRS_ADMIN_PASSWORD: 'fixture-password',+ OPS_ACCOUNTS_BACKEND: 'crs',+ OPS_ACCOUNTS_DUAL_WRITE: '0',+ };+}++{+ const root = mkdtempSync(join(tmpdir(), 'retired-401-'));+ const configPath = join(root, 'config.json');+ writeFileSync(configPath, JSON.stringify({ accounts: [], crs: {} }), { mode: 0o600 });+ const result = await run(retired401Script, { HOME: root, CLAUDE_ROTATOR_CONFIG: configPath });+ assert.notEqual(result.status, 0);+ assert.match(`${result.stdout}${result.stderr}`, /RETIRED_USE_VERIFIED_TOKEN_FEED/);+}++{+ const root = mkdtempSync(join(tmpdir(), 'cooldown-recovery-'));+ mkdirSync(join(root, 'state'), { recursive: true });+ const resetAt = new Date(Date.now() + 60_000).toISOString();+ const fixture = await startFixture([+ {+ id: 'limited',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: true,+ rateLimitStatus: { isRateLimited: true, minutesRemaining: 1, rateLimitEndAt: resetAt },+ },+ ]);+ const statePath = join(root, 'state', 'crs-429-state.json');+ const env = {+ ...fixtureEnv(root, fixture.base, { accounts: [], crs: { cooldownEnabled: true } }),+ CRS_COOLDOWN_ENABLED: '1',+ CRS_COOLDOWN_STATE_PATH: statePath,+ };+ try {+ const held = await run(cooldownScript, env);+ assert.equal(held.status, 0, held.stderr);+ assert.equal(fixture.toggles.at(-1)?.update.schedulable, false);+ const state = JSON.parse(readFileSync(statePath, 'utf8'));+ assert.equal(state.limited.cooldownUntil > Date.now(), true);++ state.limited.cooldownUntil = Date.now() - 1;+ writeFileSync(statePath, JSON.stringify(state), { mode: 0o600 });+ const released = await startFixture([+ {+ id: 'limited',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: false,+ rateLimitStatus: { isRateLimited: false },+ },+ ]);+ try {+ const releaseEnv = { ...env, CRS_BASE: released.base };+ const result = await run(cooldownScript, releaseEnv);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(released.toggles.at(-1)?.update.schedulable, true);+ assert.equal(JSON.parse(readFileSync(statePath, 'utf8')).limited, undefined);+ } finally {+ await released.close();+ }+ } finally {+ await fixture.close();+ }+}++{+ const root = mkdtempSync(join(tmpdir(), 'cooldown-toggle-failure-'));+ mkdirSync(join(root, 'state'), { recursive: true });+ const statePath = join(root, 'state', 'crs-429-state.json');+ const resetAt = new Date(Date.now() + 60_000).toISOString();+ const holdFixture = await startFixture(+ [+ {+ id: 'limited',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: true,+ rateLimitStatus: { isRateLimited: true, minutesRemaining: 1, rateLimitEndAt: resetAt },+ },+ ],+ [503],+ );+ const env = {+ ...fixtureEnv(root, holdFixture.base, { accounts: [], crs: { cooldownEnabled: true } }),+ CRS_COOLDOWN_ENABLED: '1',+ CRS_COOLDOWN_STATE_PATH: statePath,+ };+ try {+ const result = await run(cooldownScript, env);+ assert.equal(result.status, 0, result.stderr);+ const held = JSON.parse(readFileSync(statePath, 'utf8')).limited;+ assert.equal(held.retryAction, 'hold');+ assert.equal(held.lastToggleStatus, 503);+ } finally {+ await holdFixture.close();+ }++ const expired = JSON.parse(readFileSync(statePath, 'utf8'));+ expired.limited.cooldownUntil = Date.now() - 1;+ writeFileSync(statePath, JSON.stringify(expired), { mode: 0o600 });+ const releaseFixture = await startFixture(+ [+ {+ id: 'limited',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: false,+ rateLimitStatus: { isRateLimited: false },+ },+ ],+ [502],+ );+ try {+ const result = await run(cooldownScript, { ...env, CRS_BASE: releaseFixture.base });+ assert.equal(result.status, 0, result.stderr);+ const retained = JSON.parse(readFileSync(statePath, 'utf8')).limited;+ assert.equal(retained.retryAction, 'release');+ assert.equal(retained.lastToggleStatus, 502);+ } finally {+ await releaseFixture.close();+ }+}++{+ const root = mkdtempSync(join(tmpdir(), 'priority-auth-recovery-'));+ const fixture = await startFixture([+ {+ id: 'invalid-1',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: true,+ status: 'auth_repair',+ tokenExpiresAt: Date.now() - 1,+ lastError: 'HTTP 401 authentication_error invalid token',+ },+ {+ id: 'invalid-2',+ name: '[email protected]',+ platform: 'claude',+ isActive: true,+ schedulable: true,+ tokenExpiresAt: Date.now() - 1,+ errorMessage: '403 revoked credential',+ },+ ]);+ const env = {+ ...fixtureEnv(root, fixture.base, { accounts: [], crs: { enabled: true, policy: 'conservative', floor: 2 } }),+ CRS_FLOOR: '2',+ CRS_LIVE_USAGE_TTL_MS: '1',+ };+ try {+ const result = await run(priorityScript, env);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(fixture.toggles.length, 2);+ assert.equal(+ fixture.toggles.every((entry) => entry.update.schedulable === false),+ true,+ );+ assert.match(result.stdout, /all active Claude accounts unavailable; leaving pool honestly unschedulable/);+ assert.match(result.stdout, /schedulable=0/);+ } finally {+ await fixture.close();+ }+}++console.log('Production 401/429 recovery tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/refresh-lock.test.mjs b/claude-ops/scripts/account-rotation/__tests__/refresh-lock.test.mjsnew file mode 100644index 00000000..f49c27cb--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/refresh-lock.test.mjs@@ -0,0 +1,29 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const lockDir = mkdtempSync(join(tmpdir(), 'refresh-lock-owner-'));+process.env.CRS_REFRESH_LOCK_DIR = lockDir;+process.env.CRS_REFRESH_LOCK_TTL_SEC = '0.15';+const { acquireRefreshLock } = await import(`../crs-refresh-lock.mjs?test=${Date.now()}`);++const release = acquireRefreshLock('[email protected]');+assert.ok(release);+const lockPath = join(lockDir, '[email protected]');+const old = JSON.parse(readFileSync(lockPath, 'utf8'));+await new Promise((resolve) => setTimeout(resolve, 180));+writeFileSync(lockPath, JSON.stringify({ ...old, ownerNonce: 'replacement-owner', renewedAt: Date.now() }), {+ mode: 0o600,+});+assert.equal(release(), false);+assert.equal(JSON.parse(readFileSync(lockPath, 'utf8')).ownerNonce, 'replacement-owner');++const longRelease = acquireRefreshLock('[email protected]');+assert.ok(longRelease);+await new Promise((resolve) => setTimeout(resolve, 400));+assert.equal(acquireRefreshLock('[email protected]'), null);+assert.equal(longRelease(), true);++console.log('Refresh lock ownership and heartbeat tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/refresh-pacing-worker.mjs b/claude-ops/scripts/account-rotation/__tests__/refresh-pacing-worker.mjsnew file mode 100644index 00000000..60123640--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/refresh-pacing-worker.mjs@@ -0,0 +1,7 @@+#!/usr/bin/env node+import { claimRefreshPace } from '../crs-refresh-lock.mjs';++const key = process.argv[2];+const now = Number(process.argv[3]);+const value = claimRefreshPace(key, now, () => 0);+console.log(String(value));diff --git a/claude-ops/scripts/account-rotation/__tests__/refresh-pacing.test.mjs b/claude-ops/scripts/account-rotation/__tests__/refresh-pacing.test.mjsnew file mode 100644index 00000000..76ee564e--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/refresh-pacing.test.mjs@@ -0,0 +1,64 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawn } from 'node:child_process';++const lockDir = mkdtempSync(join(tmpdir(), 'refresh-pacing-'));+const worker = new URL('./refresh-pacing-worker.mjs', import.meta.url);+const now = 1_000_000;+const env = {+ ...process.env,+ CRS_REFRESH_LOCK_DIR: lockDir,+ CRS_REFRESH_MIN_PACE_MS: '40',+ CRS_REFRESH_JITTER_MS: '0',+ CRS_REFRESH_TEST_ALLOW_ZERO_PACE: '1',+};++function runWorker() {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [worker.pathname, '[email protected]', String(now)], { env });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (chunk) => (stdout += chunk));+ child.stderr.on('data', (chunk) => (stderr += chunk));+ child.on('error', reject);+ child.on('close', (code) => {+ if (code !== 0) reject(new Error(stderr || `worker exit ${code}`));+ else resolve(Number(stdout.trim()));+ });+ });+}++const waits = await Promise.all(Array.from({ length: 6 }, runWorker));+const claimed = waits.filter((value) => Number.isFinite(value) && value >= 0).sort((a, b) => a - b);+assert.equal(claimed.length >= 2, true, waits);+assert.equal(claimed[0], 0);+for (let i = 1; i < claimed.length; i += 1) {+ assert.equal(claimed[i] >= claimed[i - 1] + 40, true, claimed);+}+const paceState = JSON.parse(readFileSync(join(lockDir, '[email protected]'), 'utf8'));+assert.equal(paceState.nextEligibleAt >= now + claimed.length * 40, true);++const productionLockDir = mkdtempSync(join(tmpdir(), 'refresh-production-min-'));+const production = await new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [worker.pathname, '[email protected]', String(now)], {+ env: {+ ...process.env,+ CRS_REFRESH_LOCK_DIR: productionLockDir,+ CRS_REFRESH_MIN_PACE_MS: '0',+ CRS_REFRESH_JITTER_MS: '0',+ CRS_REFRESH_TEST_ALLOW_ZERO_PACE: '0',+ },+ });+ let stderr = '';+ child.stderr.on('data', (chunk) => (stderr += chunk));+ child.on('error', reject);+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(stderr || `worker exit ${code}`))));+});+void production;+const productionState = JSON.parse(readFileSync(join(productionLockDir, '[email protected]'), 'utf8'));+assert.equal(productionState.nextEligibleAt >= now + 1_000, true);++console.log('Refresh pacing contention tests: PASS');diff --git a/claude-ops/scripts/account-rotation/bg-respawn.mjs b/claude-ops/scripts/account-rotation/bg-respawn.mjsindex ab2161e5..172d1ee6 100644--- a/claude-ops/scripts/account-rotation/bg-respawn.mjs+++ b/claude-ops/scripts/account-rotation/bg-respawn.mjs@@ -21,8 +21,21 @@ import { normalizeClaudeModelArgs } from './model-args.mjs';//// Used by rotate.mjs (post-rotation) and daemon.mjs (periodic deferred sweep).-import { readFileSync, readdirSync, writeFileSync, appendFileSync, unlinkSync, statSync, existsSync } from 'fs';+import {+ closeSync,+ fsyncSync,+ openSync,+ readFileSync,+ readdirSync,+ renameSync,+ writeFileSync,+ appendFileSync,+ unlinkSync,+ statSync,+ existsSync,+} from 'fs';import { execFileSync, execSync } from 'child_process';+import { createHash } from 'crypto';import { join, dirname } from 'path';import { homedir } from 'os';import { fileURLToPath } from 'url';@@ -149,6 +162,181 @@ function markerFresh(path, maxAgeMs) {}}+function preserveDeferredMarker(id) {+ try {+ writeFileSync(DEFERRED_MARKER(id), String(Date.now()), { mode: 0o600 });+ } catch {}+}++function activeKeychainAccessToken() {+ try {+ if (process.platform === 'linux') {+ const store = JSON.parse(readFileSync(join(homedir(), '.claude', '.credentials.json'), 'utf8'));+ return store?.claudeAiOauth?.accessToken || null;+ }+ const account = process.env.USER || 'unknown';+ const raw = execFileSync(+ 'security',+ ['find-generic-password', '-s', 'Claude Code-credentials', '-a', account, '-w'],+ { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] },+ ).trim();+ return JSON.parse(raw)?.claudeAiOauth?.accessToken || null;+ } catch {+ return null;+ }+}++function writeJsonAtomic(path, value) {+ const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;+ const fd = openSync(tmp, 'wx', 0o600);+ try {+ writeFileSync(fd, JSON.stringify(value, null, 2));+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ renameSync(tmp, path);+}++function respawnStateCoherent(stateFile, expectedCrsActive) {+ try {+ const persisted = JSON.parse(readFileSync(stateFile, 'utf8'));+ if (!Array.isArray(persisted.respawnFlags)) return expectedCrsActive === false;+ const normalized = normalizeClaudeModelArgs(persisted.respawnFlags);+ if (!normalized.every((flag, index) => flag === persisted.respawnFlags[index])) return false;+ const hasCrsSettings = persisted.respawnFlags.some(+ (flag, index) =>+ flag === '--settings' && String(persisted.respawnFlags[index + 1] || '').endsWith('crs-session-settings.json'),+ );+ return hasCrsSettings === expectedCrsActive;+ } catch {+ return false;+ }+}++export function routeCredentialFingerprint(token) {+ if (!token) return null;+ return createHash('sha256').update('bg-respawn-route\0').update(String(token)).digest('hex');+}++function normalizedRoute(route) {+ if (!route || typeof route !== 'object') return null;+ return {+ mode: String(route.mode || ''),+ baseUrl: route.baseUrl ? String(route.baseUrl).replace(/\/+$/, '') : null,+ credentialSource: String(route.credentialSource || ''),+ credentialFingerprint: route.credentialFingerprint ? String(route.credentialFingerprint) : null,+ settings: route.settings ? String(route.settings) : null,+ };+}++export function effectiveRouteMatches(actual, expected) {+ const left = normalizedRoute(actual);+ const right = normalizedRoute(expected);+ if (!left || !right) return false;+ return (+ left.mode === right.mode &&+ left.baseUrl === right.baseUrl &&+ left.credentialSource === right.credentialSource &&+ left.credentialFingerprint === right.credentialFingerprint &&+ left.settings === right.settings+ );+}++function processEnvironment(pid) {+ try {+ if (process.platform === 'linux') {+ return readFileSync(`/proc/${pid}/environ`)+ .toString()+ .split('\0')+ .filter(Boolean)+ .reduce((env, entry) => {+ const split = entry.indexOf('=');+ if (split > 0) env[entry.slice(0, split)] = entry.slice(split + 1);+ return env;+ }, {});+ }+ const command = execFileSync('ps', ['eww', '-p', String(pid), '-o', 'command='], {+ encoding: 'utf8',+ timeout: 3000,+ });+ const env = {};+ for (const entry of command.split(/\s+/)) {+ const split = entry.indexOf('=');+ if (split <= 0) continue;+ const key = entry.slice(0, split);+ if (+ [+ 'ANTHROPIC_BASE_URL',+ 'ANTHROPIC_API_BASE',+ 'ANTHROPIC_API_KEY',+ 'ANTHROPIC_AUTH_TOKEN',+ 'CLAUDE_CODE_OAUTH_TOKEN',+ ].includes(key)+ ) {+ env[key] = entry.slice(split + 1);+ }+ }+ return env;+ } catch {+ return null;+ }+}++export function effectiveRouteFromProcess(pid, expectedSettings) {+ const env = processEnvironment(pid);+ if (!env) return null;+ const baseUrl = String(env.ANTHROPIC_BASE_URL || '');+ const apiBase = String(env.ANTHROPIC_API_BASE || '');+ if (baseUrl && apiBase && baseUrl !== apiBase) return null;+ const effectiveBase = baseUrl || apiBase || null;+ const tokens = [env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN, env.CLAUDE_CODE_OAUTH_TOKEN].filter(Boolean);+ if (effectiveBase) {+ if (!tokens.length || tokens.some((token) => token !== tokens[0] || !String(token).startsWith('cr_'))) return null;+ return {+ mode: 'crs',+ baseUrl: effectiveBase,+ credentialSource: 'crs-relay',+ credentialFingerprint: routeCredentialFingerprint(tokens[0]),+ settings: expectedSettings,+ };+ }+ if (tokens.some((token) => String(token).startsWith('cr_'))) return null;+ const directToken = tokens[0] || activeKeychainAccessToken();+ if (!directToken || tokens.some((token) => token !== directToken)) return null;+ return {+ mode: 'direct',+ baseUrl: null,+ credentialSource: tokens.length ? 'session-oauth' : 'keychain',+ credentialFingerprint: routeCredentialFingerprint(directToken),+ settings: null,+ };+}++function findNewLiveSession(id, oldPid, expectedRoute) {+ const found = listLiveBgSessions().find(+ (candidate) => String(candidate.id) === String(id) && candidate.pid !== oldPid && pidAlive(candidate.pid),+ );+ if (!found) return null;+ try {+ const sessionFile = readdirSync(SESSIONS_DIR)+ .filter((file) => file.endsWith('.json'))+ .map((file) => join(SESSIONS_DIR, file))+ .find((file) => {+ const value = JSON.parse(readFileSync(file, 'utf8'));+ const valueId = value.jobId || value.sessionId || value.id;+ return String(valueId) === String(id) && Number(value.pid) === found.pid;+ });+ if (!sessionFile) return null;+ const record = JSON.parse(readFileSync(sessionFile, 'utf8'));+ const processRoute = effectiveRouteFromProcess(found.pid, expectedRoute.settings);+ if (!effectiveRouteMatches(processRoute, expectedRoute)) return null;+ return effectiveRouteMatches(record.effectiveRoute, processRoute) ? found : null;+ } catch {+ return null;+ }+}+/** Enumerate live daemon-hosted bg sessions from ~/.claude/sessions/*.json. */export function listLiveBgSessions() {const out = [];@@ -235,11 +423,15 @@ export function doRespawn(session, log, opts = {}) {try {const childEnv = { ...process.env };+ let selectedDirectToken = null;+ let directCredentialSource = 'keychain';try {const config = readConfig();const tokenJson = getTokenForSession(session.id, config);const token = tokenJson ? extractAccessToken(tokenJson) : null;if (token) {+ selectedDirectToken = token;+ directCredentialSource = 'session-oauth';childEnv.CLAUDE_CODE_OAUTH_TOKEN = token;delete childEnv.CLAUDE_CODE_USE_BEDROCK;delete childEnv.ANTHROPIC_MODEL;@@ -420,6 +612,8 @@ export function doRespawn(session, log, opts = {}) {kc = tokenJson ? extractAccessToken(tokenJson) : null;} catch {}if (kc) {+ selectedDirectToken = kc;+ directCredentialSource = 'session-oauth';delete childEnv.ANTHROPIC_API_KEY;delete childEnv.ANTHROPIC_AUTH_TOKEN;childEnv.CLAUDE_CODE_OAUTH_TOKEN = kc;@@ -436,6 +630,42 @@ export function doRespawn(session, log, opts = {}) {}}+ if (!crsActive) {+ delete childEnv.ANTHROPIC_BASE_URL;+ delete childEnv.ANTHROPIC_API_BASE;+ delete childEnv.ANTHROPIC_API_KEY;+ delete childEnv.ANTHROPIC_AUTH_TOKEN;+ const effectiveEnvToken = String(childEnv.CLAUDE_CODE_OAUTH_TOKEN || '');+ if (effectiveEnvToken && !effectiveEnvToken.startsWith('cr_')) {+ selectedDirectToken = effectiveEnvToken;+ directCredentialSource = 'session-oauth';+ } else if (!selectedDirectToken) {+ selectedDirectToken = activeKeychainAccessToken();+ directCredentialSource = 'keychain';+ }+ if (!selectedDirectToken) {+ preserveDeferredMarker(session.id);+ log(`[bg-respawn] cannot fingerprint intended direct credential for ${session.id}; deferring retry`);+ return false;+ }+ }+ const expectedRoute = crsActive+ ? {+ mode: 'crs',+ baseUrl: crsBaseUrl,+ credentialSource: 'crs-relay',+ credentialFingerprint: routeCredentialFingerprint(crsRelayKey),+ settings: join(homedir(), '.claude', 'crs-session-settings.json'),+ }+ : {+ mode: 'direct',+ baseUrl: null,+ credentialSource: directCredentialSource,+ credentialFingerprint: routeCredentialFingerprint(selectedDirectToken),+ settings: null,+ };+ childEnv.CLAUDE_OPS_EXPECTED_ROUTE = JSON.stringify(expectedRoute);+// ── RESPAWN-FLAG RECONCILIATION (durable: base+token can't separate) ─────// `--settings crs-session-settings.json` injects ANTHROPIC_BASE_URL=CRS at// process startup, which childEnv stripping cannot undo. Make the allowlist@@ -471,10 +701,7 @@ export function doRespawn(session, log, opts = {}) {}if (mutated) {state.respawnFlags = flags;- // Rewrite in place, so no exclusive create here. The mode only bites if- // the file has gone since we read it, and keeps the replacement from- // coming back world-readable when it does.- writeFileSync(stateFile, JSON.stringify(state, null, 2), { mode: 0o600 });+ writeJsonAtomic(stateFile, state);}}} catch (err) {@@ -489,53 +716,58 @@ export function doRespawn(session, log, opts = {}) {env: childEnv,}).toString();} catch (e) {- // Capture any output the binary emitted on failure (model errors etc) to our log, not controlling tty.try {- respawnOut = (e.stdout || '') + (e.stderr || '');+ respawnOut = Buffer.concat(+ [e.stdout, e.stderr]+ .filter((part) => part !== undefined && part !== null)+ .map((part) => (Buffer.isBuffer(part) ? part : Buffer.from(String(part)))),+ ).toString();} catch {}- log(`[bg-respawn] respawn exec note for ${session.id}: ${String(e.message || e).slice(0, 120)}`);- // Do not re-throw; we still want to mark and continue fleet hygiene.+ if (respawnOut) {+ try {+ const LOGP = join(__dirname, 'bg-respawn.out.log');+ appendFileSync(LOGP, `[${new Date().toISOString()}] ${session.id}: ${respawnOut.slice(0, 2000)}\n`);+ } catch {}+ }+ preserveDeferredMarker(session.id);+ log(`[bg-respawn] respawn command failed for ${session.id}: ${String(e.message || e).slice(0, 120)}`);+ return false;}if (respawnOut && respawnOut.length > 0) {- // Persist any chatter from the respawn to dedicated log to avoid TUI pollution.try {const LOGP = join(__dirname, 'bg-respawn.out.log');appendFileSync(LOGP, `[${new Date().toISOString()}] ${session.id}: ${respawnOut.slice(0, 2000)}\n`);} catch {}}+ if (!respawnStateCoherent(stateFile, crsActive)) {+ preserveDeferredMarker(session.id);+ log(`[bg-respawn] respawn state verification failed for ${session.id}; deferring retry`);+ return false;+ }+ let liveRespawn = null;+ for (let i = 0; i < 20; i++) {+ liveRespawn = findNewLiveSession(session.id, session.pid, expectedRoute);+ if (liveRespawn) break;+ sleepSync(100);+ }+ if (!liveRespawn) {+ preserveDeferredMarker(session.id);+ log(`[bg-respawn] no verified new live PID/effective route for ${session.id}; deferring retry`);+ return false;+ }try {- // mode keeps the marker owner-only; the path under /tmp is predictable.writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()), { mode: 0o600 });} catch {}try {unlinkSync(DEFERRED_MARKER(session.id));} catch {}- log(`[bg-respawn] respawned bg session ${session.id} (pid ${session.pid}, was ${session.status})`);+ log(+ `[bg-respawn] respawned bg session ${session.id} (new pid ${liveRespawn.pid}, old pid ${session.pid}, was ${session.status})`,+ );- // Synchronously resolve new PID and update the leasetry {- const leases = readLeases();- const lease = leases[session.id];- if (lease) {- let newPid = null;- for (let i = 0; i < 20; i++) {- try {- execSync('sleep 0.5');- } catch {}- const live = listLiveBgSessions();- const found = live.find((ls) => String(ls.id) === String(session.id));- if (found && found.pid !== session.pid) {- newPid = found.pid;- break;- }- }- if (newPid) {- log(`[bg-respawn] Updated lease for session ${session.id} with new PID ${newPid}`);- recordSessionLease(session.id, lease.accountKey, newPid);- } else {- log(`[bg-respawn] Warning: could not resolve new PID for session ${session.id}`);- }- }+ const lease = readLeases()[session.id];+ if (lease) recordSessionLease(session.id, lease.accountKey, liveRespawn.pid);} catch (err) {log(`[bg-respawn] Error updating lease with new PID: ${err.message}`);}diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.jsonindex 8c4ce6d7..7176715e 100644--- a/claude-ops/scripts/account-rotation/config.example.json+++ b/claude-ops/scripts/account-rotation/config.example.json@@ -57,16 +57,10 @@"errorLogCooldownMs": 300000,"_errorLog_note": "errorLogWindowMs: how far back crs-429-cooldown.mjs scans the log for a 429 hit. errorLogCooldownMs: how long a log-only hit holds an account before rateLimitStatus itself would (default 5m each).","stateDir": null,- "_stateDir_note": "Optional absolute path (no ~ expansion), shared base directory for both crs-401-refresher.mjs and crs-429-cooldown.mjs's own state/manual-disable files (crs-401-state.json, crs-429-state.json, crs-manual-disable.json — never one shared file). Defaults to <plugin-data-dir>/account-rotation if unset.",- "cooldownStatePath": null,- "_cooldownStatePath_note": "Optional: path to a separate 429/rate-limit reconciler's state file, read-only, so crs-401-refresher.mjs's re-enable sweep doesn't fight a genuine rate-limit window. Leave null if you don't run one — treated as 'no known windows', never an error. NEVER point this at the same file crs-401-refresher.mjs writes (crs-401-state.json) — each reconciler must own its own state file.",+ "_stateDir_note": "Optional absolute path (no ~ expansion) for crs-429-cooldown.mjs state/manual-disable files (crs-429-state.json, crs-manual-disable.json). Defaults to <plugin-data-dir>/account-rotation if unset.","manualDisableEnabled": true,"cooldownEnabled": false,"_cooldownEnabled_note": "Off by default (or $CRS_COOLDOWN_ENABLED=1). Turns on crs-429-cooldown.mjs, a fast (1min-cadence) reconciler that holds an account out of rotation only on a real rateLimitStatus.isRateLimited=true from CRS (plus the optional error-log lead signal under logDir/logTzOffset above) — never on utilization. Own state file at <stateDir>/crs-429-state.json.",- "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).","enableMagicLinkRecovery": false,"_enableMagicLinkRecovery_note": "Deprecated and fail-closed. Unattended reauthentication is disabled; use the signed staged-enrollment workflow. No environment variable re-enables direct auth writes.","magicLinkRetryCooldownMs": 21600000,diff --git a/claude-ops/scripts/account-rotation/crs-401-refresher.mjs b/claude-ops/scripts/account-rotation/crs-401-refresher.mjsindex b99d4287..3743ae34 100644--- a/claude-ops/scripts/account-rotation/crs-401-refresher.mjs+++ b/claude-ops/scripts/account-rotation/crs-401-refresher.mjs@@ -1,380 +1,11 @@#!/usr/bin/env node-// crs-401-refresher.mjs — CRS pool OAuth-token auto-heal (fixes a live-authentication_error-// gap that crs-priority-daemon.mjs does not cover).-//-// OPT-IN. Does nothing (exits 0) unless crs.tokenRefreshEnabled is true (or-// $CRS_TOKEN_REFRESH_ENABLED=1) — installing this plugin never silently starts a new-// daemon.-//-// Gap this fills: crs-priority-daemon.mjs sidelines accounts with a stale/expiring-// OAuth token (it will not schedule them), but nothing proactively refreshes the CRS-// pool's OWN copy of each account's OAuth access token. Once an access token expires-// with nobody refreshing it, every completion routed to that account returns Anthropic-// `authentication_error` (HTTP 401) and any in-flight session gets no response — a pool-// account can go from "healthy" to "silently 401ing" between priority-daemon ticks.-//-// This closes that gap headlessly (no browser) using CRS's own server-side-// refresh_token grant endpoint: POST /admin/claude-accounts/:id/refresh-//-// Each tick:-// 1. Admin-login to CRS.-// 2. List claude accounts.-// 3. For any account whose access token is expired or expires within-// REFRESH_WINDOW_MS, OR that is currently sidelined (schedulable=false), call the-// refresh endpoint.-// 4. On success -> ensure schedulable=true (revive) and clear needs-reauth.-// On failure (dead refresh_token) -> record needs-reauth in this reconciler's OWN-// state file; leave the account for a human/magic-link re-auth path. We do NOT-// hard-disable a healthy account here — crs-priority-daemon.mjs owns scheduling;-// this reconciler only revives on a successful refresh, or sidelines a CONFIRMED-// dead token (never a transient failure on a still-fresh token).-//-// State is owned exclusively by THIS reconciler (own file, atomic write, single-flight-// lock via crs-reconciler-state.mjs) — see that module's header for why a shared state-// file between reconcilers is unsafe.-//-// CONFIG (config.json "crs" block; every key overridable by env — see-// config.example.json for the full annotated schema):-// tokenRefreshEnabled default false — must be true (or $CRS_TOKEN_REFRESH_ENABLED=1)-// baseUrl, adminUser, adminPasswordEnv, containerName — shared with the other CRS-// reconcilers-// tokenRefreshWindowMs default 1800000 (30m) — refresh if expiring within this window-// stateDir default: <plugin-data-dir>/account-rotation. This-// reconciler's own state file lives at-// <stateDir>/crs-401-state.json (never shared with any-// other reconciler's state file).-// cooldownStatePath default: unset. Optional READ-ONLY path to a separate-// rate-limit reconciler's state file (e.g.-// crs-429-cooldown.mjs's <stateDir>/crs-429-state.json) so-// this reconciler's re-enable sweep doesn't fight a-// genuine, still-active rate-limit hold. Never written-// here — only read.-//-// CLI: --dry-run=no writes · --status=print current token/reauth status · --only=<name|id>+// Retired. This file contains no network, credential, or account mutation code.+// Use refresh-tokens.mjs and crs-token-feed.mjs for identity-verified recovery.-import { execFileSync } from 'child_process';-import { readFileSync, existsSync, mkdirSync, appendFileSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';-import { homedir } from 'os';-import { loadJsonState, saveJsonStateAtomic, withOwnStateLock } from './crs-reconciler-state.mjs';-import { crsBaseUrl, loadRotationConfig, resolveCrsAdminPassword } from './crs-pool-config.mjs';-import { resolveAccountsBackend } from './ops-accounts-backend.mjs';--const __dirname = dirname(fileURLToPath(import.meta.url));-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 ONLY = (process.argv.find((a) => a.startsWith('--only=')) || '').slice('--only='.length);--const cfg = loadRotationConfig();-const C = cfg.crs || {};-const num = (v, d) => (v === undefined || v === null || v === '' || Number.isNaN(+v) ? d : +v);--function truthy(v) {- return ['1', 'true', 'yes', 'on'].includes(- String(v ?? '')- .trim()- .toLowerCase(),- );-}--const ENABLED = truthy(process.env.CRS_TOKEN_REFRESH_ENABLED) || C.tokenRefreshEnabled === true;--const BASE = crsBaseUrl(cfg);-const ADMIN_USER = process.env.CRS_ADMIN_USER || C.adminUser || 'cradmin';-const REFRESH_WINDOW_MS = num(process.env.CRS_REFRESH_WINDOW_MS ?? C.tokenRefreshWindowMs, 30 * 60_000);--function expandHome(p) {- return p ? p.replace(/^~(?=$|\/)/, homedir()) : p;-}--const PLUGIN_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(PLUGIN_DATA_DIR, 'account-rotation');-const STATE_PATH = expandHome(process.env.CRS_401_STATE_PATH) || join(STATE_DIR, 'crs-401-state.json');-// Read-only: another reconciler's (e.g. crs-429-cooldown.mjs) own state file, so a-// successful token refresh doesn't re-enable an account that's genuinely rate-limited.-const COOLDOWN_STATE_PATH = expandHome(process.env.CRS_COOLDOWN_STATE_PATH || C.cooldownStatePath) || null;-// This script's OWN operational text log — distinct from crs.logDir (which is the CRS-// relay's error-log directory that crs-429-cooldown.mjs reads from). Env-only override-// to avoid any config-key overlap with that unrelated concept.-const LOG_DIR = expandHome(process.env.CRS_401_LOG_DIR) || join(homedir(), '.claude', 'logs');-const LOG_PATH = join(LOG_DIR, 'crs-401-refresher.log');--const ts = () => new Date().toISOString();-function log(msg) {- const line = `${ts().slice(11, 19)} [crs-401] ${msg}`;- console.log(line);- try {- mkdirSync(LOG_DIR, { recursive: true });- appendFileSync(LOG_PATH, line + '\n');- } catch {}-}--async function jfetch(path, opts = {}) {- const r = await fetch(BASE + path, { signal: AbortSignal.timeout(30_000), ...opts });- const txt = await r.text();- let body;- try {- body = JSON.parse(txt);- } catch {- body = txt;- }- return { status: r.status, body };-}--let adminToken = null;-async function ensureAdmin() {- if (adminToken) return adminToken;- const pw = resolveCrsAdminPassword(cfg, { adminUser: ADMIN_USER });- if (!pw) throw new Error('CRS admin password unavailable (set $CRS_ADMIN_PASSWORD or see crs-pool-config.mjs)');- const r = await jfetch('/web/auth/login', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ username: ADMIN_USER, password: pw }),- });- if (r.status !== 200 || !r.body?.token) throw new Error(`admin login failed (HTTP ${r.status})`);- adminToken = 'Bearer ' + r.body.token;- return adminToken;-}--async function listClaudeAccounts(auth) {- const r = await jfetch('/admin/claude-accounts', { headers: { Authorization: auth } });- const list = Array.isArray(r.body) ? r.body : r.body?.data || r.body?.accounts || [];- return list.filter((a) => a.platform === 'claude' && a.isActive !== false);-}--function tokenExpiryMs(a) {- const v = a.tokenExpiresAt ?? a.expiresAt ?? 0;- const n = Number(v);- return Number.isFinite(n) ? n : 0;-}--function futureMs(v) {- if (!v) return 0;- const n = Number(v);- if (Number.isFinite(n) && n > 0) return n < 10_000_000_000 ? n * 1000 : n;- const t = Date.parse(v);- return Number.isFinite(t) ? t : 0;+const status = process.argv.includes('--status');+if (status) {+ console.log('CRS 401 refresher: retired; use identity-verified token refresh and feed');+ process.exit(0);}--function authoritativeRateLimited(a, nowMs) {- const status = a.rateLimitStatus || {};- const end = futureMs(status.rateLimitEndAt || a.rateLimitEndAt || a.weeklyRateLimitEndAt);- const reason = status.reason || a.rateLimitReason;- return Boolean(- (status.isRateLimited === true || a.rateLimitStatus?.isRateLimited === 'true') &&- end > nowMs &&- String(reason || '').includes('authoritative_reset'),- );-}--function hardHeld(a, nowMs) {- const status = String(a.status || '');- if (['blocked', 'auth_repair', 'error'].includes(status)) return true;- return (- futureMs(- a.rateLimitEndAt || a.rateLimitStatus?.rateLimitEndAt || a.rateLimitStatus?.resetAt || a.weeklyRateLimitEndAt,- ) > nowMs- );-}--// Read-only view of another reconciler's cooldown state (e.g. crs-429-cooldown.mjs).-// Never written here — only consulted so a successful token refresh doesn't flip a-// genuinely rate-limited account back to schedulable=true out from under it.-function externallyHeld(accountId, nowMs) {- if (!COOLDOWN_STATE_PATH || !existsSync(COOLDOWN_STATE_PATH)) return false;- try {- const other = JSON.parse(readFileSync(COOLDOWN_STATE_PATH, 'utf8'));- const entry = other?.[accountId];- return Boolean(entry?.cooldownUntil > nowMs);- } catch {- return false;- }-}--async function refreshAccount(auth, a) {- const MAX_RETRIES = 3;- let lastErr = null;- let lastStatus = null;- let lastRetryAfter = null;- for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {- const r = await fetch(BASE + `/admin/claude-accounts/${a.id}/refresh`, {- method: 'POST',- signal: AbortSignal.timeout(30_000),- headers: { Authorization: auth, 'Content-Type': 'application/json' },- body: '{}',- });- const retryAfterHdr = r.headers.get('retry-after');- lastStatus = r.status;- lastRetryAfter = retryAfterHdr;- if (r.status === 429 && attempt < MAX_RETRIES) {- const delayMs = retryAfterHdr- ? Math.min(15 * 60_000, Math.max(2_000, parseInt(retryAfterHdr, 10) * 1000 + 2000))- : 30_000;- log(- ` ${a.name}: refresh 429 (attempt ${attempt}/${MAX_RETRIES}) — waiting ${Math.round(delayMs / 1000)}s (Retry-After=${retryAfterHdr ?? 'n/a'})...`,- );- await new Promise((r2) => setTimeout(r2, delayMs));- continue;- }- const txt = await r.text();- let body;- try {- body = JSON.parse(txt);- } catch {- body = txt;- }- const ok = r.status === 200 && (body?.success === true || body?.data?.success === true || body?.data?.accessToken);- const err =- body?.message || body?.error?.message || body?.error || (typeof body === 'string' ? body.slice(0, 120) : '');- if (r.status === 200 || attempt === MAX_RETRIES) {- return { ok, status: r.status, err, retryAfter: lastRetryAfter };- }- lastErr = err;- await new Promise((r2) => setTimeout(r2, 5_000));- }- return { ok: false, status: lastStatus ?? 0, err: lastErr ?? 'max retries', retryAfter: lastRetryAfter };-}--async function setSchedulable(auth, a, value) {- const r = await jfetch(`/admin/claude-accounts/${a.id}/toggle-schedulable`, {- method: 'PUT',- headers: { Authorization: auth, 'Content-Type': 'application/json' },- body: JSON.stringify({ schedulable: value }),- });- return r.status === 200;-}--async function tick() {- const nowMs = Date.now();- const state = loadJsonState(STATE_PATH, log);- const auth = await ensureAdmin();- const accounts = await listClaudeAccounts(auth);-- if (STATUS) {- console.log(`CRS token status @ ${BASE} — ${accounts.length} claude accounts`);- for (const a of accounts) {- const exp = tokenExpiryMs(a);- const mins = exp ? Math.round((exp - nowMs) / 60_000) : null;- const flag = state[a.id]?.needsReauth ? ' NEEDS-REAUTH' : '';- const limited = authoritativeRateLimited(a, nowMs) ? ' AUTH-RATE-LIMITED' : '';- console.log(- ` ${a.name.padEnd(26)} sched=${String(a.schedulable !== false).padEnd(5)} exp_in=${mins === null ? '-' : mins + 'm'}${flag}${limited}`,- );- }- return;- }-- const targets = accounts.filter((a) => {- if (hardHeld(a, nowMs)) return false;- if (ONLY) return a.name === ONLY || a.id === ONLY;- const exp = tokenExpiryMs(a);- const expiringSoon = !exp || exp <= nowMs + REFRESH_WINDOW_MS;- const sidelined = a.schedulable === false;- const authLimited = authoritativeRateLimited(a, nowMs);- return expiringSoon || sidelined || authLimited;- });-- if (!targets.length) {- log(`tick: 0 refresh needed (${accounts.length} accounts all fresh > ${REFRESH_WINDOW_MS / 60000}m)`);- if (!DRY) saveJsonStateAtomic(STATE_PATH, state);- return;- }-- let refreshed = 0;- let revived = 0;- let dead = 0;- for (const a of targets) {- const exp = tokenExpiryMs(a);- const mins = exp ? Math.round((exp - nowMs) / 60_000) : null;- const authLimited = authoritativeRateLimited(a, nowMs);- if (DRY) {- log(- `[dry] would ${authLimited ? 'sideline auth-rate-limited' : 'refresh'} ${a.name} (exp_in=${mins === null ? '-' : mins + 'm'}, sched=${a.schedulable !== false})`,- );- continue;- }- if (authLimited) {- if (a.schedulable !== false) {- const off = await setSchedulable(auth, a, false);- log(- `${a.name}: authoritative rate limit until ${a.rateLimitStatus?.rateLimitEndAt || a.rateLimitEndAt} — ${off ? 'SIDELINED' : 'sideline FAILED'}`,- );- } else {- log(`${a.name}: authoritative rate limit already sidelined`);- }- continue;- }- const res = await refreshAccount(auth, a);- if (res.ok) {- refreshed++;- delete state[a.id];- if (a.schedulable === false && externallyHeld(a.id, Date.now())) {- log(`${a.name}: refreshed but leaving sidelined — held by another reconciler's cooldown (rate-limited)`);- } else if (a.schedulable === false && !hardHeld(a, Date.now())) {- const on = await setSchedulable(auth, a, true);- if (on) {- revived++;- log(`${a.name}: refreshed + revived (schedulable=true)`);- } else {- log(`${a.name}: refreshed but re-enable failed`);- }- } else {- log(`${a.name}: refreshed (exp_in was ${mins === null ? '-' : mins + 'm'})`);- }- } else {- dead++;- state[a.id] = {- name: a.name,- needsReauth: true,- lastFailAt: nowMs,- reason: `refresh HTTP ${res.status}: ${res.err}`.slice(0, 160),- };- // A schedulable account with a dead refresh_token AND an expired/near-expired- // access token actively 401s live traffic. Sideline it to protect the pool; a- // human/magic-link re-auth revives it, and the next tick re-enables on a- // successful refresh. We only sideline confirmed-dead + expiring tokens, never- // a transient failure on a still-fresh token.- const expired = !exp || exp <= nowMs + REFRESH_WINDOW_MS;- if (expired && a.schedulable !== false) {- const off = await setSchedulable(auth, a, false);- log(- `${a.name}: refresh FAILED (HTTP ${res.status}: ${res.err}) — dead token, ${off ? 'SIDELINED' : 'sideline FAILED'}, needs full re-auth`,- );- } else {- log(`${a.name}: refresh FAILED (HTTP ${res.status}: ${res.err}) — needs full re-auth`);- }- }- }-- const needsReauth = Object.values(state)- .filter((s) => s?.needsReauth)- .map((s) => s.name);- log(- `tick: refreshed=${refreshed} revived=${revived} dead=${dead}` +- (needsReauth.length ? ` | needs-reauth: ${needsReauth.join(', ')}` : ''),- );- if (!DRY) saveJsonStateAtomic(STATE_PATH, state);-}--async function main() {- if (!STATUS) throw new Error('CRS_401_REFRESHER_RETIRED_USE_VERIFIED_TOKEN_FEED');- const backend = resolveAccountsBackend({ env: process.env, cfgBackend: C.backend });- if (backend === 'local') {- log('backend=local — CRS 401 refresher no-op (vault refresh is rotate.mjs / keychain keepalive)');- return;- }- if (!ENABLED && !STATUS) {- log('crs.tokenRefreshEnabled is not true (and $CRS_TOKEN_REFRESH_ENABLED!=1) — skipping tick (opt-in required)');- return;- }- const outcome = await withOwnStateLock(STATE_PATH, tick, log);- if (outcome.skipped) log('skipped tick: previous run still holds the state lock');-}--main().catch((e) => {- log(`ERROR: ${e.message}`);- process.exit(1);-});+console.error('CRS_401_REFRESHER_RETIRED_USE_VERIFIED_TOKEN_FEED');+process.exit(1);diff --git a/claude-ops/scripts/account-rotation/crs-401-refresher.sh b/claude-ops/scripts/account-rotation/crs-401-refresher.shdeleted file mode 100755index c40cc641..00000000--- a/claude-ops/scripts/account-rotation/crs-401-refresher.sh+++ /dev/null@@ -1,22 +0,0 @@-#!/bin/bash-# crs-401-refresher.sh — single-flight wrapper for crs-401-refresher.mjs.-# Invoked once-per-tick by launchd/systemd (recommended: every 300s — this-# reconciler proactively refreshes tokens ahead of a 30-minute expiry window,-# so a 5-minute cadence has ample margin without hammering CRS).-set -uo pipefail--source "$HOME/.claude/scripts/lib/once.sh" 2>/dev/null || true-type claude_once >/dev/null 2>&1 && { claude_once crs-401-refresher 60 || exit 0; }--DIR="$HOME/.claude/scripts/account-rotation"-LOG="$DIR/crs-401-refresher.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/crs-401-refresher.mjs" >> "$LOG" 2>&1diff --git a/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs b/claude-ops/scripts/account-rotation/crs-429-cooldown.mjsindex b36f3127..419990df 100644--- a/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs+++ b/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs@@ -41,9 +41,9 @@// manualDisablePath default: <stateDir>/crs-manual-disable.json (optional// allow-list of account ids/names to always leave alone)// logDir default: <plugin-data-dir>/account-rotation/crs-logs.-// Shared with crs-401-refresher.mjs — this reconciler-// reads claude-relay-error-<date>.log from here for its-// optional lead signal. Unset -> that signal is disabled+// This reconciler reads claude-relay-error-<date>.log+// from here for its optional lead signal. Unset -> that+// signal is disabled// (rateLimitStatus alone is still a real Anthropic signal// and is sufficient on its own).// logTzOffset default: "+00:00" — offset appended to naive log@@ -103,8 +103,7 @@ const MANUAL_DISABLE_PATH =expandHome(process.env.CRS_MANUAL_DISABLE_PATH || C.manualDisablePath) || join(STATE_DIR, 'crs-manual-disable.json');// Unset by default: the error-log lead signal is opt-in extra sensitivity, not a// required capability. rateLimitStatus alone (signal #1) is a real Anthropic-// signal and is sufficient on its own. Shared logDir/logTzOffset config with-// crs-401-refresher.mjs.+// signal and is sufficient on its own.// Defaults to a real (likely-absent-on-a-fresh-install) path rather than a null// "disabled" sentinel: scanErrorLog() below no-ops safely via existsSync() when// the directory/file isn't there, so this stays a safe no-op until you actually@@ -261,6 +260,18 @@ async function tick() {rateLimitEndAt: new Date(cooldownUntil).toISOString(),rateLimitReason: reason || 'api-rl',});+ if (r.status < 200 || r.status >= 300) {+ state[a.id] = {+ ...state[a.id],+ retryAction: 'hold',+ retryAfter: nowMs + 60_000,+ lastToggleStatus: r.status,+ };+ } else {+ delete state[a.id].retryAction;+ delete state[a.id].retryAfter;+ delete state[a.id].lastToggleStatus;+ }changes.push({name: a.name,action: cur ? 'OFF' : 'HOLD',@@ -279,6 +290,18 @@ async function tick() {rateLimitEndAt: new Date(prevHeld).toISOString(),rateLimitReason: state[a.id]?.reason || 'persisted-api-rl-bench',});+ if (r.status < 200 || r.status >= 300) {+ state[a.id] = {+ ...state[a.id],+ retryAction: 'hold',+ retryAfter: nowMs + 60_000,+ lastToggleStatus: r.status,+ };+ } else {+ delete state[a.id].retryAction;+ delete state[a.id].retryAfter;+ delete state[a.id].lastToggleStatus;+ }changes.push({name: a.name,action: cur ? 'OFF' : 'HOLD',@@ -289,14 +312,25 @@ async function tick() {changes.push({ name: a.name, action: '[dry]HOLD', reason: 'persisted cooldown', http: '-' });}} else if (prevHeld && prevHeld <= nowMs) {- delete state[a.id];if (!cur) {if (DRY) {changes.push({ name: a.name, action: '[dry]ON', reason: 'cooldown expired', http: '-' });} else {const r = await toggle(auth, a.id, true);+ if (r.status >= 200 && r.status < 300) {+ delete state[a.id];+ } else {+ state[a.id] = {+ ...state[a.id],+ retryAction: 'release',+ retryAfter: nowMs + 60_000,+ lastToggleStatus: r.status,+ };+ }changes.push({ name: a.name, action: 'ON', reason: 'cooldown expired', http: r.status });}+ } else {+ delete state[a.id];}}}diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjsindex 815bd222..34949ff9 100755--- a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs@@ -319,6 +319,15 @@ async function liveUsage(email) {}}+function authenticationUnavailable(a) {+ const status = String(a.status || '').toLowerCase();+ const detail = [a.lastError, a.error, a.errorMessage, a.statusMessage, a.statusReason].filter(Boolean).join(' ');+ return (+ status === 'auth_repair' ||+ /\b(401|403)\b|authentication[_ -]?error|invalid (api )?key|invalid.*token|revoked/i.test(detail)+ );+}+function genuineRateLimit(a, now = Date.now()) {const flagged = !!a.rateLimitStatus?.isRateLimited || !!a.opusRateLimitStatus?.isRateLimited;return flagged && !rateLimitLooksStale(a, now);@@ -475,19 +484,36 @@ function decideMaxOut(accts, nowMs) {const u7 = lu?.u7 ?? cu.sevenDay?.utilization;const sw = a.sessionWindow?.sessionWindowStatus || null;const cur = a.schedulable !== false;+ const unavailable = authenticationUnavailable(a);const quota = liveQuotaExhaustion(a, nowMs);const rl = Boolean(quota);const overloaded = genuineOverload(a, nowMs);let desired = true;let reason = `max-out (5h=${u5 ?? '?'} 7d=${u7 ?? '?'} sw=${sw ?? 'none'})`;- if (quota) {+ if (unavailable) {+ desired = false;+ reason = 'authentication unavailable; staged re-auth required';+ } else if (quota) {desired = false;reason = `quota exhausted (${quota.windows.join('+')}); auto-reschedule ${quota.resetAt}`;} else if (overloaded) {reason = 'overloaded(529), staying schedulable';}- return { a, cur, desired, reason, soft: false, sw, u5: u5 ?? '?', u7: u7 ?? '?', rl, overloaded, quota };+ return {+ a,+ cur,+ desired,+ reason,+ soft: false,+ sw,+ u5: u5 ?? '?',+ u7: u7 ?? '?',+ unavailable,+ rl,+ overloaded,+ quota,+ };});}@@ -499,6 +525,7 @@ function decideConservative(accts, nowMs) {const u7 = lu?.u7 ?? cu.sevenDay?.utilization;const sw = a.sessionWindow?.sessionWindowStatus || null;const cur = a.schedulable !== false;+ const unavailable = authenticationUnavailable(a);const quota = liveQuotaExhaustion(a, nowMs);const rl = Boolean(quota);const overloaded = genuineOverload(a, nowMs);@@ -506,20 +533,23 @@ function decideConservative(accts, nowMs) {let desired = true;let reason = 'scheduled unless live quota is exhausted';let soft = false;- if (quota) {+ if (unavailable) {+ desired = false;+ reason = 'authentication unavailable; staged re-auth required';+ } else if (quota) {desired = false;reason = `quota exhausted (${quota.windows.join('+')}); auto-reschedule ${quota.resetAt}`;} else if (overloaded) {reason = 'overloaded(529), staying schedulable';}- return { a, cur, desired, reason, soft, sw, u5: u5 ?? '?', u7: u7 ?? '?', rl, overloaded, quota };+ return { a, cur, desired, reason, soft, sw, u5: u5 ?? '?', u7: u7 ?? '?', unavailable, rl, overloaded, quota };});- let usable = decisions.filter((d) => d.desired && !d.rl && !d.overloaded).length;+ let usable = decisions.filter((d) => d.desired && !d.unavailable && !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)+ .filter((d) => d.desired === false && d.soft && !d.unavailable && !d.rl && !d.overloaded).sort((x, y) => unum(x) - unum(y));for (const d of revertable) {if (usable >= FLOOR) break;@@ -527,7 +557,7 @@ function decideConservative(accts, nowMs) {d.reason = `FLOOR(${FLOOR}): held schedulable despite ${d.reason}`;usable++;}- const final = decisions.filter((d) => d.desired && !d.rl && !d.overloaded).length;+ const final = decisions.filter((d) => d.desired && !d.unavailable && !d.rl && !d.overloaded).length;if (final < FLOOR)log(`WARNING: only ${final} usable account(s) (< floor ${FLOOR}) — pool is capacity-constrained`);}@@ -847,7 +877,10 @@ async function main() {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' : '?')})`);+ const off = decisions+ .filter((d) => !d.desired)+ .map((d) => `${d.a.name}(${d.unavailable ? 'AUTH' : d.sw || (d.rl ? 'RL' : '?')})`);+ if (!on.length) log('WARNING: all active Claude accounts unavailable; leaving pool honestly unschedulable');log(`tick: ${changed} change(s). live-quota=${liveN}/${decisions.length} schedulable=${on.length} [${on.join(',')}] | off=[${off.join(',')}]`,);diff --git a/claude-ops/scripts/account-rotation/crs-refresh-lock.mjs b/claude-ops/scripts/account-rotation/crs-refresh-lock.mjsindex d8af9e87..e7c3a532 100644--- a/claude-ops/scripts/account-rotation/crs-refresh-lock.mjs+++ b/claude-ops/scripts/account-rotation/crs-refresh-lock.mjs@@ -1,31 +1,8 @@-#!/usr/bin/env node-/**- * crs-refresh-lock.mjs — per-account single-writer OAuth refresh lock.- *- * crs-token-feed.mjs calls acquireRefreshLock(key) before refreshing a rotator- * account's OAuth token, so an overlapping run (e.g. a slow tick plus a- * cron/timer overlap) can't send two concurrent refresh_token grants for the- * same account — the second grant would race the first and could invalidate- * a token the first request is still using.- *- * Local, mkdir-based advisory lock (no native deps, same approach as- * crs-reconciler-state.mjs's withOwnStateLock): synchronous, per-key, with a- * TTL-based stale-lock reclaim so a crashed process can't wedge a key- * forever. This is a single-host lock — sufficient for the default- * single-timer cadence this ships with. A distributed lock (e.g. Redis, for- * multiple hosts sharing one vault/pool) is a possible future extension, not- * implemented here.- *- * CONFIG (env only, no config.json keys — this lock is infrastructure, not a- * feature to toggle):- * CRS_REFRESH_LOCK_DIR default: <plugin-data-dir>/account-rotation/refresh-locks- * CRS_REFRESH_LOCK_TTL_SEC default: 120 — age after which a lock is considered- * stale (owner crashed mid-refresh) and reclaimed.- */--import { mkdirSync, rmdirSync, statSync, existsSync } from 'fs';+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { homedir } from 'os';+import { randomBytes } from 'crypto';+import { execSync } from 'child_process';const DEFAULT_LOCK_DIR = join(process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace'),@@ -34,58 +11,174 @@ const DEFAULT_LOCK_DIR = join();const LOCK_DIR = process.env.CRS_REFRESH_LOCK_DIR || DEFAULT_LOCK_DIR;const LOCK_TTL_MS = (Number(process.env.CRS_REFRESH_LOCK_TTL_SEC) || 120) * 1000;+const GUARD_TTL_MS = 10_000;+const PRODUCTION_MIN_PACE_MS = 1_000;+const MIN_PACE_MS = Math.max(+ process.env.CRS_REFRESH_TEST_ALLOW_ZERO_PACE === '1' ? 0 : PRODUCTION_MIN_PACE_MS,+ Number(process.env.CRS_REFRESH_MIN_PACE_MS) || PRODUCTION_MIN_PACE_MS,+);+const MAX_JITTER_MS = Math.max(0, Math.min(5_000, Number(process.env.CRS_REFRESH_JITTER_MS) || 500));-function lockPathFor(key) {- const safeKey = String(key).replace(/[^a-zA-Z0-9_.@-]/g, '_');- return join(LOCK_DIR, `${safeKey}.lock`);+function safeKey(key) {+ return String(key).replace(/[^a-zA-Z0-9_.@-]/g, '_');}-/**- * Try to acquire the refresh lock for `key`.- * @returns {(() => void) | null} a release() function on success, or null if- * the lock is already held by a live (non-stale) refresh for this key.- */-export function acquireRefreshLock(key) {- const lockPath = lockPathFor(key);- mkdirSync(LOCK_DIR, { recursive: true });+function lockPathFor(key) {+ return join(LOCK_DIR, `${safeKey(key)}.lock.json`);+}- if (tryMkdir(lockPath)) return () => release(lockPath);+function guardPathFor(key) {+ return join(LOCK_DIR, `${safeKey(key)}.guard`);+}- // Lock already exists — reclaim it if stale (owner crashed mid-refresh),- // otherwise report held.- let ageMs;+function readJson(path) {try {- ageMs = Date.now() - statSync(lockPath).mtimeMs;+ return JSON.parse(readFileSync(path, 'utf8'));} catch {- // Vanished between our failed mkdir and this stat (owner just released- // it) — try once more.- return tryMkdir(lockPath) ? () => release(lockPath) : null;+ return null;}- if (ageMs < LOCK_TTL_MS) return null;+}+function writeJsonAtomic(path, value) {+ const tmp = `${path}.tmp.${process.pid}.${randomBytes(8).toString('hex')}`;+ writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: 'wx' });+ renameSync(tmp, path);+}++function pidAlive(pid) {+ if (!Number.isInteger(pid) || pid <= 0) return false;try {- rmdirSync(lockPath);+ process.kill(pid, 0);+ return true;} catch {- // Someone else reclaimed it first — treat as held.- return null;+ return false;}- return tryMkdir(lockPath) ? () => release(lockPath) : null;}-function tryMkdir(lockPath) {+function sleepBriefly() {+ try {+ execSync('sleep 0.01', { stdio: 'ignore', timeout: 100 });+ } catch {}+}++function tryCreateGuard(path, owner) {try {- mkdirSync(lockPath);+ mkdirSync(path);+ } catch (error) {+ if (error.code === 'EEXIST') return false;+ throw error;+ }+ try {+ writeFileSync(join(path, 'owner.json'), JSON.stringify(owner), { mode: 0o600, flag: 'wx' });return true;- } catch (e) {- if (e.code !== 'EEXIST') throw e;- return false;+ } catch (error) {+ rmSync(path, { recursive: true, force: true });+ throw error;}}-function release(lockPath) {+function reclaimStaleGuard(path) {+ const observed = readJson(join(path, 'owner.json'));+ const age = Date.now() - Number(observed?.acquiredAt || 0);+ if (observed && pidAlive(Number(observed.pid)) && age < GUARD_TTL_MS) return false;+ const tombstone = `${path}.stale.${process.pid}.${randomBytes(8).toString('hex')}`;try {- if (existsSync(lockPath)) rmdirSync(lockPath);+ renameSync(path, tombstone);} catch {- // Already gone (e.g. reclaimed as stale by another process) — fine.+ return false;+ }+ const claimed = readJson(join(tombstone, 'owner.json'));+ if (claimed?.ownerNonce !== observed?.ownerNonce) {+ try {+ renameSync(tombstone, path);+ } catch {}+ return false;+ }+ rmSync(tombstone, { recursive: true, force: true });+ return true;+}++function withGuard(key, action) {+ mkdirSync(LOCK_DIR, { recursive: true });+ const path = guardPathFor(key);+ const owner = { ownerNonce: randomBytes(16).toString('hex'), pid: process.pid, acquiredAt: Date.now() };+ for (let attempt = 0; attempt < 100; attempt++) {+ if (tryCreateGuard(path, owner)) {+ try {+ return action();+ } finally {+ const current = readJson(join(path, 'owner.json'));+ if (current?.ownerNonce === owner.ownerNonce) rmSync(path, { recursive: true, force: true });+ }+ }+ reclaimStaleGuard(path);+ sleepBriefly();}+ return null;+}++/** Acquire one account refresh lease with owner-checked renewal and release. */+export function acquireRefreshLock(key) {+ const lockPath = lockPathFor(key);+ const ownerNonce = randomBytes(16).toString('hex');+ const acquiredAt = Date.now();+ const acquired = withGuard(key, () => {+ const current = readJson(lockPath);+ const renewedAt = Number(current?.renewedAt || current?.acquiredAt || 0);+ if (current && pidAlive(Number(current.pid)) && Date.now() - renewedAt < LOCK_TTL_MS) return false;+ writeJsonAtomic(lockPath, { ownerNonce, pid: process.pid, acquiredAt, renewedAt: acquiredAt });+ return true;+ });+ if (!acquired) return null;++ let active = true;+ const renew = () => {+ if (!active) return false;+ return Boolean(+ withGuard(key, () => {+ const current = readJson(lockPath);+ if (current?.ownerNonce !== ownerNonce || current.pid !== process.pid) return false;+ writeJsonAtomic(lockPath, { ...current, renewedAt: Date.now() });+ return true;+ }),+ );+ };+ const heartbeat = setInterval(renew, Math.max(100, Math.floor(LOCK_TTL_MS / 3)));+ heartbeat.unref?.();++ const release = () => {+ if (!active) return false;+ active = false;+ clearInterval(heartbeat);+ return Boolean(+ withGuard(key, () => {+ const current = readJson(lockPath);+ if (current?.ownerNonce !== ownerNonce || current.pid !== process.pid) return false;+ rmSync(lockPath, { force: true });+ return true;+ }),+ );+ };+ release.renew = renew;+ release.ownerNonce = ownerNonce;+ return release;+}++function pacingPathFor(key) {+ return join(LOCK_DIR, `${safeKey(key)}.next.json`);+}++function readNextEligible(path) {+ return Number(readJson(path)?.nextEligibleAt) || 0;+}++export function claimRefreshPace(key, nowMs = Date.now(), random = Math.random) {+ return withGuard(`${key}.pace`, () => {+ const path = pacingPathFor(key);+ const eligible = readNextEligible(path);+ const startAt = Math.max(nowMs, eligible);+ const jitterMs = Math.floor(Math.max(0, Math.min(1, Number(random()) || 0)) * (MAX_JITTER_MS + 1));+ writeJsonAtomic(path, { nextEligibleAt: startAt + MIN_PACE_MS + jitterMs });+ return Math.max(0, startAt - nowMs);+ });}diff --git a/claude-ops/scripts/account-rotation/crs-token-feed.mjs b/claude-ops/scripts/account-rotation/crs-token-feed.mjsindex 21c30919..82ccb5a5 100644--- a/claude-ops/scripts/account-rotation/crs-token-feed.mjs+++ b/claude-ops/scripts/account-rotation/crs-token-feed.mjs@@ -19,7 +19,7 @@ import { fileURLToPath } from 'url';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 { acquireRefreshLock, claimRefreshPace } from './crs-refresh-lock.mjs';import {buildCrsNameMaps,crsBaseUrl,@@ -218,6 +218,12 @@ async function main() {log(`${key}: refresh lock held elsewhere — propagate-only`);} else {try {+ const paceWaitMs = claimRefreshPace(key);+ if (paceWaitMs === null) {+ log(`${key}: refresh pacing lease held elsewhere — propagate-only`);+ return;+ }+ if (paceWaitMs > 0) await sleep(paceWaitMs);const r = await withAuthWriterLock(async () => {// Re-read under the canonical writer lock: refresh tokens are// single-use and the resulting file update is one transaction.diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjsindex ad72f215..255b8d4e 100644--- a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs@@ -2,9 +2,9 @@/*** 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. This reconciler, if enabled,+ * Fills the recovery gap left when identity-verified vault refresh confirms an+ * account's refresh_token is dead (not just expiring). The refresher flags it+ * needs-reauth and stops. This reconciler, if enabled,* dispatches ONE unattended browser re-auth per tick (serial, single-flight).** OPT-IN. Does nothing (exits 0) unless crs.enableMagicLinkRecovery is true@@ -93,7 +93,7 @@ function rotatingLockBusy() {}}-/** Read crs-401-refresher's own state file, READ-ONLY, for accounts it flagged needs-reauth. */+/** Read the legacy needs-reauth state file, READ-ONLY, during migration. */function needsReauthKeysFromRefresher() {const state = loadJsonState(REFRESHER_STATE_PATH, log);const out = new Set();@@ -103,7 +103,7 @@ function needsReauthKeysFromRefresher() {return out;}-/** Fallback when crs-401-refresher isn't enabled: vault missing refresh_token. */+/** Fallback when no needs-reauth record exists: vault missing refresh_token. */function needsReauthKeysFromVault(vaultKeys) {const cfg = loadRotationConfig();const vaultPath = crsFileVaultPath(cfg) || join(homedir(), '.claude', '.credentials.json');diff --git a/claude-ops/scripts/account-rotation/refresh-tokens.mjs b/claude-ops/scripts/account-rotation/refresh-tokens.mjsindex acde1fec..57879638 100644--- a/claude-ops/scripts/account-rotation/refresh-tokens.mjs+++ b/claude-ops/scripts/account-rotation/refresh-tokens.mjs@@ -20,11 +20,12 @@ import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { execFileSync, execSync } from 'child_process';import { fetchWithProxyFallback } from './proxy-helper.mjs';-import { acquireRefreshLock } from './crs-refresh-lock.mjs';+import { acquireRefreshLock, claimRefreshPace } from './crs-refresh-lock.mjs';import { readRotationToken, reconcileRemoteRotationVault, writeRotationTokenCoordinated } from './rotation-vault.mjs';import { withAuthWriterLock } from './auth-writer-coordination.mjs';import { verifyRefreshedTokenIdentity } from './token-identity.mjs';import { automatedAuthAllowed } from './auto-auth-policy.mjs';+import { retryAfterDelayMs } from './retry-after.mjs';import {REFRESH_WHEN_BELOW_MS,MIN_HEALTHY_TTL_MS,@@ -236,11 +237,7 @@ async function refreshOAuthToken(refreshToken) {// to backoff. Anthropic returns seconds-in-Retry-After when present.if (res.status === 429) {const retryAfterHeader = res.headers && (res.headers.get?.('retry-after') || res.headers['retry-after']);- const retryAfterMs = retryAfterHeader- ? /\d+/i.test(String(retryAfterHeader))- ? Math.min(15 * 60_000, Math.max(2_000, parseInt(String(retryAfterHeader), 10) * 1000 + 2000))- : 60_000- : null;+ const retryAfterMs = retryAfterDelayMs(retryAfterHeader);const delay = retryAfterMs ?? RETRY_DELAY_MS * attempt;log(` 429 Too Many Requests (attempt ${attempt}/${MAX_RETRIES}) — waiting ${Math.round(delay / 1000)}s (Retry-After=${retryAfterHeader ?? 'n/a'})...`,@@ -413,10 +410,16 @@ for (let i = 0; i < accountsOrdered.length; i++) {try {await withAuthWriterLock(async (writerCapability) => {- // Rate limit courtesy: delay between accounts- if (i > 0) {- await sleep(INTER_ACCOUNT_DELAY_MS);+ // Cross-process pacing: reserve the next eligible refresh slot before+ // touching a single-use refresh token. Keep the existing per-loop gap too.+ const paceWaitMs = claimRefreshPace(key);+ if (paceWaitMs === null) {+ log(`${key}: refresh pacing lease held elsewhere — skipping`);+ skipped++;+ return;}+ if (paceWaitMs > 0) await sleep(paceWaitMs);+ if (i > 0) await sleep(INTER_ACCOUNT_DELAY_MS);const currentTokenJson = readStoredToken(account);const parsed = parseToken(currentTokenJson);diff --git a/claude-ops/scripts/account-rotation/retry-after.mjs b/claude-ops/scripts/account-rotation/retry-after.mjsnew file mode 100644index 00000000..97525ab3--- /dev/null+++ b/claude-ops/scripts/account-rotation/retry-after.mjs@@ -0,0 +1,15 @@+const MAX_RETRY_AFTER_MS = 15 * 60_000;+const MIN_RETRY_AFTER_MS = 2_000;++export function retryAfterDelayMs(value, nowMs = Date.now()) {+ if (value === undefined || value === null || String(value).trim() === '') return null;+ const raw = String(value).trim();+ let delayMs;+ if (/^\d+$/.test(raw)) delayMs = Number(raw) * 1000;+ else {+ const retryAt = Date.parse(raw);+ if (!Number.isFinite(retryAt)) return 60_000;+ delayMs = retryAt - nowMs;+ }+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(MIN_RETRY_AFTER_MS, delayMs + 2_000));+}diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth.pyindex ee6b5197..59b4ab42 100644--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py@@ -67,13 +67,20 @@ Usage:import argparseimport atexit+import fcntl+import hashlibimport jsonimport osimport re+import shutilimport signal+import socketimport subprocessimport sys+import tempfile+import threadingimport time+import uuidfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -91,7 +98,6 @@ BU_MODEL = "gpt-5.6-luna"STATE_DIR = Path(os.environ.get("CRSPROXY_STATE_DIR", "/opt/crsproxy/state"))LOG_DIR = STATE_DIRLEASE_FILE = STATE_DIR / "crsproxy-claude-oauth-lease.json"-CANARY_URL = "http://localhost:8319/v1/chat/completions"# Exit codesEXIT_SUCCESS = 0@@ -155,6 +161,12 @@ PROVIDERS = {},}+CANARY_EXPECTED_KEYS = {+ "claude": ("access_token", "accessToken", "refresh_token", "refreshToken"),+ "xai": ("access_token", "accessToken", "refresh_token", "refreshToken", "token"),+ "codex": ("access_token", "accessToken", "refresh_token", "refreshToken", "token"),+}+# JS to inject before clicking Authorize. Intercepts the navigation to the# localhost callback URL and stores it in window.__CB__ so the agent can# retrieve it after clicking. The port is templated per provider.@@ -220,31 +232,167 @@ def safe_email(email: str) -> str:# ----------------------------------------------------------------------------# Canary request (proxy health check)+# Candidate canary request# ----------------------------------------------------------------------------def send_canary(model: str, timeout: int = 30) -> int:- """Send a canary request through the cli-proxy-api proxy.+def _expected_auth_content(auth: dict, provider: str) -> bool:+ """Require provider-specific non-empty credential material."""+ keys = CANARY_EXPECTED_KEYS.get(provider, ())+ if any(isinstance(auth.get(key), str) and auth[key].strip() for key in keys):+ return True+ nested = auth.get("claudeAiOauth") if provider == "claude" else None+ return bool(isinstance(nested, dict) and any(+ isinstance(nested.get(key), str) and nested[key].strip()+ for key in ("accessToken", "refreshToken")))+++def _canary_status_rejection(status: int) -> str:+ """Classify a failed candidate-only inference result."""+ if status in (401, 403):+ return f"candidate authentication rejected (HTTP {status})"+ if status == 429:+ return "candidate rate-limited (HTTP 429)"+ if status == 503:+ return "candidate unavailable (HTTP 503)"+ if status == 400:+ return "candidate model unsupported (HTTP 400)"+ return f"candidate canary failed (HTTP {status})"+++def _reserve_loopback_port() -> int:+ """Ask the kernel for an unused loopback port."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _candidate_proxy_config(auth_dir: Path, port: int, api_key: str) -> str:+ """Build a minimal candidate-only CLIProxyAPI configuration."""+ quoted_auth_dir = json.dumps(str(auth_dir))+ quoted_api_key = json.dumps(api_key)+ return (+ 'host: "127.0.0.1"\n'+ f"port: {port}\n"+ f"auth-dir: {quoted_auth_dir}\n"+ "api-keys:\n"+ f" - {quoted_api_key}\n"+ "remote-management:\n"+ " allow-remote: false\n"+ ' secret-key: ""\n'+ "debug: false\n"+ "logging-to-file: false\n"+ "usage-statistics-enabled: false\n"+ )- Returns the HTTP status code, or -1 on connection error.- A 200 means the proxy is serving the model. 429 means rate-limited- (proxy is alive). 503 means no auth available (proxy is alive but- has no enabled accounts — the candidate might fix this).- """++def _stop_candidate_proxy(process: subprocess.Popen):+ """Terminate the candidate proxy process group."""+ if process.poll() is not None:+ returntry:- r = requests.post(- CANARY_URL,- headers={"Authorization": "Bearer test"},- json={- "model": model,- "messages": [{"role": "user", "content": "hi"}],- "max_tokens": 1,- },- timeout=timeout,- )- return r.status_code- except Exception as e:- log(f"Canary request error: {e}")- return -1+ os.killpg(process.pid, signal.SIGTERM)+ process.wait(timeout=2)+ except (OSError, subprocess.TimeoutExpired):+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except OSError:+ pass+ try:+ process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ pass+++def send_canary(model: str, auth_path: Path, timeout: int = 30) -> tuple[bool, str]:+ """Launch and probe a candidate-only proxy owned by this validator."""+ proxy_bin = os.environ.get("CRSPROXY_CANDIDATE_PROXY_BIN", HUB_BIN).strip()+ if not proxy_bin or not Path(proxy_bin).is_file() or not os.access(proxy_bin, os.X_OK):+ return False, "candidate proxy binary is unavailable"++ try:+ candidate_bytes = auth_path.read_bytes()+ except OSError as e:+ return False, f"cannot read candidate for canary: {type(e).__name__}"+ candidate_digest = hashlib.sha256(candidate_bytes).hexdigest()+ deadline = time.monotonic() + timeout++ with tempfile.TemporaryDirectory(prefix="crsproxy-candidate-") as tmpdir:+ root = Path(tmpdir)+ os.chmod(root, 0o700)+ isolated_dir = root / "auths"+ isolated_dir.mkdir(mode=0o700)+ isolated_auth = isolated_dir / auth_path.name+ with open(isolated_auth, "xb") as fh:+ fh.write(candidate_bytes)+ fh.flush()+ os.fsync(fh.fileno())+ os.chmod(isolated_auth, 0o600)+ if hashlib.sha256(isolated_auth.read_bytes()).hexdigest() != candidate_digest:+ return False, "candidate canary copy digest mismatch"++ port = _reserve_loopback_port()+ api_key = f"candidate-{uuid.uuid4().hex}"+ config_path = root / "config.yaml"+ config_path.write_text(_candidate_proxy_config(isolated_dir, port, api_key), encoding="utf-8")+ os.chmod(config_path, 0o600)+ env = {+ "HOME": str(root),+ "PATH": os.environ.get("PATH", ""),+ "TMPDIR": str(root),+ }+ process = None+ try:+ process = subprocess.Popen(+ [proxy_bin, "-config", str(config_path)],+ cwd=root,+ env=env,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ endpoint = f"http://127.0.0.1:{port}/v1/chat/completions"+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}+ response = None+ while time.monotonic() < deadline:+ if process.poll() is not None:+ return False, f"candidate proxy exited before readiness (exit {process.returncode})"+ try:+ response = requests.post(+ endpoint,+ headers=headers,+ json={+ "model": model,+ "messages": [{"role": "user", "content": "Reply with OK."}],+ "max_tokens": 8,+ },+ timeout=min(2, max(0.05, deadline - time.monotonic())),+ )+ break+ except requests.RequestException:+ time.sleep(0.05)+ if response is None:+ return False, "candidate canary timed out"+ if response.status_code != 200:+ return False, _canary_status_rejection(response.status_code)+ try:+ result = response.json()+ content = result["choices"][0]["message"]["content"]+ except (ValueError, KeyError, IndexError, TypeError):+ return False, "candidate canary returned invalid model response"+ if not isinstance(content, str) or not content.strip():+ return False, "candidate canary returned HTTP 200 without model content"+ try:+ current_digest = hashlib.sha256(auth_path.read_bytes()).hexdigest()+ except OSError:+ return False, "candidate changed during canary"+ if current_digest != candidate_digest:+ return False, "candidate changed during canary"+ return True, "candidate canary passed"+ except OSError as e:+ return False, f"candidate proxy unavailable: {type(e).__name__}"+ finally:+ if process is not None:+ _stop_candidate_proxy(process)# ---------------------------------------------------------------------------@@ -307,18 +455,15 @@ def validate_candidate(auth_path: Path, expected_email: str,except Exception as e:return False, f"cannot parse expiry '{expired_str}': {e}"- # --- Check 4: Canary request (proxy health) ---+ # --- Check 4: Provider credential material is present ---+ if not _expected_auth_content(auth, expected_type):+ return False, "candidate auth file has no non-empty provider credential"++ # --- Check 5: Candidate-specific isolated canary request ---if canary_model and not skip_canary:- status = send_canary(canary_model)- # The canary is a proxy health check, not a per-account token test.- # The token freshness is validated by the expiry check (check 3).- # Any HTTP response means the proxy is alive and processing- # requests. Only a connection error (-1) means the proxy is down.- # 200 = serving, 429 = rate-limited, 503 = no auth available,- # 401/403 = accounts in cooldown/auth issues — all indicate the- # proxy is alive. -1 = connection error — proxy is down.- if status < 0:- return False, "canary request failed: proxy unreachable (connection error)"+ passed, reason = send_canary(canary_model, auth_path)+ if not passed:+ return False, reasonreturn True, "all checks passed"@@ -379,60 +524,142 @@ def disable_auth_file(auth_path: Path) -> bool:# ---------------------------------------------------------------------------# Serialization lease# ----------------------------------------------------------------------------def acquire_lease(provider: str, max_wait: int = 120) -> bool:- """Acquire the serialization lease, waiting up to max_wait seconds.-- If the lease file exists and is recent (younger than- LEASE_STALE_SECONDS), polls every 5 seconds until it is released- or max_wait is reached. If the lease is stale, it is removed and a- new lease is acquired. Returns True if the lease was acquired,- False on timeout.- """- t0 = time.time()- first_check = True- while True:- if LEASE_FILE.exists():- try:- data = json.loads(LEASE_FILE.read_text())- age = time.time() - data.get("timestamp", 0)- if age < LEASE_STALE_SECONDS:- if first_check:- log(f"Lease held by {data.get('provider','?')} "- f"({int(age)}s old) — waiting up to {max_wait}s")- first_check = False- if time.time() - t0 >= max_wait:- log(f"Lease wait timed out after {max_wait}s — "- "another login may still be in progress")- return False- time.sleep(5)- continue- # Stale lease — remove it- log(f"Stale lease ({int(age)}s old) — removing")- LEASE_FILE.unlink()- except (json.JSONDecodeError, OSError):- try:- LEASE_FILE.unlink()- except OSError as e:- log(f"Stale lease cleanup error: {e}")- # Lease file doesn't exist or was removed — acquire- break+def _lease_guard_path() -> Path:+ return LEASE_FILE.with_name(LEASE_FILE.name + ".guard")+++def _with_lease_guard(action):+ """Serialize lease record replacement and release across processes."""+ _ensure_state_dir(LEASE_FILE.parent)+ fd = os.open(_lease_guard_path(), os.O_RDWR | os.O_CREAT, 0o600)+ try:+ fcntl.flock(fd, fcntl.LOCK_EX)+ return action()+ finally:+ fcntl.flock(fd, fcntl.LOCK_UN)+ os.close(fd)+- LEASE_FILE.write_text(json.dumps({+def _read_lease(path: Path | None = None) -> dict:+ """Read a lease record, returning an empty dict for missing/corrupt data."""+ try:+ return json.loads((path or LEASE_FILE).read_text())+ except (OSError, json.JSONDecodeError, TypeError):+ return {}+++def _pid_alive(pid: int) -> bool:+ if pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ return True+ except OSError:+ return False+++def _write_lease(data: dict):+ tmp = LEASE_FILE.with_name(f"{LEASE_FILE.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(data, fh)+ fh.flush()+ os.fsync(fh.fileno())+ os.replace(tmp, LEASE_FILE)+ except Exception:+ try:+ tmp.unlink()+ except OSError:+ pass+ raise+++def _try_acquire_or_reclaim(provider: str, lease_id: str) -> str:+ now = time.time()+ current = _read_lease()+ if current:+ renewed_at = float(current.get("renewed_at", current.get("timestamp", 0)) or 0)+ owner_alive = _pid_alive(int(current.get("pid", 0) or 0))+ if owner_alive and now - renewed_at < LEASE_STALE_SECONDS:+ return "held"+ data = {"provider": provider,- "timestamp": time.time(),+ "timestamp": now,+ "renewed_at": now,"pid": os.getpid(),- }))- log(f"Lease acquired for {provider}")- return True+ "lease_id": lease_id,+ }+ _write_lease(data)+ return "acquired"+++def acquire_lease(provider: str, max_wait: int = 120) -> str | None:+ """Acquire the serialization lease and return its owner lease ID."""+ t0 = time.monotonic()+ first_check = True+ lease_id = uuid.uuid4().hex+ while True:+ outcome = _with_lease_guard(+ lambda: _try_acquire_or_reclaim(provider, lease_id))+ if outcome == "acquired":+ log(f"Lease acquired for {provider}")+ return lease_id+ if first_check:+ data = _read_lease()+ age = time.time() - float(+ data.get("renewed_at", data.get("timestamp", 0)) or 0)+ log(f"Lease held by {data.get('provider','?')} "+ f"({int(max(age, 0))}s old) — waiting up to {max_wait}s")+ first_check = False+ if time.monotonic() - t0 >= max_wait:+ log(f"Lease wait timed out after {max_wait}s — "+ "another login may still be in progress")+ return None+ time.sleep(min(0.1, max(0.01, max_wait / 20)))+++def renew_lease(lease_id: str | None) -> bool:+ """Renew only the current owner's lease record."""+ if not lease_id:+ return False++ def renew():+ data = _read_lease()+ if data.get("lease_id") != lease_id:+ return False+ data["renewed_at"] = time.time()+ _write_lease(data)+ return True+ return _with_lease_guard(renew)+++def release_lease(lease_id: str | None) -> bool:+ """Release atomically while holding the owner-record guard."""+ if not lease_id:+ return False++ def release():+ data = _read_lease()+ if data.get("lease_id") != lease_id:+ return False+ try:+ LEASE_FILE.unlink()+ except FileNotFoundError:+ return False+ return True-def release_lease():- """Remove the serialization lease file."""try:- LEASE_FILE.unlink(missing_ok=True)- log("Lease released")+ released = _with_lease_guard(release)+ if released:+ log("Lease released")+ else:+ log("Lease release skipped — ownership changed")+ return releasedexcept Exception as e:log(f"Lease release error: {e}")+ return False# ---------------------------------------------------------------------------@@ -1139,6 +1366,24 @@ def handle_captcha_checkpoint(client: BrowserUseClient, run_id: str,# ---------------------------------------------------------------------------# Core reauth flow# ---------------------------------------------------------------------------+def _restore_failed_candidate(auth_file: Path, stale_backup: Path):+ """Restore the prior auth atomically, or remove a failed new candidate."""+ if stale_backup.exists():+ try:+ os.replace(stale_backup, auth_file)+ log(f"[9] Stale auth restored: {auth_file.name}")+ except Exception as e:+ log(f"[9] Stale restore error: {e}")+ else:+ log("[9] No stale backup — removing failed candidate")+ try:+ auth_file.unlink()+ except FileNotFoundError:+ pass+ except Exception as e:+ log(f"Failed candidate cleanup error: {e}")++def _complete_reauth(proc: subprocess.Popen, callback_url: str,auth_file: Path, stale_backup: Path,email: str, provider: str,@@ -1179,24 +1424,14 @@ def _complete_reauth(proc: subprocess.Popen, callback_url: str,if not valid:log(f"[FAIL] Candidate validation failed: {reason}")log("[9] Preserving stale auth — restoring from backup")- if stale_backup.exists():- try:- os.rename(str(stale_backup), str(auth_file))- log(f"[9] Stale auth restored: {auth_file.name}")- except Exception as e:- log(f"[9] Stale restore error: {e}")- else:- log("[9] No stale backup — removing failed candidate")- try:- auth_file.unlink()- except Exception as e:- log(f"Failed candidate cleanup error: {e}")+ _restore_failed_candidate(auth_file, stale_backup)return EXIT_FAILURElog(f"[9] Candidate validation passed: {reason}")log("[9] Atomically activating auth file...")if not activate_auth_file(auth_file):log("[FAIL] Could not activate auth file")+ _restore_failed_candidate(auth_file, stale_backup)return EXIT_FAILURE# Clean up stale backup on success@@ -1222,15 +1457,29 @@ def run_reauth(provider: str, email: str, gog_account: str,log_path.unlink(missing_ok=True)# --- Step 1: Acquire serialization lease ---- if not acquire_lease(provider):+ lease_id = acquire_lease(provider)+ if not lease_id:log("Could not acquire lease — another login may be in progress")return EXIT_FAILURE+ stop_heartbeat = threading.Event()++ def heartbeat():+ interval = max(1.0, LEASE_STALE_SECONDS / 3)+ while not stop_heartbeat.wait(interval):+ if not renew_lease(lease_id):+ log("Lease heartbeat stopped — ownership changed")+ return++ heartbeat_thread = threading.Thread(target=heartbeat, daemon=True)+ heartbeat_thread.start()try:return _run_reauth_inner(provider, email, gog_account, client,dry_run, log_path)finally:- release_lease()+ stop_heartbeat.set()+ heartbeat_thread.join(timeout=1)+ release_lease(lease_id)def _run_reauth_inner(provider: str, email: str, gog_account: str,@@ -1561,14 +1810,20 @@ def _checkpoint_resume(args) -> int:atexit.register(client.stop_all_browsers)# Acquire serialization lease (prevents concurrent logins)- if not acquire_lease(provider):+ lease_id = acquire_lease(provider)+ if not lease_id:log("[FAIL] Could not acquire lease — another login may be in progress")return EXIT_FAILURE# Start a new login process (the original is likely dead)log_path = LOG_DIR / "bu_reauth_hub.log"log("[1] Starting new cli-proxy-api login for checkpoint resume")- proc = start_login(provider, log_path)+ try:+ proc = start_login(provider, log_path)+ except Exception as e:+ log(f"[ERROR] Could not start login process: {e}")+ release_lease(lease_id)+ return EXIT_FAILURE# Wait for OAuth URL (needed to keep the callback port listener alive)log("[2] Waiting for OAuth URL...")@@ -1576,6 +1831,7 @@ def _checkpoint_resume(args) -> int:if not oauth_url:log("[ERROR] No OAuth URL found — cannot resume login process")cleanup_login_process(proc)+ release_lease(lease_id)return EXIT_FAILURElog(f"[2] OAuth URL captured: {sanitize_url(oauth_url)}")@@ -1644,7 +1900,7 @@ def _checkpoint_resume(args) -> int:client.stop_all_browsers()cleanup_login_process(proc)clear_checkpoint()- release_lease()+ release_lease(lease_id)# ---------------------------------------------------------------------------diff --git a/claude-ops/scripts/crsproxy-reauth/test-python-suites.sh b/claude-ops/scripts/crsproxy-reauth/test-python-suites.shnew file mode 100644index 00000000..11ce7ca3--- /dev/null+++ b/claude-ops/scripts/crsproxy-reauth/test-python-suites.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++python3 test_browser_cleanup.py+python3 test_checkpoint.py+python3 test_lease_cooldown.py+python3 test_candidate_validation.pydiff --git a/claude-ops/scripts/crsproxy-reauth/test_candidate_validation.py b/claude-ops/scripts/crsproxy-reauth/test_candidate_validation.pynew file mode 100644index 00000000..6efccf0f--- /dev/null+++ b/claude-ops/scripts/crsproxy-reauth/test_candidate_validation.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""Behavioral tests for exact-candidate validation and rollback."""++import json+import os+import stat+import sys+import tempfile+import threading+from datetime import datetime, timedelta, timezone+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from unittest.mock import patch++sys.path.insert(0, str(Path(__file__).parent))+import bu_reauth+++def valid_auth(email="[email protected]", token="test-access-token"):+ return {+ "email": email,+ "type": "claude",+ "expired": (datetime.now(timezone.utc) + timedelta(days=2)).isoformat(),+ "access_token": token,+ "disabled": True,+ }+++def make_proxy(root: Path, mode="normal") -> tuple[Path, Path]:+ proxy = root / f"candidate-proxy-{mode}.py"+ record = root / f"candidate-proxy-{mode}.json"+ proxy.write_text(f'''#!/usr/bin/env python3+import argparse, json, re, time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+parser=argparse.ArgumentParser()+parser.add_argument("-config", required=True)+args=parser.parse_args()+config=Path(args.config).read_text()+def field(name):+ match=re.search(r"^"+re.escape(name)+r":\\s*(.+)$",config,re.M)+ if not match: raise SystemExit(12)+ return json.loads(match.group(1)) if match.group(1).startswith('"') else match.group(1)+host=field("host")+port=int(field("port"))+auth_dir=Path(field("auth-dir"))+api_key=re.search(r"^\\s*-\\s*(.+)$",config,re.M).group(1)+api_key=json.loads(api_key) if api_key.startswith('"') else api_key+files=list(auth_dir.glob("*.json"))+if len(files) != 1: raise SystemExit(13)+payload=json.loads(files[0].read_text())+Path({str(record)!r}).write_text(json.dumps({{"host":host,"port":port,"auth_dir":str(auth_dir),"auth_file":str(files[0]),"token":payload.get("access_token"),"api_key":api_key}}))+mode={mode!r}+if mode == "exit": raise SystemExit(14)+class Handler(BaseHTTPRequestHandler):+ def log_message(self,*args): pass+ def do_POST(self):+ if mode == "timeout":+ time.sleep(2)+ return+ length=int(self.headers.get("content-length","0"))+ request=json.loads(self.rfile.read(length) or b"{{}}")+ authorized=self.headers.get("authorization") == "Bearer " + api_key+ status=200 if authorized and payload.get("access_token") == "good-token" else 401+ content="candidate-only-ok" if status == 200 else ""+ if mode == "empty": content=""+ body=json.dumps({{"model":request.get("model"),"choices":[{{"message":{{"content":content}}}}]}}).encode()+ self.send_response(status)+ self.send_header("content-type","application/json")+ self.send_header("content-length",str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ThreadingHTTPServer((host,port),Handler).serve_forever()+''')+ os.chmod(proxy, 0o700)+ return proxy, record+++def proxy_env(proxy: Path):+ return patch.dict(os.environ, {"CRSPROXY_CANDIDATE_PROXY_BIN": str(proxy)}, clear=False)+++def test_candidate_specific_success_and_permissions():+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ auth = root / "claude-user.json"+ auth.write_text(json.dumps(valid_auth(token="good-token")))+ os.chmod(auth, 0o640)+ proxy, record = make_proxy(root)+ with proxy_env(proxy):+ valid, reason = bu_reauth.validate_candidate(+ auth, "[email protected]", "claude", "claude-sonnet-5")+ assert valid is True, reason+ used = json.loads(record.read_text())+ assert used["token"] == "good-token"+ assert Path(used["auth_file"]).name == auth.name+ assert Path(used["auth_dir"]) != auth.parent+ assert used["host"] == "127.0.0.1"+ assert stat.S_IMODE(auth.stat().st_mode) == 0o640+ print("PASS: validator launches a loopback proxy with only the exact isolated candidate")+++def test_response_and_process_failures():+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ auth = root / "claude-user.json"+ auth.write_text(json.dumps(valid_auth(token="good-token")))+ for mode, expected in [("empty", "without model content"), ("exit", "exited before readiness")]:+ proxy, _ = make_proxy(root, mode)+ with proxy_env(proxy):+ valid, reason = bu_reauth.send_canary("claude-sonnet-5", auth)+ assert valid is False, mode+ assert expected in reason, (mode, reason)+ print("PASS: malformed responses and failed candidate proxy startup fail closed")+++def test_healthy_shared_endpoint_cannot_validate_bad_candidate():+ class HealthyShared(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = b'{"choices":[{"message":{"content":"healthy-shared"}}]}'+ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ shared = ThreadingHTTPServer(("127.0.0.1", 0), HealthyShared)+ thread = threading.Thread(target=shared.serve_forever, daemon=True)+ thread.start()+ try:+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ auth = root / "claude-user.json"+ auth.write_text(json.dumps(valid_auth(token="bad-token")))+ proxy, record = make_proxy(root)+ shared_url = f"http://127.0.0.1:{shared.server_port}/v1/chat/completions"+ with proxy_env(proxy), patch.dict(os.environ, {"CRSPROXY_CANARY_URL": shared_url}, clear=False):+ valid, reason = bu_reauth.send_canary("claude-sonnet-5", auth)+ assert valid is False+ assert "authentication rejected" in reason+ used = json.loads(record.read_text())+ assert used["port"] != shared.server_port+ assert used["token"] == "bad-token"+ print("PASS: healthy shared service cannot substitute for a bad isolated candidate")+ finally:+ shared.shutdown()+ shared.server_close()+ thread.join(timeout=2)+++def test_validation_classification_and_timeout():+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ bad = root / "bad.json"+ bad.write_text(json.dumps(valid_auth(token="bad-token")))+ proxy, _ = make_proxy(root)+ with proxy_env(proxy):+ valid, reason = bu_reauth.send_canary("claude-sonnet-5", bad)+ assert valid is False and "authentication rejected" in reason++ good = root / "good.json"+ good.write_text(json.dumps(valid_auth(token="good-token")))+ timeout_proxy, _ = make_proxy(root, "timeout")+ with proxy_env(timeout_proxy):+ valid, reason = bu_reauth.send_canary("claude-sonnet-5", good, timeout=0.2)+ assert valid is False and "timed out" in reason+ print("PASS: candidate status and validator-owned timeout fail closed")+++def test_missing_credential_rejected_before_canary():+ with tempfile.TemporaryDirectory() as tmpdir:+ auth = Path(tmpdir) / "claude-user.json"+ payload = valid_auth()+ payload.pop("access_token")+ auth.write_text(json.dumps(payload))+ with patch.object(bu_reauth, "send_canary") as canary:+ valid, reason = bu_reauth.validate_candidate(+ auth, "[email protected]", "claude", "claude-sonnet-5")+ assert valid is False+ assert "no non-empty provider credential" in reason+ canary.assert_not_called()+ print("PASS: empty provider credentials are rejected before activation")+++def test_failed_candidate_rollback_and_activation_mode():+ with tempfile.TemporaryDirectory() as tmpdir:+ auth = Path(tmpdir) / "claude-user.json"+ stale = auth.with_suffix(".stale")+ stale_payload = {"email": "[email protected]", "type": "claude", "disabled": True, "access_token": "old"}+ auth.write_text(json.dumps(valid_auth("[email protected]")))+ stale.write_text(json.dumps(stale_payload))+ os.chmod(stale, 0o640)+ proc = object()+ with patch.object(bu_reauth, "paste_callback_url", return_value=True), \+ patch.object(bu_reauth.time, "sleep"), \+ patch.object(bu_reauth, "AUTH_FILE_WAIT", 0):+ result = bu_reauth._complete_reauth(+ proc, "http://localhost/callback", auth, stale,+ "[email protected]", "claude", bu_reauth.PROVIDERS["claude"])+ assert result == bu_reauth.EXIT_FAILURE+ assert json.loads(auth.read_text()) == stale_payload+ assert stat.S_IMODE(auth.stat().st_mode) == 0o640++ auth.write_text(json.dumps(valid_auth()))+ os.chmod(auth, 0o640)+ assert bu_reauth.activate_auth_file(auth) is True+ assert json.loads(auth.read_text())["disabled"] is False+ assert stat.S_IMODE(auth.stat().st_mode) == 0o640+ print("PASS: failed candidates roll back atomically and activation preserves permissions")+++def main():+ tests = [+ test_candidate_specific_success_and_permissions,+ test_response_and_process_failures,+ test_healthy_shared_endpoint_cannot_validate_bad_candidate,+ test_validation_classification_and_timeout,+ test_missing_credential_rejected_before_canary,+ test_failed_candidate_rollback_and_activation_mode,+ ]+ failed = 0+ for test in tests:+ try:+ test()+ except Exception as exc:+ print(f"FAIL: {test.__name__}: {exc}")+ failed += 1+ print(f"Results: {len(tests) - failed} passed, {failed} failed, {len(tests)} total")+ return 1 if failed else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.pyindex 0dbc5e4f..0cb261fc 100644--- a/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py+++ b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py@@ -15,11 +15,13 @@ Run locally (syntax/logic only, no hub dependencies):"""import json+import multiprocessingimport osimport sysimport tempfileimport timefrom pathlib import Path+from unittest.mock import patch# Add the script directory to the pathsys.path.insert(0, str(Path(__file__).parent))@@ -28,6 +30,27 @@ sys.path.insert(0, str(Path(__file__).parent))import bu_reauth+def _lease_contender(lease_path: str, start, results):+ bu_reauth.LEASE_FILE = Path(lease_path)+ start.wait()+ lease_id = bu_reauth.acquire_lease("claude", max_wait=0.2)+ results.put(bool(lease_id))+ if lease_id:+ time.sleep(0.4)+ bu_reauth.release_lease(lease_id)+++def _hold_and_renew(lease_path: str, ready, release_now, results):+ bu_reauth.LEASE_FILE = Path(lease_path)+ bu_reauth.LEASE_STALE_SECONDS = 0.15+ lease_id = bu_reauth.acquire_lease("claude", max_wait=0.2)+ results.put(lease_id)+ ready.set()+ while not release_now.wait(0.04):+ results.put(bu_reauth.renew_lease(lease_id))+ results.put(bu_reauth.release_lease(lease_id))++def test_lease_file_constant():"""Lease file path is correct."""assert bu_reauth.LEASE_FILE == bu_reauth.STATE_DIR / "crsproxy-claude-oauth-lease.json"@@ -43,143 +66,167 @@ def test_lease_stale_seconds():def test_acquire_lease_no_existing():- """acquire_lease acquires when no lease file exists."""+ """acquire_lease creates an owner-scoped lease."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:- lease_path = Path(tmpdir) / "lease.json"- bu_reauth.LEASE_FILE = lease_path-- result = bu_reauth.acquire_lease("claude", max_wait=5)- assert result is True, "Expected lease acquisition to succeed"- assert lease_path.exists(), "Lease file should be created"- data = json.loads(lease_path.read_text())+ bu_reauth.LEASE_FILE = Path(tmpdir) / "lease.json"+ lease_id = bu_reauth.acquire_lease("claude", max_wait=0.2)+ assert lease_id+ data = json.loads(bu_reauth.LEASE_FILE.read_text())assert data["provider"] == "claude"- assert "timestamp" in data- assert "pid" in data- print("PASS: acquire_lease creates lease file when none exists")+ assert data["pid"] == os.getpid()+ assert data["lease_id"] == lease_id+ assert data["renewed_at"] >= data["timestamp"]+ assert bu_reauth.release_lease(lease_id) is True+ print("PASS: acquire_lease creates an owner-scoped lease")bu_reauth.LEASE_FILE = orig_lease-def test_acquire_lease_stale_deleted():- """acquire_lease removes stale lease and acquires new one."""+def test_acquire_lease_stale_replaced():+ """A stale lease can be replaced without deleting a newer owner."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:lease_path = Path(tmpdir) / "lease.json"bu_reauth.LEASE_FILE = lease_path-- # Write a stale lease (timestamp 20 minutes ago)- stale_data = {+ stale = {"provider": "claude",- "timestamp": time.time() - 1200, # 20 min ago+ "timestamp": time.time() - 1200,"pid": 99999,+ "lease_id": "stale-owner",}- lease_path.write_text(json.dumps(stale_data))-- result = bu_reauth.acquire_lease("claude", max_wait=5)- assert result is True, "Expected lease acquisition after stale removal"- data = json.loads(lease_path.read_text())- assert data["provider"] == "claude"- assert data["pid"] == os.getpid()- print("PASS: acquire_lease removes stale lease and acquires new one")+ lease_path.write_text(json.dumps(stale))+ lease_id = bu_reauth.acquire_lease("claude", max_wait=0.2)+ assert lease_id and lease_id != "stale-owner"+ assert json.loads(lease_path.read_text())["lease_id"] == lease_id+ assert bu_reauth.release_lease(lease_id) is True+ print("PASS: stale lease is replaced by a new owner")bu_reauth.LEASE_FILE = orig_lease-def test_acquire_lease_waits_for_recent():- """acquire_lease waits when lease is recent, then acquires when released."""+def test_multiprocess_contention_single_winner():+ """Atomic O_EXCL acquisition allows exactly one simultaneous winner."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:- lease_path = Path(tmpdir) / "lease.json"- bu_reauth.LEASE_FILE = lease_path-- # Write a recent lease- recent_data = {- "provider": "claude",- "timestamp": time.time(), # just now- "pid": 99999,- }- lease_path.write_text(json.dumps(recent_data))-- # Start a thread that removes the lease after 2 seconds- import threading-- def remove_lease():- time.sleep(2)- lease_path.unlink()-- t = threading.Thread(target=remove_lease)- t.start()-- result = bu_reauth.acquire_lease("claude", max_wait=10)- t.join()-- assert result is True, (- "Expected lease acquisition after waiting for release"- )- assert lease_path.exists(), "New lease file should be created"- print("PASS: acquire_lease waits for recent lease to be released")+ lease_path = str(Path(tmpdir) / "lease.json")+ ctx = multiprocessing.get_context("spawn")+ start = ctx.Event()+ results = ctx.Queue()+ procs = [ctx.Process(target=_lease_contender, args=(lease_path, start, results)) for _ in range(4)]+ for proc in procs:+ proc.start()+ start.set()+ winners = [results.get(timeout=5) for _ in procs]+ for proc in procs:+ proc.join(timeout=5)+ assert proc.exitcode == 0+ assert winners.count(True) == 1, winners+ print("PASS: multiprocessing contention has exactly one lease owner")bu_reauth.LEASE_FILE = orig_lease-def test_acquire_lease_timeout():- """acquire_lease returns False on timeout."""+def test_owner_only_release():+ """A former or foreign owner cannot remove the current lease."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:lease_path = Path(tmpdir) / "lease.json"bu_reauth.LEASE_FILE = lease_path-- # Write a recent lease that won't be removed- recent_data = {- "provider": "claude",- "timestamp": time.time(),- "pid": 99999,- }- lease_path.write_text(json.dumps(recent_data))-- result = bu_reauth.acquire_lease("claude", max_wait=3)- assert result is False, "Expected False on timeout"- print("PASS: acquire_lease returns False on timeout")+ owner = bu_reauth.acquire_lease("claude", max_wait=0.2)+ assert owner+ assert bu_reauth.release_lease("foreign-owner") is False+ assert lease_path.exists()+ assert json.loads(lease_path.read_text())["lease_id"] == owner+ assert bu_reauth.release_lease(owner) is True+ assert not lease_path.exists()+ print("PASS: release_lease is owner-only")bu_reauth.LEASE_FILE = orig_lease-def test_release_lease():- """release_lease removes the lease file."""+def test_release_interleaving_cannot_delete_replacement():+ """Release rechecks ownership under the same interprocess guard."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:- lease_path = Path(tmpdir) / "lease.json"- bu_reauth.LEASE_FILE = lease_path-- # Create a lease- lease_path.write_text(json.dumps({"provider": "claude"}))- assert lease_path.exists()-- bu_reauth.release_lease()- assert not lease_path.exists(), "Lease file should be removed"- print("PASS: release_lease removes the lease file")+ bu_reauth.LEASE_FILE = Path(tmpdir) / "lease.json"+ old_owner = bu_reauth.acquire_lease("claude", max_wait=0.2)+ assert old_owner+ entered = multiprocessing.Event()+ proceed = multiprocessing.Event()+ original_guard = bu_reauth._with_lease_guard++ def delayed_guard(action):+ entered.set()+ proceed.wait(timeout=2)+ return original_guard(action)++ result = []+ import threading+ with patch.object(bu_reauth, "_with_lease_guard", side_effect=delayed_guard):+ thread = threading.Thread(+ target=lambda: result.append(bu_reauth.release_lease(old_owner)))+ thread.start()+ assert entered.wait(timeout=1)+ replacement = {+ "provider": "claude", "timestamp": time.time(),+ "renewed_at": time.time(), "pid": os.getpid(),+ "lease_id": "replacement-owner",+ }+ original_guard(lambda: bu_reauth._write_lease(replacement))+ proceed.set()+ thread.join(timeout=2)+ assert result == [False]+ assert json.loads(bu_reauth.LEASE_FILE.read_text())["lease_id"] == "replacement-owner"+ print("PASS: old owner cannot delete an interleaved replacement")bu_reauth.LEASE_FILE = orig_lease-def test_release_lease_missing_ok():- """release_lease does not error if lease file doesn't exist."""+def test_long_lease_renewal_is_not_stolen():+ """A live long operation renews often enough to prevent stale reclaim."""orig_lease = bu_reauth.LEASE_FILEwith tempfile.TemporaryDirectory() as tmpdir:- lease_path = Path(tmpdir) / "lease.json"- bu_reauth.LEASE_FILE = lease_path-- # No lease file exists — should not raise- bu_reauth.release_lease()- print("PASS: release_lease handles missing lease gracefully")+ lease_path = str(Path(tmpdir) / "lease.json")+ ctx = multiprocessing.get_context("spawn")+ ready = ctx.Event()+ release_now = ctx.Event()+ results = ctx.Queue()+ holder = ctx.Process(target=_hold_and_renew,+ args=(lease_path, ready, release_now, results))+ holder.start()+ assert ready.wait(timeout=3)+ owner = results.get(timeout=2)+ assert owner+ time.sleep(0.35)+ bu_reauth.LEASE_FILE = Path(lease_path)+ original_stale = bu_reauth.LEASE_STALE_SECONDS+ bu_reauth.LEASE_STALE_SECONDS = 0.15+ contender = bu_reauth.acquire_lease("claude", max_wait=0.1)+ bu_reauth.LEASE_STALE_SECONDS = original_stale+ assert contender is None+ release_now.set()+ holder.join(timeout=3)+ assert holder.exitcode == 0+ assert results.get(timeout=1) is True+ print("PASS: renewed long lease is not stolen")bu_reauth.LEASE_FILE = orig_lease-def test_release_lease_always_called():- """release_lease is called in run_reauth's finally block."""- # Verify by checking the source that run_reauth has try/finally with release_lease- import inspect- source = inspect.getsource(bu_reauth.run_reauth)- assert "acquire_lease" in source, "run_reauth should acquire lease"- assert "release_lease" in source, "run_reauth should release lease"- assert "finally" in source, "run_reauth should have a finally block"- print("PASS: run_reauth acquires and releases lease in try/finally")+def test_run_reauth_releases_on_success_and_failure():+ """run_reauth releases its exact lease across return and exception branches."""+ client = object()+ for inner_result, side_effect in ((bu_reauth.EXIT_SUCCESS, None), (None, RuntimeError("boom"))):+ released = []+ with patch.object(bu_reauth, "acquire_lease", return_value="lease-123"), \+ patch.object(bu_reauth, "release_lease", side_effect=lambda lease_id: released.append(lease_id)), \+ patch.object(bu_reauth, "_run_reauth_inner", return_value=inner_result, side_effect=side_effect):+ if side_effect:+ try:+ bu_reauth.run_reauth("claude", "[email protected]", "", client)+ except RuntimeError:+ pass+ else:+ raise AssertionError("Expected injected failure")+ else:+ assert bu_reauth.run_reauth("claude", "[email protected]", "", client) == inner_result+ assert released == ["lease-123"]+ print("PASS: run_reauth releases its owned lease on success and failure")# ---------------------------------------------------------------------------@@ -428,8 +475,8 @@ def test_lease_log_no_pid_exposed_inappropriately():captured = io.StringIO()sys.stdout = captured- bu_reauth.acquire_lease("claude", max_wait=5)- bu_reauth.release_lease()+ lease_id = bu_reauth.acquire_lease("claude", max_wait=0.2)+ bu_reauth.release_lease(lease_id)sys.stdout = orig_stdoutoutput = captured.getvalue()@@ -441,20 +488,30 @@ def test_lease_log_no_pid_exposed_inappropriately():bu_reauth.LEASE_FILE = orig_lease-def test_checkpoint_resume_has_lease():- """_checkpoint_resume acquires and releases the lease."""- import inspect- source = inspect.getsource(bu_reauth._checkpoint_resume)- assert "acquire_lease" in source, (- "_checkpoint_resume should acquire the lease"- )- assert "release_lease" in source, (- "_checkpoint_resume should release the lease"- )- assert "finally" in source, (- "_checkpoint_resume should have a finally block"- )- print("PASS: _checkpoint_resume acquires and releases lease")+def test_checkpoint_resume_releases_on_early_failure():+ """Checkpoint resume releases its owned lease when OAuth URL setup fails."""+ released = []+ checkpoint = {+ "session_id": "session-1",+ "provider": "claude",+ "email": "[email protected]",+ "callback_port": 54545,+ }+ with tempfile.TemporaryDirectory() as tmpdir:+ ckpt = Path(tmpdir) / "checkpoint.json"+ ckpt.write_text(json.dumps(checkpoint))+ with patch.object(bu_reauth, "CHECKPOINT_FILE", ckpt), \+ patch.dict(os.environ, {"BROWSER_USE_API_KEY": "fake"}), \+ patch.object(bu_reauth.atexit, "register"), \+ patch.object(bu_reauth, "acquire_lease", return_value="lease-resume"), \+ patch.object(bu_reauth, "release_lease", side_effect=lambda lease_id: released.append(lease_id)), \+ patch.object(bu_reauth, "start_login", return_value=object()), \+ patch.object(bu_reauth, "get_oauth_url", return_value=None), \+ patch.object(bu_reauth, "cleanup_login_process"):+ result = bu_reauth._checkpoint_resume(object())+ assert result == bu_reauth.EXIT_FAILURE+ assert released == ["lease-resume"]+ print("PASS: checkpoint resume releases its lease on setup failure")def main():@@ -468,12 +525,12 @@ def main():test_lease_file_constant,test_lease_stale_seconds,test_acquire_lease_no_existing,- test_acquire_lease_stale_deleted,- test_acquire_lease_waits_for_recent,- test_acquire_lease_timeout,- test_release_lease,- test_release_lease_missing_ok,- test_release_lease_always_called,+ test_acquire_lease_stale_replaced,+ test_multiprocess_contention_single_winner,+ test_owner_only_release,+ test_release_interleaving_cannot_delete_replacement,+ test_long_lease_renewal_is_not_stolen,+ test_run_reauth_releases_on_success_and_failure,# Email cooldown teststest_email_cooldown_constants,test_record_email_send,@@ -489,7 +546,7 @@ def main():# Sensitive data exposuretest_cooldown_log_no_email_exposed,test_lease_log_no_pid_exposed_inappropriately,- test_checkpoint_resume_has_lease,+ test_checkpoint_resume_releases_on_early_failure,]passed = 0diff --git a/claude-ops/scripts/install-crs-reconcilers-agent.sh b/claude-ops/scripts/install-crs-reconcilers-agent.shindex f47c6d8a..422fec2d 100755--- a/claude-ops/scripts/install-crs-reconcilers-agent.sh+++ b/claude-ops/scripts/install-crs-reconcilers-agent.sh@@ -1,9 +1,9 @@#!/usr/bin/env bash-# install-crs-reconcilers-agent.sh — Install the CRS 429-cooldown, 401-refresher,-# and/or magic-link-autoloop reconcilers as launchd LaunchAgents (macOS).+# install-crs-reconcilers-agent.sh — Install the CRS 429-cooldown and/or+# magic-link-autoloop reconcilers as launchd LaunchAgents (macOS).#-# Reads crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery-# from the rotator config and installs only the ones that are true — this+# Reads crs.cooldownEnabled / 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).#@@ -26,25 +26,17 @@ command -v node >/dev/null 2>&1 || { echo "error: node not found in PATH (need Ncommand -v jq >/dev/null 2>&1 || { echo "error: jq not found in PATH" >&2; exit 1; }COOLDOWN_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 [[ "$TOKEN_REFRESH_ENABLED" == "true" ]]; then- echo "error: CRS 401 refresher is retired; use the identity-verified crs-token-feed service" >&2- exit 1-fi--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"+if [[ "$COOLDOWN_ENABLED" != "true" && "$MAGIC_LINK_ENABLED" != "true" ]]; then+ echo "skip: neither crs.cooldownEnabled nor crs.enableMagicLinkRecovery is true in $CFG"+ echo " set one (or \$CRS_COOLDOWN_ENABLED=1 / \$CRS_ENABLE_MAGIC_LINK=1) and re-run"exit 0fi@@ -58,7 +50,6 @@ 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"[[ "$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 0@@ -101,13 +92,7 @@ elseuninstall "crs-429-cooldown"fi-if [[ "$TOKEN_REFRESH_ENABLED" == "true" ]]; then- render_and_install "crs-401-refresher" \- "$PLUGIN_ROOT/scripts/account-rotation/crs-401-refresher.sh" \- "$PLUGIN_ROOT/templates/com.claude-ops.crs-401-refresher.plist"-else- uninstall "crs-401-refresher"-fi+uninstall "crs-401-refresher"if [[ "$MAGIC_LINK_ENABLED" == "true" ]]; thenrender_and_install "magic-link-autoloop" \@@ -119,7 +104,6 @@ fiechoecho "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 " 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\""+echo "logs: $LOG_DIR/crs-429-cooldown.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.magic-link-autoloop\""diff --git a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist b/claude-ops/templates/com.claude-ops.crs-401-refresher.plistdeleted file mode 100644index d3953c8f..00000000--- a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist+++ /dev/null@@ -1,61 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!--- CRS 401-refresher reconciler (claude-relay-service pool proactive OAuth- token refresh).-- Schedule: every 300s. Equivalent systemd: OnUnitActiveSec=300s.- 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.crs-401-refresher.plist before:- launchctl bootstrap "gui/$(id -u)" <plist>-- To uninstall:- launchctl bootout "gui/$(id -u)/com.claude-ops.crs-401-refresher"- rm ~/Library/LaunchAgents/com.claude-ops.crs-401-refresher.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-401-refresher</string>-- <key>ProgramArguments</key>- <array>- <string>/bin/bash</string>- <string>__WRAPPER_PATH__</string>- </array>-- <key>StartInterval</key>- <integer>300</integer>-- <key>ThrottleInterval</key>- <integer>60</integer>-- <key>RunAtLoad</key>- <true/>-- <key>StandardOutPath</key>- <string>__LOG_DIR__/crs-401-refresher-launchd.log</string>- <key>StandardErrorPath</key>- <string>__LOG_DIR__/crs-401-refresher-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>- <key>CLAUDE_AUTH_COORDINATION_CONFIG</key>- <string>__CLAUDE_AUTH_COORDINATION_CONFIG__</string>- <key>CLAUDE_ROTATOR_CONFIG</key>- <string>__CLAUDE_ROTATOR_CONFIG__</string>- </dict>-- <key>ProcessType</key>- <string>Background</string>- <key>LowPriorityIO</key>- <true/>-</dict>-</plist>diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex 0fd6de8e..7096d381 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -41,6 +41,8 @@ run_suite "$TESTS_DIR/test-hooks.sh"run_suite "$TESTS_DIR/test-specialist-agent-swap.sh"run_suite "$TESTS_DIR/test-rotate-cliproxy-integration.sh"run_suite "$TESTS_DIR/test-model-args.sh"+run_suite "$TESTS_DIR/test-account-recovery.sh"+run_suite "$TESTS_DIR/../scripts/crsproxy-reauth/test-python-suites.sh"run_suite "$TESTS_DIR/test-staged-enrollment.sh"run_suite "$TESTS_DIR/test-coordination-provisioning.sh"run_suite "$TESTS_DIR/test-template.sh"diff --git a/claude-ops/tests/test-account-recovery.sh b/claude-ops/tests/test-account-recovery.shnew file mode 100644index 00000000..44fcb642--- /dev/null+++ b/claude-ops/tests/test-account-recovery.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"++node "$ROOT/scripts/account-rotation/__tests__/refresh-pacing.test.mjs"+node "$ROOT/scripts/account-rotation/__tests__/refresh-lock.test.mjs"+node "$ROOT/scripts/account-rotation/__tests__/production-recovery.test.mjs"