Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(cliproxy-heal): unattended quota re-entry with AI advisor (#846)
Aurora Capital8e61e8cab680
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex 13555a88..2992589f 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -1,5 +1,6 @@## Unreleased+- feat(cliproxy-heal): unattended hub healer puts seats back in rotation as soon as any leftover or reset quota is observed (no hysteresis). A seat sits out only on certain "quota exhausted" plus a parseable reschedule stamp, then re-enters at that stamp. An AI advisor runs on every seat and cannot override those rules. `applied=reauth` only after `CLIPROXY_REAUTH_CMD` (`cliproxy-reauth-one.sh` → hub `bu_reauth_lib.py` / `xai_device_reauth.py`); otherwise the seat is recorded blocked. Hub systemd timer `cliproxy-heal.timer`; Mac stays client-only. `runHealTick` denies healing unless both gates are satisfied: the `CLIPROXY_HUB_HEAL=1` env var, and the presence of the `/opt/crsproxy/.heal-account-optin` marker file that only `install-heal.sh` writes (not the systemd unit's `Environment=` lines), so editing the unit alone cannot satisfy both. Tests in `scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjs`.- fix(ops-mac): the application firewall is opt-in. `/ops:mac fix` no longer offers to enable it and no longer lists it as a recommendation; the audit reports its state and stops. Turning the firewall on breaks local listeners (dev servers, MCP proxies, VNC, tunnels) and the user rarely connects the breakage to a `fix` run they asked for other reasons. `socketfilterfw` now runs only when the user asks for the firewall by name in that turn.- **Removed the CRS relay backend.** claude-relay-service handed every session astatic `cr_` bearer token pinned into `settings.json`, and the plugin had to keepdiff --git a/claude-ops/scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjs b/claude-ops/scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjsnew file mode 100644index 00000000..3e5285d2--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjs@@ -0,0 +1,707 @@+#!/usr/bin/env node+/**+ * Gating tests for cliproxy heal / re-entry. Drive healPool + runHealTick+ * from representative start states. Do not re-implement the policy here.+ */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, writeFileSync, existsSync, rmSync, chmodSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { ACTIONS, healPool } from '../cliproxy-heal-policy.mjs';+import { opaqueSeatId, snapshotFromAuthDir } from '../cliproxy-pool-snapshot.mjs';+import { applyDecision, runHealTick, accountOptedIn } from '../cliproxy-heal-tick.mjs';+import { parseAdviceText, buildHealerPrompt } from '../cliproxy-heal-ai.mjs';+import { automatedAuthAllowed, directOAuthWriterAllowed, CLIPROXY_HEAL_OPTIN_TOKEN } from '../auto-auth-policy.mjs';++const NOW = Date.parse('2026-08-20T12:00:00Z');+const FUTURE = '2026-08-20T18:00:00Z';+const PAST = '2026-08-20T06:00:00Z';++function spyAsk(adviceById = {}) {+ const calls = [];+ async function ask(facts) {+ calls.push(facts);+ if (typeof adviceById === 'function') return adviceById(facts);+ if (Object.prototype.hasOwnProperty.call(adviceById, facts.id)) return adviceById[facts.id];+ return { inRotation: facts.hard.inRotation, action: facts.hard.action, reason: 'echo-hard' };+ }+ ask.calls = calls;+ return ask;+}++const pool = [+ {+ id: 'cooled-new-quota',+ provider: 'claude',+ inRotation: false,+ disabled: false,+ cooling: true,+ remainingQuota: 12,+ newQuotaObserved: true,+ quotaExceeded: false,+ hadQuotaSignal: true,+ certainQuotaExhausted: false,+ rescheduleAt: FUTURE,+ },+ {+ id: 'remaining-quota',+ provider: 'claude',+ inRotation: true,+ disabled: false,+ cooling: false,+ remainingQuota: 40,+ paidSeat: true,+ quotaExceeded: false,+ },+ {+ id: 'uncertain-exhaust',+ provider: 'xai',+ inRotation: false,+ disabled: true,+ cooling: true,+ lastExhaustReason: 'stream disconnected',+ lastExhaustBody: 'xai stream error: stream disconnected before response.completed',+ certainQuotaExhausted: false,+ rescheduleAt: null,+ tokenStale: false,+ },+ {+ id: 'certain-future',+ provider: 'claude',+ inRotation: true,+ disabled: false,+ cooling: true,+ quotaExceeded: true,+ quotaReason: 'credential_quota',+ lastExhaustReason: 'credential_quota',+ lastExhaustBody: 'quota exhausted',+ certainQuotaExhausted: true,+ rescheduleAt: FUTURE,+ },+ {+ id: 'expired-stamp',+ provider: 'codex',+ inRotation: false,+ disabled: false,+ cooling: true,+ quotaExceeded: true,+ quotaReason: 'quota',+ lastExhaustBody: 'The usage limit has been reached',+ certainQuotaExhausted: true,+ rescheduleAt: PAST,+ },+ {+ id: 'codex-quota-flag',+ provider: 'codex',+ inRotation: false,+ cooling: true,+ quotaExceeded: true,+ quotaReason: 'quota',+ lastExhaustBody: 'The usage limit has been reached',+ rescheduleAt: FUTURE,+ },+ {+ id: 'stream-cool',+ provider: 'xai',+ inRotation: false,+ cooling: true,+ quotaExceeded: false,+ hadQuotaSignal: false,+ lastExhaustBody: 'stream disconnected',+ rescheduleAt: FUTURE,+ },+];++// Save/restore so this suite's env mutations never leak into a process that+// runs multiple test files back to back.+const savedHubHeal = process.env.CLIPROXY_HUB_HEAL;+const savedCliproxyRoot = process.env.CLIPROXY_ROOT;+const savedConfig = process.env.CLIPROXY_CONFIG;+const savedIsolateDir = process.env.CLIPROXY_ISOLATE_DIR;+const savedIsolateManifest = process.env.CLIPROXY_ISOLATE_MANIFEST;+delete process.env.CLIPROXY_HUB_HEAL;++// runHealTick resolves the compat-isolation config/isolate/manifest paths+// (defaulting to real /opt/crsproxy locations) and the account opt-in gate+// (a marker file at CLIPROXY_ROOT/.heal-account-optin — the filename is+// fixed, not independently overridable, see cliproxy-heal-tick.mjs) purely+// from process.env — it takes no path parameters for any of them. On a hub+// host that has real files at those default paths, calling runHealTick with+// dryRun:false from this suite would rewrite the live proxy config and would+// see a stray real opt-in marker as this suite's own state. Pin every one of+// them to this suite's own sandbox before any runHealTick call, and restore+// the saved values (not just delete) at the end so a real value some other+// process depends on is never left cleared.+const sandbox = mkdtempSync(join(tmpdir(), 'cliproxy-heal-sandbox-'));+const accountOptInMarker = join(sandbox, '.heal-account-optin');+process.env.CLIPROXY_ROOT = sandbox;+process.env.CLIPROXY_CONFIG = join(sandbox, 'config.yaml');+process.env.CLIPROXY_ISOLATE_DIR = join(sandbox, 'isolated');+process.env.CLIPROXY_ISOLATE_MANIFEST = join(sandbox, 'isolated', 'manifest.json');++assert.equal(directOAuthWriterAllowed('cliproxy'), false);+assert.equal(automatedAuthAllowed({ cliproxyHubHeal: true }), false);+process.env.CLIPROXY_HUB_HEAL = '1';+assert.equal(automatedAuthAllowed({ cliproxyHubHeal: true }), true);+assert.equal(automatedAuthAllowed({}), false);+assert.equal(automatedAuthAllowed({ automatedCredentialMutation: true }), false);+// runHealTick derives the second gate factor from this marker file's+// CONTENT matching CLIPROXY_HEAL_OPTIN_TOKEN, not from account.cliproxyHubHeal+// directly and not from mere existence — see cliproxy-heal-tick.mjs. Only+// install-heal.sh writes it in production; the suite writes it here to+// simulate a provisioned host.+// writeFileSync's `mode` option only takes effect when the file is created —+// it is a no-op when overwriting a file that already exists — so every+// write that needs a specific mode chmod's explicitly afterward rather than+// relying on writeFileSync alone.+function writeMarker(content, mode = 0o600) {+ writeFileSync(accountOptInMarker, content);+ chmodSync(accountOptInMarker, mode);+}+writeMarker(CLIPROXY_HEAL_OPTIN_TOKEN);++const ask = spyAsk({+ 'cooled-new-quota': { inRotation: false, action: ACTIONS.LEAVE, reason: 'model wants out' },+ 'remaining-quota': { inRotation: true, action: ACTIONS.KEEP_IN, reason: 'agree leftover' },+ 'uncertain-exhaust': { inRotation: false, action: ACTIONS.LEAVE, reason: 'model parks uncertain' },+ 'certain-future': { inRotation: false, action: ACTIONS.KEEP_OUT, reason: 'agree stamp' },+ 'expired-stamp': { inRotation: true, action: ACTIONS.ENTER, reason: 'agree elapsed' },+});++const result = await healPool(pool, { now: NOW, ask });+assert.equal(ask.calls.length, pool.length, 'AI advisor invoked once per seat');++const byId = Object.fromEntries(result.decisions.map((d) => [d.id, d]));++assert.equal(byId['cooled-new-quota'].inRotation, true, 'new quota re-enters even while cooling');+assert.equal(byId['cooled-new-quota'].ai.applied, false, 'advisor cannot park leftover quota');+assert.equal(byId['cooled-new-quota'].ai.invoked, true);++assert.equal(byId['remaining-quota'].inRotation, true, 'leftover paid quota stays serving');+assert.equal(byId['remaining-quota'].ai.applied, true);++assert.equal(byId['uncertain-exhaust'].inRotation, true, 'uncertain exhaust is healed, not parked');+assert.equal(byId['uncertain-exhaust'].ai.applied, false, 'advisor cannot park without certain exhaust+stamp');++assert.equal(byId['certain-future'].inRotation, false, 'certain exhaust + future stamp sits out');+assert.equal(byId['certain-future'].rescheduleAt, new Date(FUTURE).toISOString());+assert.equal(byId['certain-future'].ai.applied, true);++assert.equal(byId['expired-stamp'].inRotation, true, 'elapsed stamp re-enters');+assert.equal(byId['expired-stamp'].ai.applied, true);++assert.equal(byId['codex-quota-flag'].inRotation, false, 'quota.exceeded with future stamp sits out');+assert.equal(byId['stream-cool'].inRotation, true, 'stream-error cooling is healed, not treated as leftover quota');++assert.ok(Object.values(ACTIONS).includes(byId['cooled-new-quota'].action));+assert.ok(Object.values(ACTIONS).includes(byId['certain-future'].action));++const prompt = buildHealerPrompt({ remainingQuota: 3, hard: { inRotation: true } });+assert.match(prompt, /No hysteresis/);+assert.equal(parseAdviceText('```json\n{"inRotation":true,"action":"enter_rotation"}\n```').inRotation, true);++const authDir = mkdtempSync(join(tmpdir(), 'cliproxy-heal-'));+const statePath = join(authDir, '..', `heal-state-${Date.now()}.json`);++function writeSeat(stem, auth, cds) {+ writeFileSync(join(authDir, `${stem}.json`), JSON.stringify(auth, null, 2));+ if (cds) writeFileSync(join(authDir, `${stem}.cds`), JSON.stringify(cds, null, 2));+}++writeSeat(+ 'cooled-new-quota',+ { type: 'claude', disabled: false, expired: '2026-08-21T00:00:00Z' },+ {+ version: 1,+ provider: 'claude',+ auth_id: 'cooled-new-quota',+ records: [+ {+ status: 'cooling',+ reason: 'credential_quota',+ next_retry_after: FUTURE,+ quota: { exceeded: false, remaining: 12, reason: 'credential_quota', next_recover_at: FUTURE },+ last_error: { message: 'quota window reset; remaining tokens available' },+ },+ ],+ },+);+writeSeat('remaining-quota', { type: 'claude', disabled: false, expired: '2026-08-21T00:00:00Z' }, null);+writeSeat(+ 'uncertain-exhaust',+ { type: 'xai', disabled: true, disabled_reason: 'stream error', expired: '2026-08-21T00:00:00Z' },+ {+ version: 1,+ provider: 'xai',+ records: [+ {+ status: 'cooling',+ reason: 'stream disconnected',+ next_retry_after: FUTURE,+ quota: { exceeded: false, next_recover_at: '0001-01-01T00:00:00Z' },+ last_error: { message: 'xai stream error: stream disconnected before response.completed', http_status: 408 },+ },+ ],+ },+);+writeSeat(+ 'certain-future',+ { type: 'claude', disabled: false, expired: '2026-08-21T00:00:00Z' },+ {+ version: 1,+ provider: 'claude',+ records: [+ {+ status: 'cooling',+ reason: 'credential_quota',+ next_retry_after: FUTURE,+ quota: {+ exceeded: true,+ reason: 'credential_quota',+ next_recover_at: FUTURE,+ },+ last_error: { message: '{"error":{"type":"rate_limit_error","message":"quota exhausted"}}' },+ },+ ],+ },+);+writeSeat(+ 'expired-stamp',+ { type: 'codex', disabled: false, expired: '2026-08-21T00:00:00Z' },+ {+ version: 1,+ provider: 'codex',+ records: [+ {+ status: 'cooling',+ reason: 'quota',+ next_retry_after: PAST,+ quota: { exceeded: true, reason: 'quota', next_recover_at: PAST },+ last_error: {+ message:+ '{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":1787190000}}',+ },+ },+ ],+ },+);++writeSeat(+ '[email protected]',+ { type: 'claude', email: '[email protected]', disabled: false, expired: '2026-08-21T00:00:00Z' },+ null,+);+writeFileSync(+ join(authDir, 'claude-user_example.com.cds'),+ JSON.stringify({+ version: 1,+ provider: 'claude',+ auth_id: '[email protected]',+ records: [+ {+ status: 'cooling',+ reason: 'credential_quota',+ auth_id: '[email protected]',+ next_retry_after: FUTURE,+ quota: { exceeded: true, reason: 'credential_quota', next_recover_at: FUTURE },+ last_error: { message: 'quota exhausted' },+ },+ ],+ }),+);+writeFileSync(+ join(authDir, 'openai-compatible-kimi.cds'),+ JSON.stringify({+ version: 1,+ provider: 'openai-compatible-kimi',+ auth_id: 'kimi-key',+ records: [+ {+ status: 'cooling',+ reason: 'quota',+ next_retry_after: FUTURE,+ quota: { exceeded: true, reason: 'quota', next_recover_at: FUTURE },+ last_error: { message: 'quota exhausted' },+ },+ ],+ }),+);++const snap = snapshotFromAuthDir(authDir, { now: NOW });+assert.equal(snap.seats.length, 7);+// Seat ids leaving snapshotFromAuthDir must be opaque (sha256-derived), never+// the raw filename/email — the raw value only survives on `rawId`, used+// internally for auth-file mutation and reauth targeting.+for (const seat of snap.seats) {+ assert.equal(seat.id, opaqueSeatId(seat.rawId), 'seat.id must be the opaque hash of rawId');+ assert.notEqual(seat.id, seat.rawId, 'seat.id must not leak the raw account identifier');+}+const emailMatched = snap.seats.find((s) => s.rawId === '[email protected]');+assert.equal(emailMatched.cooling, true, 'json email maps to underscore cds via auth_id');+assert.equal(emailMatched.certainQuotaExhausted, true);+assert.ok(emailMatched.cdsFile.endsWith('claude-user_example.com.cds'));+const kimi = snap.seats.find((s) => s.rawId === 'openai-compatible-kimi');+assert.equal(kimi.certainQuotaExhausted, true);+assert.equal(kimi.cooling, true);+const snapRawIds = snap.seats.map((s) => s.rawId).sort();+assert.deepEqual(snapRawIds, [+ 'certain-future',+ '[email protected]',+ 'cooled-new-quota',+ 'expired-stamp',+ 'openai-compatible-kimi',+ 'remaining-quota',+ 'uncertain-exhaust',+]);++const reauthCalls = [];+const tickAsk = spyAsk((facts) => ({+ inRotation: facts.hard.inRotation,+ action: facts.hard.action,+ reason: 'tick-echo',+}));++const tick = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: tickAsk,+ dryRun: false,+ log: () => {},+ reauth: (d) => reauthCalls.push(d.id),+});++assert.equal(tick.denied, false);+assert.equal(tickAsk.calls.length, 7, 'tick invokes AI on every seat');+// decisions/actions are the externally-visible surface (persisted state,+// --json output) and must carry only the opaque id; rawId is present on+// decisions solely for internal auth-file/reauth targeting.+const tickBy = Object.fromEntries(tick.decisions.map((d) => [d.rawId, d]));+for (const decision of tick.decisions) {+ assert.equal(decision.id, opaqueSeatId(decision.rawId), 'decision.id must be the opaque hash of rawId');+}+for (const action of tick.actions) {+ assert.ok(+ tick.decisions.some((d) => d.id === action.id),+ 'action.id must be an opaque id, matching a decision.id',+ );+}+assert.equal(tickBy['cooled-new-quota'].inRotation, true);+assert.equal(tickBy['remaining-quota'].inRotation, true);+assert.equal(tickBy['uncertain-exhaust'].inRotation, true);+assert.equal(tickBy['certain-future'].inRotation, false);+assert.equal(tickBy['expired-stamp'].inRotation, true);+assert.equal(tickBy['[email protected]'].inRotation, false);+assert.equal(tickBy['openai-compatible-kimi'].inRotation, false);++assert.equal(JSON.parse(readFileSync(join(authDir, 'uncertain-exhaust.json'), 'utf8')).disabled, false);+assert.equal(existsSync(join(authDir, 'cooled-new-quota.cds')), false);+assert.equal(existsSync(join(authDir, 'uncertain-exhaust.cds')), false);+assert.equal(existsSync(join(authDir, 'certain-future.cds')), true);+assert.equal(existsSync(join(authDir, 'expired-stamp.cds')), false);+assert.equal(existsSync(join(authDir, 'claude-user_example.com.cds')), true);+assert.equal(existsSync(join(authDir, 'openai-compatible-kimi.cds')), true);++const state = JSON.parse(readFileSync(statePath, 'utf8'));+assert.equal(state.seats[opaqueSeatId('certain-future')].rescheduleAt, new Date(FUTURE).toISOString());+assert.equal(+ state.lastTick.every((row) => row.aiInvoked === true),+ true,+);+// Persisted state and lastTick must never carry a raw account id.+for (const key of Object.keys(state.seats)) {+ assert.doesNotMatch(key, /example\.com|kimi/, 'persisted seat key must be opaque, not the raw account id');+}++// Regression: CLIPROXY_CONFIG (pinned to the sandbox above) does not exist,+// so applyIsolateCompat returns ok:false/missing_config. The tick must not+// look fully healthy — runHealTick.failed and the persisted isolate.ok must+// both surface the failure, even though seat healing itself succeeded and+// state was still persisted (compat isolation failing must not lose the+// seat-level work already done).+assert.equal(tick.isolate.ok, false, 'isolate must report failure when configPath is missing');+assert.equal(tick.isolate.reason, 'missing_config');+assert.equal(tick.failed, true, 'runHealTick must surface an unrunnable compat isolation as a failed tick');+assert.equal(state.isolate.ok, false, 'persisted state must also carry the isolate failure');++// Once a real (empty) config exists at the pinned path, isolation has+// nothing to do (no manifest-listed providers present) and must not be+// reported as a failure.+writeFileSync(process.env.CLIPROXY_CONFIG, 'openai-compatibility: []\n');+const healthyIsolateTick = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: spyAsk((facts) => ({ inRotation: facts.hard.inRotation, action: facts.hard.action, reason: 'echo' })),+ dryRun: false,+ log: () => {},+});+assert.equal(healthyIsolateTick.isolate.ok, true);+assert.equal(healthyIsolateTick.failed, false, 'a runnable compat isolation must not be reported as a failed tick');++// Regression: the account opt-in gate is a filesystem marker at a fixed+// path, not a second env-var mirror of the first. Removing only the marker+// file — CLIPROXY_HUB_HEAL stays set — must still deny the tick; a caller+// cannot satisfy both gates with one env flip.+const savedMarkerContents = readFileSync(accountOptInMarker, 'utf8');+rmSync(accountOptInMarker);+const deniedByMissingMarker = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+assert.equal(deniedByMissingMarker.denied, true, 'CLIPROXY_HUB_HEAL alone must not be enough without the marker file');++// Regression: the gate is content-checked, not existence-checked. A marker+// that merely exists at the right path but does not contain the exact+// expected token (e.g. an attacker pointing at some pre-existing file, or a+// stray empty file) must still deny — this is what makes the marker a real+// second factor instead of a second name for the same env-controlled gate.+writeMarker('not-the-real-token');+const deniedByWrongContent = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+assert.equal(deniedByWrongContent.denied, true, 'a marker file with the wrong content must not satisfy the gate');++// Regression: a marker that is group/other-writable must also be rejected,+// even with the correct content — an attacker who can only widen+// permissions on an existing file should not be able to forge the gate.+writeMarker(CLIPROXY_HEAL_OPTIN_TOKEN, 0o666);+const deniedByWorldWritableMarker = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+assert.equal(+ deniedByWorldWritableMarker.denied,+ true,+ 'a world-writable marker file must not satisfy the gate even with correct content',+);++writeMarker(savedMarkerContents);++delete process.env.CLIPROXY_HUB_HEAL;+const denied = await runHealTick({+ authDir,+ statePath,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+assert.equal(denied.denied, true);++const enableApplied = applyDecision(+ {+ inRotation: true,+ disabled: true,+ cooling: false,+ authFile: join(authDir, 'remaining-quota.json'),+ },+ { dryRun: true },+);+assert.deepEqual(enableApplied.applied, ['enable_auth']);++const staleDir = mkdtempSync(join(tmpdir(), 'cliproxy-stale-'));+const staleState = join(staleDir, 'state.json');+writeFileSync(+ join(staleDir, '[email protected]'),+ JSON.stringify({+ type: 'xai',+ email: '[email protected]',+ disabled: false,+ disabled_reason: 'expired credentials (auth_kind=bearer, reason=no auth context)',+ expired: '2026-08-21T00:00:00Z',+ }),+);+process.env.CLIPROXY_HUB_HEAL = '1';+writeMarker(CLIPROXY_HEAL_OPTIN_TOKEN);+delete process.env.CLIPROXY_REAUTH_CMD;+const noWriter = await runHealTick({+ authDir: staleDir,+ statePath: staleState,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+const staleOpaque = opaqueSeatId('[email protected]');+const noWriterRow = noWriter.actions.find((a) => a.id === staleOpaque);+assert.ok(noWriterRow, 'stale seat present');+assert.equal(noWriterRow.inRotation, true);+assert.equal(noWriterRow.applied.includes('reauth'), false, 'must not claim reauth without a writer');+assert.equal(noWriterRow.applied.includes('blocked'), true);+assert.equal(noWriterRow.blocked?.reason, 'no_reauth_writer');+assert.equal(JSON.parse(readFileSync(staleState, 'utf8')).seats[staleOpaque].blocked.reason, 'no_reauth_writer');++const writerDir = mkdtempSync(join(tmpdir(), 'cliproxy-stale-w-'));+const writerState = join(writerDir, 'state.json');+const writerBin = join(writerDir, 'writer.sh');+const writerMarker = join(writerDir, 'ran');+writeFileSync(+ join(writerDir, '[email protected]'),+ JSON.stringify({+ type: 'xai',+ email: '[email protected]',+ disabled: false,+ disabled_reason: 'invalid_grant expired credentials',+ expired: '2026-08-21T00:00:00Z',+ }),+);+writeFileSync(writerBin, `#!/bin/sh\necho "$*" > ${JSON.stringify(writerMarker)}\nexit 0\n`, { mode: 0o700 });+process.env.CLIPROXY_REAUTH_CMD = writerBin;+const withWriter = await runHealTick({+ authDir: writerDir,+ statePath: writerState,+ now: NOW,+ ask: spyAsk(),+ dryRun: false,+ log: () => {},+});+const withWriterRow = withWriter.actions.find((a) => a.id === staleOpaque);+assert.equal(withWriterRow.applied.includes('reauth'), true);+assert.equal(withWriterRow.applied.includes('blocked'), false);+assert.equal(existsSync(writerMarker), true, 'configured writer must be invoked');+assert.match(readFileSync(writerMarker, 'utf8'), /xai/);+delete process.env.CLIPROXY_REAUTH_CMD;++const applyNoWriter = applyDecision({ inRotation: true, tokenStale: true, disabled: false }, { dryRun: false });+assert.equal(applyNoWriter.applied.includes('reauth'), false);+assert.equal(applyNoWriter.applied.includes('blocked'), true);+assert.equal(applyNoWriter.blocked?.reason, 'no_reauth_writer');++// Regression: CRITICAL clear_cooldown data-integrity bug. A healthy,+// non-cooling, in-rotation seat can still carry a leftover .cds file (e.g.+// from a previous unrelated cooldown that already resolved on its own via+// CLIProxy). The old guard was `if (decision.inRotation)` alone, which wiped+// that .cds unconditionally — destroying CLIProxy's own quota/reset-at+// evidence for a seat that was never actually being healed. The correct+// guard only fires when the seat is presently cooling or its reschedule+// stamp just elapsed.+{+ const cdsDir = mkdtempSync(join(tmpdir(), 'cliproxy-clear-cooldown-'));+ const cdsFile = join(cdsDir, 'healthy-seat.cds');+ writeFileSync(cdsFile, JSON.stringify({ version: 1, provider: 'claude', records: [] }));+ const healthyDecision = {+ id: 'healthy-seat',+ inRotation: true,+ disabled: false,+ cooling: false,+ reason: 'remaining_or_reset_quota',+ cdsFile,+ };+ const healthyApplied = applyDecision(healthyDecision, { dryRun: false });+ assert.equal(+ healthyApplied.applied.includes('clear_cooldown'),+ false,+ 'must not clear the sidecar for a seat that is not cooling and has no elapsed reschedule',+ );+ assert.equal(existsSync(cdsFile), true, '.cds for a healthy non-cooling seat must survive untouched');+ assert.equal(existsSync(`${cdsFile}.healed`), false);++ // Sanity check the positive case still works: an actually-cooling seat (or+ // one whose reschedule stamp elapsed) does get its sidecar renamed, never+ // destructively deleted.+ const coolingFile = join(cdsDir, 'cooling-seat.cds');+ writeFileSync(coolingFile, JSON.stringify({ version: 1, provider: 'claude', records: [] }));+ const coolingDecision = {+ id: 'cooling-seat',+ inRotation: true,+ disabled: false,+ cooling: true,+ reason: 'reschedule_elapsed',+ cdsFile: coolingFile,+ };+ const coolingApplied = applyDecision(coolingDecision, { dryRun: false });+ assert.equal(coolingApplied.applied.includes('clear_cooldown'), true);+ assert.equal(existsSync(coolingFile), false, 'renamed away, not present under the original name');+ assert.equal(existsSync(`${coolingFile}.healed`), true, 'renamed, not unlinked, so it stays recoverable');+}++// Regression: CRITICAL rule-1/rule-2 cancellation bug. hasRemainingOrResetQuota+// (rule 1) must not short-circuit rule 2 for a seat that is BOTH+// quotaExceeded:false (leftover-quota shaped) AND certainQuotaExhausted:true+// with a parseable future reschedule stamp — that combination means the+// exhaustion is certain and the seat must sit out until the stamp elapses,+// not re-enter rotation on the leftover-quota fast path.+{+ const cancelPool = [+ {+ id: 'certain-exhaust-with-leftover-signal',+ provider: 'claude',+ inRotation: true,+ disabled: false,+ cooling: true,+ quotaExceeded: false,+ hadQuotaSignal: true,+ certainQuotaExhausted: true,+ rescheduleAt: FUTURE,+ },+ ];+ const cancelResult = await healPool(cancelPool, { now: NOW, ask: spyAsk() });+ const cancelDecision = cancelResult.decisions.find((d) => d.id === 'certain-exhaust-with-leftover-signal');+ assert.equal(+ cancelDecision.inRotation,+ false,+ 'certain exhaust + future stamp must win over a coincidental quotaExceeded:false/hadQuotaSignal:true reading',+ );+}++// Unit tests for accountOptedIn() directly: it opens the marker path ONCE+// (openSync) and validates mode + content off that same file descriptor+// (fstatSync, then readFileSync(fd, ...)) rather than doing an+// existsSync/statSync-by-path followed by a separate readFileSync-by-path —+// the latter shape is a TOCTOU file-system race (CodeQL js/file-system-race:+// the path could be swapped between the permission check and the read).+{+ const optDir = mkdtempSync(join(tmpdir(), 'account-optin-'));+ const optMarker = join(optDir, '.heal-account-optin');++ assert.equal(accountOptedIn(optMarker), false, 'missing marker file must be rejected');++ writeFileSync(optMarker, 'wrong-token');+ chmodSync(optMarker, 0o600);+ assert.equal(accountOptedIn(optMarker), false, 'marker with the wrong content must be rejected');++ writeFileSync(optMarker, CLIPROXY_HEAL_OPTIN_TOKEN);+ chmodSync(optMarker, 0o666);+ assert.equal(+ accountOptedIn(optMarker),+ false,+ 'group/other-writable marker must be rejected even with correct content',+ );++ writeFileSync(optMarker, CLIPROXY_HEAL_OPTIN_TOKEN);+ chmodSync(optMarker, 0o600);+ assert.equal(accountOptedIn(optMarker), true, 'a 0600 marker with the exact token must be accepted');++ // Trailing whitespace (a trailing newline from an editor or `echo`, for+ // instance) must not defeat an otherwise-correct marker.+ writeFileSync(optMarker, `${CLIPROXY_HEAL_OPTIN_TOKEN}\n`);+ chmodSync(optMarker, 0o600);+ assert.equal(accountOptedIn(optMarker), true, 'trailing whitespace in an otherwise-correct marker is tolerated');+}++console.log('cliproxy-heal-policy.test.mjs: ok');++process.env.CLIPROXY_HUB_HEAL = savedHubHeal;+process.env.CLIPROXY_ROOT = savedCliproxyRoot;+process.env.CLIPROXY_CONFIG = savedConfig;+process.env.CLIPROXY_ISOLATE_DIR = savedIsolateDir;+process.env.CLIPROXY_ISOLATE_MANIFEST = savedIsolateManifest;+if (savedHubHeal === undefined) delete process.env.CLIPROXY_HUB_HEAL;+if (savedCliproxyRoot === undefined) delete process.env.CLIPROXY_ROOT;+if (savedConfig === undefined) delete process.env.CLIPROXY_CONFIG;+if (savedIsolateDir === undefined) delete process.env.CLIPROXY_ISOLATE_DIR;+if (savedIsolateManifest === undefined) delete process.env.CLIPROXY_ISOLATE_MANIFEST;diff --git a/claude-ops/scripts/account-rotation/__tests__/cliproxy-isolate-compat.test.mjs b/claude-ops/scripts/account-rotation/__tests__/cliproxy-isolate-compat.test.mjsnew file mode 100644index 00000000..8060c1a2--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/cliproxy-isolate-compat.test.mjs@@ -0,0 +1,219 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { isolateCompatYaml, applyIsolateCompat, splitCompatItems } from '../cliproxy-isolate-compat.mjs';++const yaml = `host: 127.0.0.1+port: 8319+openai-compatibility:+- name: kimi+ base-url: https://api.kimi.example/v1+ api-key-entries:+ - api-key: fake-kimi-key+ models:+ - name: k3+ alias: kimi-k3+- name: opencode-go+ base-url: https://opencode.example/v1+ api-key-entries:+ - api-key: fake-opencode-key+ models:+ - name: glm-5+ alias: go-glm-5+ - name: mimo-v2.5+ alias: go-mimo-v2.5+- name: gemini+ base-url: https://gemini.example/v1+ api-key-entries:+ - api-key: fake-gemini-key+ models:+ - name: gemini-2.5-flash+auth-auto-refresh-workers: 16+ws-auth: true+`;++const split = splitCompatItems(yaml);+assert.deepEqual(+ split.items.map((it) => it.name),+ ['kimi', 'opencode-go', 'gemini'],+);++const isolated = isolateCompatYaml(yaml, ['opencode-go']);+assert.deepEqual(+ isolated.removed.map((it) => it.name),+ ['opencode-go'],+);+assert.deepEqual(isolated.kept, ['kimi', 'gemini']);+assert.match(isolated.yaml, /^- name: kimi$/m);+assert.match(isolated.yaml, /^- name: gemini$/m);+assert.doesNotMatch(isolated.yaml, /^- name: opencode-go$/m);+assert.match(isolated.yaml, /^auth-auto-refresh-workers: 16$/m);+assert.match(isolated.yaml, /fake-kimi-key/);+assert.doesNotMatch(isolated.yaml, /fake-opencode-key/);++const dir = mkdtempSync(join(tmpdir(), 'cliproxy-isolate-'));+const configPath = join(dir, 'config.yaml');+const isolateDir = join(dir, 'isolated');+const manifestPath = join(dir, 'manifest.json');+writeFileSync(configPath, yaml);+writeFileSync(+ manifestPath,+ JSON.stringify({+ providers: ['opencode-go'],+ reasons: { 'opencode-go': 'CreditsError: no payment method' },+ }),+);++const applied = applyIsolateCompat({ configPath, isolateDir, manifestPath });+assert.equal(applied.ok, true);+assert.deepEqual(applied.removed, ['opencode-go']);+assert.equal(existsSync(join(isolateDir, 'opencode-go.yaml')), true);+const after = readFileSync(configPath, 'utf8');+assert.doesNotMatch(after, /^- name: opencode-go$/m);+assert.match(after, /^- name: kimi$/m);+assert.match(readFileSync(join(isolateDir, 'opencode-go.yaml'), 'utf8'), /fake-opencode-key/);++const second = applyIsolateCompat({ configPath, isolateDir, manifestPath });+assert.equal(second.unchanged, true);++// Regression: openai-compatibility sequences indented under the key (valid+// YAML) must still be detected — a column-0-only scan silently returns zero+// items and leaves an unservable provider advertised.+const indentedYaml = `host: 127.0.0.1+port: 8319+openai-compatibility:+ - name: kimi+ base-url: https://api.kimi.example/v1+ api-key-entries:+ - api-key: fake-kimi-key+ models:+ - name: k3+ alias: kimi-k3+ - name: opencode-go+ base-url: https://opencode.example/v1+ api-key-entries:+ - api-key: fake-opencode-key+ models:+ - name: glm-5+ alias: go-glm-5+auth-auto-refresh-workers: 16+`;+const indentedSplit = splitCompatItems(indentedYaml);+assert.deepEqual(+ indentedSplit.items.map((it) => it.name),+ ['kimi', 'opencode-go'],+ 'indented openai-compatibility sequence must be detected, not silently return zero items',+);+const indentedIsolated = isolateCompatYaml(indentedYaml, ['opencode-go']);+assert.deepEqual(+ indentedIsolated.removed.map((it) => it.name),+ ['opencode-go'],+);+assert.deepEqual(indentedIsolated.kept, ['kimi']);++// Regression: a comment-only line right after the `openai-compatibility:`+// header, and a comment-only line between two same-depth items, are both+// valid YAML and must not stop the scan — a provider after either comment+// must still be parsed and remain isolatable.+const commentedYaml = `host: 127.0.0.1+port: 8319+openai-compatibility:+ # header comment before the first item+- name: kimi+ base-url: https://api.kimi.example/v1+ api-key-entries:+ - api-key: fake-kimi-key+ models:+ - name: k3+ alias: kimi-k3+# comment between kimi and opencode-go+- name: opencode-go+ base-url: https://opencode.example/v1+ api-key-entries:+ - api-key: fake-opencode-key+ models:+ - name: glm-5+ alias: go-glm-5+- name: gemini+ base-url: https://gemini.example/v1+ api-key-entries:+ - api-key: fake-gemini-key+ models:+ - name: gemini-2.5-flash+auth-auto-refresh-workers: 16+`;+const commentedSplit = splitCompatItems(commentedYaml);+assert.deepEqual(+ commentedSplit.items.map((it) => it.name),+ ['kimi', 'opencode-go', 'gemini'],+ 'a comment after the header, and a comment between items, must not truncate the scan',+);++const commentedIsolated = isolateCompatYaml(commentedYaml, ['opencode-go']);+assert.deepEqual(+ commentedIsolated.removed.map((it) => it.name),+ ['opencode-go'],+ 'opencode-go must still be isolatable when preceded by a comment line',+);+assert.deepEqual(commentedIsolated.kept, ['kimi', 'gemini']);+assert.match(commentedIsolated.yaml, /^- name: kimi$/m);+assert.match(commentedIsolated.yaml, /^- name: gemini$/m);+assert.doesNotMatch(commentedIsolated.yaml, /^- name: opencode-go$/m);+// The comment attached to the removed item travels with it into the+// isolated block, not into the rewritten config.yaml.+assert.doesNotMatch(commentedIsolated.yaml, /comment between kimi and opencode-go/);+assert.match(commentedIsolated.removed[0].lines.join('\n'), /comment between kimi and opencode-go/);+// The header comment is attached to kept item "kimi" and is preserved.+assert.match(commentedIsolated.yaml, /header comment before the first item/);++// Regression: a same-depth comment that follows the LAST item in the list+// must keep its original position (attached after that item, before+// whatever key follows the list), not be silently dropped. The inner loop+// that reads an item's body stops as soon as it sees a comment at or above+// the item's own indent, so the outer loop buffers it as `pendingComments`+// — and previously discarded that buffer entirely when the list then ended+// with no further item to attach it to.+const trailingCommentYaml = `host: 127.0.0.1+port: 8319+openai-compatibility:+- name: kimi+ base-url: https://api.kimi.example/v1+ api-key-entries:+ - api-key: fake-kimi-key+ models:+ - name: k3+ alias: kimi-k3+- name: gemini+ base-url: https://gemini.example/v1+ api-key-entries:+ - api-key: fake-gemini-key+ models:+ - name: gemini-2.5-flash+# trailing comment after the last provider+auth-auto-refresh-workers: 16+ws-auth: true+`;+const trailingSplit = splitCompatItems(trailingCommentYaml);+assert.deepEqual(+ trailingSplit.items.map((it) => it.name),+ ['kimi', 'gemini'],+);+assert.match(+ trailingSplit.after,+ /^# trailing comment after the last provider$/m,+ 'a comment after the final item must be preserved in `after`, not dropped',+);+assert.match(trailingSplit.after, /^auth-auto-refresh-workers: 16$/m);++const trailingIsolated = isolateCompatYaml(trailingCommentYaml, ['gemini']);+assert.deepEqual(trailingIsolated.kept, ['kimi']);+assert.match(+ trailingIsolated.yaml,+ /^# trailing comment after the last provider$/m,+ 'round-tripping through isolateCompatYaml must not lose the trailing comment',+);+assert.match(trailingIsolated.yaml, /^auth-auto-refresh-workers: 16$/m);++console.log('cliproxy-isolate-compat.test.mjs: ok');diff --git a/claude-ops/scripts/account-rotation/auto-auth-policy.mjs b/claude-ops/scripts/account-rotation/auto-auth-policy.mjsindex 5a28c635..92cbae9a 100644--- a/claude-ops/scripts/account-rotation/auto-auth-policy.mjs+++ b/claude-ops/scripts/account-rotation/auto-auth-policy.mjs@@ -1,5 +1,38 @@-/** Configuration alone is never a signed, exact mutation authorization. */-export function automatedAuthAllowed(_account) {+/**+ * Mac / plugin credential mutation stays fail-closed.+ * The hub CLIProxy healer is the only unattended path, gated by two+ * factors on genuinely different control planes: CLIPROXY_HUB_HEAL=1+ * ("this process is allowed to mutate credentials at all", a process+ * environment variable — settable by anyone who can edit the systemd+ * unit's Environment= lines or export it in a shell) and+ * account.cliproxyHubHeal ("this host was deliberately provisioned for+ * unattended healing", a filesystem fact — cliproxy-heal-tick.mjs derives+ * it from a marker file at a FIXED path (CLIPROXY_ROOT + '/.heal-account-optin',+ * not itself overridable by any env var) whose CONTENT must equal a fixed+ * expected token, not merely exist. Content-gating (rather than+ * existence-gating) is what makes this a real second factor: existence-only+ * would let an Environment=-only change point at any file that already+ * exists on the host (e.g. /etc/hosts) and satisfy the gate without ever+ * running install-heal.sh. Only install-heal.sh writes that exact token, so+ * a single environment flip cannot forge the second factor — it genuinely+ * requires an install-time step against /opt/crsproxy. Direct OAuth writers+ * stay denied everywhere (the hub binary owns refresh; the Mac is+ * client-only).+ */+/**+ * Expected content of the unattended-healing opt-in marker file. install-heal.sh+ * is the only writer; cliproxy-heal-tick.mjs reads it back and treats the+ * marker as absent unless the content matches exactly (see this file's+ * top-of-file comment for why content, not mere existence, is required).+ * Bump the suffix if the marker's meaning ever changes, so a stale marker+ * left over from an older install cannot silently opt a host back in.+ */+export const CLIPROXY_HEAL_OPTIN_TOKEN = 'cliproxy-heal-optin-v1';++export function automatedAuthAllowed(account) {+ if (account && account.cliproxyHubHeal === true && process.env.CLIPROXY_HUB_HEAL === '1') {+ return true;+ }return false;}diff --git a/claude-ops/scripts/account-rotation/cliproxy-heal-ai.mjs b/claude-ops/scripts/account-rotation/cliproxy-heal-ai.mjsnew file mode 100644index 00000000..20729bf0--- /dev/null+++ b/claude-ops/scripts/account-rotation/cliproxy-heal-ai.mjs@@ -0,0 +1,100 @@+/**+ * Bounded generative advisor for the CLIProxy healer.+ * Talks to the local CLIProxy OpenAI-compat endpoint. Hard quota rules in+ * cliproxy-heal-policy.mjs always win; this module only proposes JSON.+ */+import { ACTIONS } from './cliproxy-heal-policy.mjs';++const DEFAULT_MODEL = process.env.CLIPROXY_HEAL_MODEL || 'grok-3-mini';+const REQUEST_TIMEOUT_MS = 20_000;++export function buildHealerPrompt(facts) {+ return [+ 'You advise a CLIProxy seat rotator. Return ONLY one JSON object. No markdown.',+ `Schema: {"inRotation": true|false, "action": "${Object.values(ACTIONS).join('|')}", "reason": "short"}`,+ 'Hard rules you must obey:',+ '- Remaining, reset, or newly observed quota → inRotation true. No hysteresis.',+ '- inRotation false only if quota is certainly exhausted AND a parseable reschedule datetime exists.',+ '- Uncertain exhaust (no proven quota exhausted, or no stamp) → inRotation true (heal/keep serving).',+ '- Paid leftover quota stays serving.',+ '',+ 'Facts:',+ JSON.stringify(facts),+ ].join('\n');+}++export function parseAdviceText(text) {+ if (!text) return null;+ let cleaned = String(text).trim();+ cleaned = cleaned+ .replace(/^```(?:json|JSON)?\s*/i, '')+ .replace(/```\s*$/i, '')+ .trim();+ const m = cleaned.match(/\{[\s\S]*\}/);+ if (!m) return null;+ try {+ const parsed = JSON.parse(m[0]);+ if (!parsed || typeof parsed !== 'object') return null;+ return parsed;+ } catch {+ return null;+ }+}++// This module never reads files itself. cliproxy-heal-tick.mjs is the only+// caller allowed to read config.yaml's api-keys entry off disk+// (readApiKeyFromConfig), and it stores that value into process.env+// (CLIPROXY_API_KEY) rather than passing the readFileSync() result straight+// into askCliproxyHealer's arguments — so the apiKey this function receives+// always traces back to a process.env read, the same as CLIPROXYAPI_KEY,+// never directly to a file read. Re-validate against a strict allowlist+// immediately before the fetch sink anyway, as defense-in-depth for any+// future caller that passes apiKey directly.+const API_KEY_RE = /^[A-Za-z0-9_.\-:]{1,256}$/;++export async function askCliproxyHealer(facts, { baseUrl, apiKey, model, fetchImpl } = {}) {+ const urlBase = (baseUrl || process.env.CLIPROXY_HEAL_BASE_URL || process.env.CLIPROXYAPI_BASE_URL || '').replace(+ /\/$/,+ '',+ );+ const rawKey = apiKey || process.env.CLIPROXY_API_KEY || process.env.CLIPROXYAPI_KEY || '';+ if (!urlBase || !rawKey) {+ return { inRotation: facts?.hard?.inRotation, action: facts?.hard?.action, reason: 'no_cliproxy_endpoint' };+ }+ const keyMatch = API_KEY_RE.exec(String(rawKey));+ if (!keyMatch) {+ return { inRotation: facts?.hard?.inRotation, action: facts?.hard?.action, reason: 'invalid_api_key_format' };+ }+ const fetchFn = fetchImpl || globalThis.fetch;+ const res = await fetchFn(`${urlBase}/v1/chat/completions`, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${keyMatch[0]}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model: model || DEFAULT_MODEL,+ temperature: 0,+ max_tokens: 220,+ messages: [{ role: 'user', content: buildHealerPrompt(facts) }],+ }),+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ return {+ inRotation: facts?.hard?.inRotation,+ action: facts?.hard?.action,+ reason: `http_${res.status}`,+ };+ }+ const text = data?.choices?.[0]?.message?.content || data?.choices?.[0]?.text || '';+ const parsed = parseAdviceText(text);+ return (+ parsed || {+ inRotation: facts?.hard?.inRotation,+ action: facts?.hard?.action,+ reason: 'unparseable_model',+ }+ );+}diff --git a/claude-ops/scripts/account-rotation/cliproxy-heal-policy.mjs b/claude-ops/scripts/account-rotation/cliproxy-heal-policy.mjsnew file mode 100644index 00000000..493c3128--- /dev/null+++ b/claude-ops/scripts/account-rotation/cliproxy-heal-policy.mjs@@ -0,0 +1,235 @@+/**+ * Pure CLIProxy seat rotate / re-entry / heal policy.+ *+ * Hard rules (cannot be overridden by the AI advisor):+ * 1. Remaining, reset, or newly observed quota → in rotation immediately.+ * No high-water / low-water hysteresis.+ * 2. Out of rotation only when quota is known-certain exhausted AND a+ * parseable reschedule datetime is recorded. At that stamp, re-enter.+ * 3. Uncertain exhaust (no proven "quota exhausted", or no stamp) → keep+ * serving / heal back in.+ * 4. A paid seat with leftover quota stays serving.+ */+export const ACTIONS = {+ ENTER: 'enter_rotation',+ LEAVE: 'leave_rotation',+ KEEP_IN: 'keep_in_rotation',+ KEEP_OUT: 'keep_out_until_reschedule',+ HEAL: 'heal_into_rotation',+};++const CERTAIN_EXHAUST_RE =+ /quota\s*exhausted|credential_quota|usage_limit_reached|usage limit has been reached|quota_exceeded|\bquota exceeded\b/i;++// Shared guard for both numeric-epoch paths: reject non-finite, non-positive,+// and out-of-range (year 2020-2100) values before they can be treated as a+// valid reschedule stamp. A corrupt or zero stamp must never look "elapsed".+function fromEpoch(n) {+ if (!Number.isFinite(n) || n <= 0) return null;+ const ms = n < 1e12 ? n * 1000 : n;+ const d = new Date(ms);+ if (Number.isNaN(d.getTime())) return null;+ const year = d.getUTCFullYear();+ if (year < 2020 || year > 2100) return null;+ return d.getTime();+}++export function parseTimestamp(value, now = Date.now()) {+ if (value == null || value === '') return null;+ if (typeof value === 'number' && Number.isFinite(value)) {+ return fromEpoch(value);+ }+ const raw = String(value).trim();+ if (!raw || raw.startsWith('0001-01-01')) return null;+ if (/^\d+(\.\d+)?$/.test(raw)) {+ return fromEpoch(Number(raw));+ }+ const parsed = Date.parse(raw.replace('Z', '+00:00'));+ if (!Number.isFinite(parsed)) return null;+ const year = new Date(parsed).getUTCFullYear();+ if (year < 2020 || year > 2100) return null;+ return parsed;+}++export function detectCertainExhaust({+ certainQuotaExhausted,+ lastExhaustReason,+ lastExhaustBody,+ quotaExceeded,+ quotaReason,+} = {}) {+ if (certainQuotaExhausted === true) return true;+ if (certainQuotaExhausted === false) return false;+ const blob = [lastExhaustReason, lastExhaustBody, quotaReason].filter(Boolean).join(' ');+ if (CERTAIN_EXHAUST_RE.test(blob)) return true;+ // CLIProxy writes quota.exceeded=true on a credential/usage window. That is+ // the certain-exhaust signal; the stamp is checked separately.+ if (quotaExceeded === true) return true;+ return false;+}++export function hasRemainingOrResetQuota(seat = {}) {+ if (seat.newQuotaObserved === true) return true;+ if (seat.quotaReset === true) return true;+ const rem = Number(seat.remainingQuota);+ if (Number.isFinite(rem) && rem > 0) return true;+ // Exceeded flipped off (or remaining appeared) while a cooldown sidecar still+ // exists — leftover/reset quota, re-enter immediately. Stream-error cooling+ // with quotaExceeded null/undefined is not leftover quota. A certain-exhaust+ // signal (e.g. a "usage_limit_reached" body) is not leftover quota either —+ // rule 2 (certain exhaust + stamp) owns that seat, and this rule must not+ // short-circuit it and re-enter a seat the provider still rejects.+ if (seat.quotaExceeded === false && seat.hadQuotaSignal === true && seat.certainQuotaExhausted !== true) {+ return true;+ }+ return false;+}++function pickAction(inRotation, currentlyIn, heal) {+ if (inRotation) {+ if (currentlyIn) return ACTIONS.KEEP_IN;+ return heal ? ACTIONS.HEAL : ACTIONS.ENTER;+ }+ return currentlyIn ? ACTIONS.LEAVE : ACTIONS.KEEP_OUT;+}++/**+ * Decide whether a seat belongs in rotation. Pure. now is epoch ms.+ */+export function decideSeat(seat, now = Date.now()) {+ const currentlyIn = seat.inRotation === true;+ if (hasRemainingOrResetQuota(seat)) {+ return {+ inRotation: true,+ action: pickAction(true, currentlyIn, false),+ reason: 'remaining_or_reset_quota',+ rescheduleAt: null,+ };+ }++ const certain = detectCertainExhaust(seat);+ const until = parseTimestamp(seat.rescheduleAt, now);++ if (certain && until != null && until > now) {+ return {+ inRotation: false,+ action: pickAction(false, currentlyIn, false),+ reason: 'certain_exhaust_until_reschedule',+ rescheduleAt: new Date(until).toISOString(),+ };+ }++ if (certain && until != null && until <= now) {+ return {+ inRotation: true,+ action: pickAction(true, currentlyIn, false),+ reason: 'reschedule_elapsed',+ rescheduleAt: new Date(until).toISOString(),+ };+ }++ return {+ inRotation: true,+ action: pickAction(true, currentlyIn, !currentlyIn),+ reason: 'uncertain_exhaust_keep_serving',+ rescheduleAt: until != null ? new Date(until).toISOString() : null,+ };+}++function adviceWantsIn(advice) {+ if (!advice || typeof advice !== 'object') return null;+ if (typeof advice.inRotation === 'boolean') return advice.inRotation;+ const action = String(advice.action || '');+ if (action === ACTIONS.LEAVE || action === ACTIONS.KEEP_OUT || action === 'leave' || action === 'out') {+ return false;+ }+ if (+ action === ACTIONS.ENTER ||+ action === ACTIONS.KEEP_IN ||+ action === ACTIONS.HEAL ||+ action === 'enter' ||+ action === 'heal' ||+ action === 'in'+ ) {+ return true;+ }+ return null;+}++/**+ * Overlay advisor output on a hard decision. Advisor cannot flip inRotation.+ */+export function applyAdviceIfLegal(hard, advice) {+ const wantsIn = adviceWantsIn(advice);+ if (wantsIn == null) {+ return { ...hard, ai: { invoked: true, applied: false, reason: 'unparseable' } };+ }+ if (Boolean(wantsIn) !== Boolean(hard.inRotation)) {+ return {+ ...hard,+ ai: { invoked: true, applied: false, reason: 'violates_hard_rules', advice },+ };+ }+ const next = { ...hard, ai: { invoked: true, applied: true, advice } };+ if (advice.action && Object.values(ACTIONS).includes(advice.action)) {+ next.action = advice.action;+ }+ if (advice.reason) next.aiReason = String(advice.reason).slice(0, 240);+ return next;+}++export async function adviseSeat(seat, hard, ask) {+ if (typeof ask !== 'function') {+ return { ...hard, ai: { invoked: false, applied: false, reason: 'no_ask' } };+ }+ try {+ const advice = await ask({+ id: seat.id,+ provider: seat.provider,+ disabled: seat.disabled === true,+ cooling: seat.cooling === true,+ remainingQuota: seat.remainingQuota ?? null,+ quotaExceeded: seat.quotaExceeded ?? null,+ certainQuotaExhausted: detectCertainExhaust(seat),+ rescheduleAt: seat.rescheduleAt ?? null,+ lastExhaustReason: seat.lastExhaustReason ?? null,+ tokenStale: seat.tokenStale === true,+ paidSeat: seat.paidSeat !== false,+ hard,+ });+ return applyAdviceIfLegal(hard, advice);+ } catch (err) {+ return {+ ...hard,+ ai: { invoked: true, applied: false, reason: `ask_failed:${String(err?.message || err).slice(0, 80)}` },+ };+ }+}++/**+ * Decision entry for a pool snapshot. Always invokes `ask` per seat when given.+ */+export async function healPool(seats, { now = Date.now(), ask } = {}) {+ const list = Array.isArray(seats) ? seats : [];+ const decisions = await Promise.all(+ list.map(async (seat) => {+ const hard = decideSeat(seat, now);+ const advised = await adviseSeat(seat, hard, ask);+ return {+ id: seat.id,+ // Internal-only: the un-opaqued identifier, needed by the reauth+ // writer to target the right credential file. Never surfaced through+ // the actions/state allowlists built in cliproxy-heal-tick.mjs.+ rawId: seat.rawId || null,+ provider: seat.provider || null,+ tokenStale: seat.tokenStale === true,+ disabled: seat.disabled === true,+ cooling: seat.cooling === true,+ authFile: seat.authFile || null,+ cdsFile: seat.cdsFile || null,+ ...advised,+ };+ }),+ );+ return { now, decisions };+}diff --git a/claude-ops/scripts/account-rotation/cliproxy-heal-tick.mjs b/claude-ops/scripts/account-rotation/cliproxy-heal-tick.mjsnew file mode 100644index 00000000..932c2d74--- /dev/null+++ b/claude-ops/scripts/account-rotation/cliproxy-heal-tick.mjs@@ -0,0 +1,416 @@+#!/usr/bin/env node+/**+ * Unattended CLIProxy healer tick.+ *+ * Reads auth-dir json + .cds, runs healPool (hard rules + AI advisor),+ * then applies: enable leftover-quota seats, clear stale cooldowns, persist+ * reschedule stamps, request reauth for stale tokens.+ *+ * Hub systemd sets CLIPROXY_HUB_HEAL=1. Without that flag this process+ * refuses to mutate credentials (Mac stays client-only).+ *+ * node cliproxy-heal-tick.mjs [--dry-run] [--status] [--auth-dir DIR]+ */+import {+ closeSync,+ existsSync,+ fstatSync,+ mkdirSync,+ openSync,+ readFileSync,+ renameSync,+ writeFileSync,+} from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { automatedAuthAllowed, CLIPROXY_HEAL_OPTIN_TOKEN } from './auto-auth-policy.mjs';+import { healPool } from './cliproxy-heal-policy.mjs';+import { askCliproxyHealer } from './cliproxy-heal-ai.mjs';+import { censusFromSeats, redactSeat, snapshotFromAuthDir } from './cliproxy-pool-snapshot.mjs';+import { applyIsolateCompat } from './cliproxy-isolate-compat.mjs';++const __dirname = dirname(fileURLToPath(import.meta.url));++export function defaultAuthDir() {+ return process.env.CLIPROXY_AUTH_DIR || '/opt/crsproxy/auths';+}++export function defaultStatePath(authDir) {+ return process.env.CLIPROXY_HEAL_STATE || join(dirname(authDir), '.cliproxy-heal-state.json');+}++function loadState(path) {+ if (!path || !existsSync(path)) return { version: 1, seats: {} };+ try {+ const parsed = JSON.parse(readFileSync(path, 'utf8'));+ if (!parsed || typeof parsed !== 'object') return { version: 1, seats: {} };+ if (!parsed.seats || typeof parsed.seats !== 'object') parsed.seats = {};+ return parsed;+ } catch {+ return { version: 1, seats: {} };+ }+}++function saveState(path, state) {+ mkdirSync(dirname(path), { recursive: true });+ const tmp = `${path}.tmp`;+ writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });+ renameSync(tmp, path);+}++// Second unattended-healing gate (see auto-auth-policy.mjs). The path is+// deliberately NOT overridable by its own env var — only CLIPROXY_ROOT (the+// same variable that also relocates auth dir, state, config, etc., so+// changing it is a coordinated redeploy, not a one-line escalation) can move+// it, and even then the filename stays fixed. Existence alone is not+// sufficient: the file's content must equal CLIPROXY_HEAL_OPTIN_TOKEN, which+// only install-heal.sh writes, so an Environment=-only change that points+// at some other pre-existing file (e.g. /etc/hosts) cannot satisfy the gate.+// A marker that is group/other-writable is also rejected — a marker+// install-heal.sh actually wrote is mode 0600.+export function accountOptedIn(path) {+ // Open once and validate the mode + content of that SAME file descriptor —+ // not two independent lookups by path (existsSync/statSync, then a+ // separate readFileSync by path) — so there is no window between the+ // permission check and the read in which the path could be swapped to a+ // different file (a TOCTOU / file-system race).+ let fd;+ try {+ fd = openSync(path, 'r');+ } catch {+ return false; // missing, or unreadable — either way, not opted in+ }+ try {+ const stat = fstatSync(fd);+ if ((stat.mode & 0o022) !== 0) return false;+ return readFileSync(fd, 'utf8').trim() === CLIPROXY_HEAL_OPTIN_TOKEN;+ } catch {+ return false;+ } finally {+ closeSync(fd);+ }+}++function writeJsonAtomic(path, data) {+ const tmp = `${path}.tmp`;+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });+ renameSync(tmp, path);+}++function readAuth(path) {+ const parsed = JSON.parse(readFileSync(path, 'utf8'));+ if (!parsed || typeof parsed !== 'object') {+ throw new Error(`auth file is not an object: ${path}`);+ }+ return parsed;+}++export function normalizeReauthOutcome(ret) {+ if (ret === true) return { ok: true, blocked: false, reason: 'reauth_ok' };+ if (ret && typeof ret === 'object' && 'ok' in ret) {+ const ok = ret.ok === true;+ return {+ ok,+ blocked: ok ? false : ret.blocked !== false,+ reason: String(ret.reason || (ok ? 'reauth_ok' : 'reauth_failed')).slice(0, 160),+ };+ }+ return { ok: false, blocked: true, reason: 'no_reauth_writer' };+}++export function defaultReauth(decision) {+ const cmd = process.env.CLIPROXY_REAUTH_CMD;+ if (!cmd || !existsSync(cmd)) {+ return { ok: false, blocked: true, reason: 'no_reauth_writer' };+ }+ const r = spawnSync(cmd, [decision.provider || '', decision.rawId || decision.id || '', decision.authFile || ''], {+ timeout: 90_000,+ stdio: 'ignore',+ env: { ...process.env, CLIPROXY_HUB_HEAL: '1' },+ });+ if (r.status === 0) return { ok: true, blocked: false, reason: 'reauth_ok' };+ if (r.status === 2) return { ok: false, blocked: true, reason: 'reauth_checkpoint' };+ if (r.status == null && r.signal) return { ok: false, blocked: true, reason: `reauth_signal_${r.signal}` };+ return { ok: false, blocked: true, reason: `reauth_exit_${r.status ?? 'unknown'}` };+}++export function applyDecision(decision, { dryRun = false, reauth } = {}) {+ const applied = [];+ let blocked = null;+ if (decision.inRotation) {+ if (decision.disabled && decision.authFile) {+ applied.push('enable_auth');+ if (!dryRun) {+ const auth = readAuth(decision.authFile);+ auth.disabled = false;+ delete auth.disabled_reason;+ auth.healer_enabled_at = new Date().toISOString();+ writeJsonAtomic(decision.authFile, auth);+ }+ }+ // Only clear the CLIProxy quota sidecar when this seat actually carried a+ // cooldown record: it is still cooling per its own signal, or its+ // reschedule stamp just elapsed (reason 'reschedule_elapsed'). decideSeat+ // also returns inRotation:true for healthy seats with a coincidental+ // leftover .cds file ('remaining_or_reset_quota' with cooling:false) and+ // for uncertain-exhaust seats that were never actually cooling — deleting+ // their sidecar destroys the proxy's own quota/reset-at evidence for no+ // reason and is not reversible. Rename instead of unlink so a mistaken+ // clear can still be recovered from disk.+ if (+ (decision.cooling === true || decision.reason === 'reschedule_elapsed') &&+ decision.cdsFile &&+ existsSync(decision.cdsFile)+ ) {+ applied.push('clear_cooldown');+ if (!dryRun) {+ renameSync(decision.cdsFile, `${decision.cdsFile}.healed`);+ }+ }+ if (decision.tokenStale) {+ const runner = reauth === undefined ? defaultReauth : reauth;+ let outcome = { ok: false, blocked: true, reason: 'no_reauth_writer' };+ if (dryRun) {+ const writerReady =+ typeof reauth === 'function' ||+ (Boolean(process.env.CLIPROXY_REAUTH_CMD) && existsSync(process.env.CLIPROXY_REAUTH_CMD));+ outcome = writerReady+ ? { ok: true, blocked: false, reason: 'reauth_ok' }+ : { ok: false, blocked: true, reason: 'no_reauth_writer' };+ } else if (typeof runner === 'function') {+ outcome = normalizeReauthOutcome(runner(decision));+ }+ if (outcome.ok) applied.push('reauth');+ else {+ applied.push('blocked');+ blocked = { reason: outcome.reason || 'no_reauth_writer', tokenStale: true };+ }+ }+ } else if (decision.rescheduleAt) {+ // persist_reschedule alone only wrote the healer's own state file, which+ // has no consumer inside CLIProxy — the seat stayed advertised and the+ // proxy kept routing to it. Actually remove the seat from rotation using+ // the mechanism CLIProxy itself honors: the `disabled` flag on the auth+ // file. Re-entry still happens exactly when this decision flips (rule 2's+ // reschedule check), which flows through the enable_auth branch above.+ applied.push('persist_reschedule');+ if (decision.authFile && !decision.disabled) {+ applied.push('leave_rotation');+ if (!dryRun) {+ const auth = readAuth(decision.authFile);+ auth.disabled = true;+ auth.disabled_reason = `cliproxy-heal: certain_exhaust_until_reschedule (${decision.rescheduleAt})`;+ auth.healer_disabled_at = new Date().toISOString();+ writeJsonAtomic(decision.authFile, auth);+ }+ }+ }+ return { applied, blocked };+}++function readApiKeyFromConfig(configPath) {+ if (!configPath || !existsSync(configPath)) return '';+ try {+ const text = readFileSync(configPath, 'utf8');+ const m = text.match(/api-keys:\s*\n(?:- |\s+- )([^\s#]+)/);+ return m ? m[1].trim() : '';+ } catch {+ return '';+ }+}++export async function runHealTick({+ authDir = defaultAuthDir(),+ statePath = defaultStatePath(authDir),+ now = Date.now(),+ ask,+ dryRun = false,+ log = console.log,+ reauth,+} = {}) {+ // Two gates on different control planes: CLIPROXY_HUB_HEAL says "this+ // process may mutate credentials at all" (a process env var — settable by+ // editing the systemd unit's Environment= lines or exporting it in a+ // shell). accountOptInMarker says "this host was deliberately provisioned+ // for unattended healing" — it is satisfied only by a marker file, at a+ // fixed path, whose content matches the token only install-heal.sh writes+ // (see accountOptedIn() above). Editing the unit's Environment= lines+ // cannot produce that file or its content, so a single environment flip+ // cannot satisfy both gates.+ const accountOptInMarker = join(process.env.CLIPROXY_ROOT || '/opt/crsproxy', '.heal-account-optin');+ if (!automatedAuthAllowed({ cliproxyHubHeal: accountOptedIn(accountOptInMarker) })) {+ log(+ `heal denied: CLIPROXY_HUB_HEAL unset and/or account opt-in marker missing at ${accountOptInMarker} (Mac client-only; hub must run install-heal.sh and export CLIPROXY_HUB_HEAL=1)`,+ );+ return { denied: true, decisions: [], census: censusFromSeats([], now) };+ }++ const prev = loadState(statePath);+ const { seats, census } = snapshotFromAuthDir(authDir, { now, previous: prev.seats });+ // Resolve the CLIProxy API key once, here, at the single point that is+ // allowed to read it off disk. The result is stored into the same env var+ // that a deployment can also set directly (CLIPROXY_API_KEY) rather than+ // threaded straight into askCliproxyHealer's arguments — so the value+ // askCliproxyHealer's fetch call actually uses always comes from a+ // process.env read, identically to the CLIPROXYAPI_KEY branch, and never+ // from a readFileSync() result flowing directly into that call.+ if (!process.env.CLIPROXY_API_KEY && !process.env.CLIPROXYAPI_KEY) {+ const configKey = readApiKeyFromConfig(process.env.CLIPROXY_CONFIG || '/opt/crsproxy/config.yaml');+ if (configKey) process.env.CLIPROXY_API_KEY = configKey;+ }+ const askFn =+ ask ||+ ((facts) =>+ askCliproxyHealer(facts, {+ baseUrl: process.env.CLIPROXY_HEAL_BASE_URL || process.env.CLIPROXYAPI_BASE_URL || 'http://127.0.0.1:8317',+ apiKey: process.env.CLIPROXY_API_KEY || process.env.CLIPROXYAPI_KEY,+ }));++ const result = await healPool(seats, { now, ask: askFn });+ const actions = [];+ const nextSeats = { ...prev.seats };++ let reauthBudget = 1;+ for (const decision of result.decisions) {+ let runner = reauth;+ if (runner === undefined) {+ runner = (d) => {+ if (reauthBudget <= 0) return { ok: false, blocked: true, reason: 'reauth_budget' };+ reauthBudget -= 1;+ return defaultReauth(d);+ };+ }+ // Isolate each seat: a truncated auth file, a permission error, or a+ // concurrent delete by the proxy must not throw out of the loop and skip+ // every seat after it (and skip saveState entirely). Coding guideline:+ // never silently skip a channel/service/integration — so the failure is+ // logged with the seat's identity rather than swallowed.+ let applied = [];+ let blocked = null;+ try {+ ({ applied, blocked } = applyDecision(decision, { dryRun, reauth: runner }));+ } catch (err) {+ applied = [`error:${String(err?.message || err).slice(0, 120)}`];+ blocked = { reason: 'apply_decision_failed', tokenStale: decision.tokenStale === true };+ log(+ `heal seat failed id=${decision.id} provider=${decision.provider || '?'} action=${decision.action} err=${applied[0]}`,+ );+ }+ actions.push({+ id: decision.id,+ provider: decision.provider,+ inRotation: decision.inRotation,+ action: decision.action,+ reason: decision.reason,+ rescheduleAt: decision.rescheduleAt,+ ai: decision.ai,+ applied,+ blocked,+ });+ nextSeats[decision.id] = {+ remainingQuota: seats.find((s) => s.id === decision.id)?.remainingQuota ?? null,+ quotaExceeded: seats.find((s) => s.id === decision.id)?.quotaExceeded ?? null,+ certainQuotaExhausted: seats.find((s) => s.id === decision.id)?.certainQuotaExhausted === true,+ rescheduleAt: decision.rescheduleAt,+ inRotation: decision.inRotation,+ blocked: blocked || undefined,+ updatedAt: new Date(now).toISOString(),+ };+ }++ const state = {+ version: 1,+ updatedAt: new Date(now).toISOString(),+ census,+ seats: nextSeats,+ lastTick: actions.map((a) => ({+ id: a.id,+ provider: a.provider,+ inRotation: a.inRotation,+ action: a.action,+ reason: a.reason,+ rescheduleAt: a.rescheduleAt,+ aiInvoked: a.ai?.invoked === true,+ aiApplied: a.ai?.applied === true,+ applied: a.applied,+ blocked: a.blocked || undefined,+ })),+ };+ const isolate = applyIsolateCompat({+ configPath: process.env.CLIPROXY_CONFIG || '/opt/crsproxy/config.yaml',+ isolateDir: process.env.CLIPROXY_ISOLATE_DIR || join(dirname(authDir), 'isolated'),+ manifestPath: process.env.CLIPROXY_ISOLATE_MANIFEST || join(dirname(authDir), 'isolated', 'manifest.json'),+ dryRun,+ });+ if (isolate.removed?.length) {+ log(`isolated unservable compat providers: ${isolate.removed.join(',')}`);+ }+ if (!isolate.ok) {+ // applyIsolateCompat returns ok:false (e.g. missing_config) without+ // throwing. Silently continuing would leave an unservable openai-compat+ // provider advertised with no signal in the log or the returned result.+ // Surface it explicitly: log it, mark the tick failed in the returned+ // result (so --json / exit-code callers see it), and still persist the+ // seat-level state gathered so far rather than losing that work.+ log(`compat isolation FAILED reason=${isolate.reason || 'unknown'} — unservable providers may still be advertised`);+ }++ if (!dryRun) saveState(statePath, { ...state, isolate });++ log(+ `heal tick seats=${seats.length} enter=${actions.filter((a) => a.inRotation).length} out=${actions.filter((a) => !a.inRotation).length} dry=${dryRun}`,+ );+ for (const a of actions) {+ log(+ ` ${a.provider || '?'} ${a.action} in=${a.inRotation} reason=${a.reason} ai=${a.ai?.invoked ? (a.ai.applied ? 'applied' : a.ai.reason) : 'skip'} applied=${(a.applied || []).join(',') || 'none'} until=${a.rescheduleAt || '-'}`,+ );+ }++ return {+ denied: false,+ // Compat isolation failing is not a full tick failure (seat healing+ // above still ran and was persisted), but it is a failure the caller+ // must not treat as a clean run. Callers (the --json / exit-code CLI+ // below, or any other consumer of runHealTick) key off this field+ // instead of having to know to inspect isolate.ok themselves.+ failed: !isolate.ok,+ dryRun,+ census,+ seats: seats.map(redactSeat),+ decisions: result.decisions,+ actions,+ state,+ isolate,+ };+}++const isMain = Boolean(process.argv[1]) && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ const args = process.argv.slice(2);+ const dryRun = args.includes('--dry-run') || args.includes('--status');+ const dirFlag = args.indexOf('--auth-dir');+ const dirValue = dirFlag >= 0 ? args[dirFlag + 1] : undefined;+ if (dirFlag >= 0 && (!dirValue || dirValue.startsWith('--'))) {+ console.error('--auth-dir requires a directory path');+ process.exit(2);+ }+ const authDir = dirFlag >= 0 ? dirValue : defaultAuthDir();+ runHealTick({ authDir, dryRun, now: Date.now() })+ .then((out) => {+ if (args.includes('--json')) {+ const json = {+ denied: out.denied,+ failed: out.failed === true,+ census: out.census,+ actions: out.actions,+ };+ process.stdout.write(JSON.stringify(json, null, 2) + '\n');+ }+ process.exit(out.denied ? 2 : out.failed ? 3 : 0);+ })+ .catch((err) => {+ console.error(err);+ process.exit(1);+ });+}diff --git a/claude-ops/scripts/account-rotation/cliproxy-isolate-compat.mjs b/claude-ops/scripts/account-rotation/cliproxy-isolate-compat.mjsnew file mode 100644index 00000000..70fe2cfc--- /dev/null+++ b/claude-ops/scripts/account-rotation/cliproxy-isolate-compat.mjs@@ -0,0 +1,164 @@+/**+ * Isolate openai-compatibility providers that cannot serve (billing-dead,+ * region-blocked) so they are not advertised on /v1/models.+ *+ * Pure splice of CLIProxy config.yaml list items. Does not parse secrets.+ */+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++export function loadIsolateManifest(path) {+ if (!path || !existsSync(path)) return { providers: [], reasons: {} };+ try {+ const parsed = JSON.parse(readFileSync(path, 'utf8'));+ const providers = (parsed.providers || []).map((p) => String(p).toLowerCase()).filter(Boolean);+ return { providers, reasons: parsed.reasons && typeof parsed.reasons === 'object' ? parsed.reasons : {} };+ } catch {+ return { providers: [], reasons: {} };+ }+}++/**+ * Split openai-compatibility list items. Each item starts at a line matching+ * /^\s*- name: / — YAML permits the sequence indented under the key, not+ * only at column 0. The indentation of the FIRST such line under the key+ * sets the expected depth for every subsequent item boundary in this list,+ * so a nested list (e.g. `models:` / `api-key-entries:` inside an item) at a+ * deeper indent is never mistaken for a new top-level item.+ */+export function splitCompatItems(yamlText) {+ const lines = String(yamlText).split('\n');+ const start = lines.findIndex((l) => l.trim() === 'openai-compatibility:');+ if (start < 0) return { before: yamlText, items: [], after: '', start: -1 };++ let itemIndent = null;+ for (let j = start + 1; j < lines.length; j += 1) {+ const line = lines[j];+ // Blank lines and comment-only lines carry no indentation signal for the+ // list itself — valid YAML permits a `#`-only line (at any indent)+ // between the `openai-compatibility:` key and its first item, or between+ // any two items. Skip both while locating the first `- name:` line.+ if (line.trim() === '' || line.trim().startsWith('#')) continue;+ const m = line.match(/^(\s*)-\s*name:/);+ if (m) itemIndent = m[1].length;+ break;+ }++ const items = [];+ let i = start + 1;+ // Comment-only lines seen while looking for the next item start (either+ // before the first item, or between two same-depth items) are buffered+ // here and prepended to whichever item follows, so they survive+ // reassembly attached to that item. If the list ends without another item+ // (trailing comments after the last one, or before any item at all), the+ // buffer is NOT discarded — `i` has already advanced past those comment+ // lines, so `lines.slice(i)` no longer contains them; they are prepended+ // back onto `after` below so they keep their original position instead of+ // being silently dropped.+ let pendingComments = [];+ if (itemIndent != null) {+ const itemStartRe = new RegExp(`^\\s{${itemIndent}}-\\s*name:`);+ while (i < lines.length) {+ const line = lines[i];+ if (line.trim() === '') {+ i += 1;+ continue;+ }+ if (line.trim().startsWith('#')) {+ // Valid YAML permits a comment-only line, at any indent, between+ // the header and the first item or between two items — it does not+ // end the list.+ pendingComments.push(line);+ i += 1;+ continue;+ }+ if (itemStartRe.test(line)) {+ const name = line.slice(line.indexOf('name:') + 'name:'.length).trim();+ const begin = i;+ i += 1;+ while (i < lines.length) {+ const l = lines[i];+ if (l.trim() === '') {+ i += 1;+ continue;+ }+ if (itemStartRe.test(l)) break;+ const lineIndent = l.match(/^(\s*)/)[1].length;+ if (l.trim().startsWith('#') && lineIndent <= itemIndent) {+ // A comment at or above this item's own indent belongs to the+ // gap before the *next* item, not to this item's nested block —+ // stop here and let the outer loop buffer it.+ break;+ }+ if (lineIndent <= itemIndent) break;+ i += 1;+ }+ items.push({ name, lines: [...pendingComments, ...lines.slice(begin, i)] });+ pendingComments = [];+ continue;+ }+ // Not another item at this depth, not blank, not a comment — the list ended.+ break;+ }+ }++ return {+ before: lines.slice(0, start).join('\n'),+ header: 'openai-compatibility:',+ items,+ after: [...pendingComments, ...lines.slice(i)].join('\n'),+ start,+ };+}++export function isolateCompatYaml(yamlText, isolateNames) {+ const want = new Set((isolateNames || []).map((n) => String(n).toLowerCase()));+ const split = splitCompatItems(yamlText);+ if (split.start < 0 || want.size === 0) {+ return { yaml: yamlText, removed: [], kept: split.items?.map((it) => it.name) || [] };+ }+ const kept = [];+ const removed = [];+ for (const item of split.items) {+ if (want.has(String(item.name).toLowerCase())) removed.push(item);+ else kept.push(item);+ }+ const body = [split.header, ...kept.flatMap((it) => it.lines)].join('\n');+ const parts = [split.before, body];+ if (split.after) parts.push(split.after);+ let yaml = parts.join('\n');+ if (!yaml.endsWith('\n')) yaml += '\n';+ return { yaml, removed, kept: kept.map((it) => it.name) };+}++export function applyIsolateCompat({ configPath, isolateDir, manifestPath, names, dryRun = false } = {}) {+ if (!configPath || !existsSync(configPath)) {+ return { ok: false, reason: 'missing_config' };+ }+ const manifest = loadIsolateManifest(manifestPath);+ const isolateNames = names && names.length ? names : manifest.providers;+ if (!isolateNames.length) return { ok: true, removed: [], kept: [] };+ const original = readFileSync(configPath, 'utf8');+ const result = isolateCompatYaml(original, isolateNames);+ if (!result.removed.length) {+ return { ok: true, removed: [], kept: result.kept, unchanged: true };+ }+ if (!dryRun) {+ if (isolateDir) {+ mkdirSync(isolateDir, { recursive: true });+ for (const item of result.removed) {+ const dest = join(isolateDir, `${item.name}.yaml`);+ writeFileSync(dest, item.lines.join('\n') + '\n', { mode: 0o600 });+ }+ }+ const tmp = `${configPath}.tmp-isolate`;+ writeFileSync(tmp, result.yaml, { mode: 0o600 });+ renameSync(tmp, configPath);+ }+ return {+ ok: true,+ removed: result.removed.map((it) => it.name),+ kept: result.kept,+ unchanged: false,+ };+}diff --git a/claude-ops/scripts/account-rotation/cliproxy-pool-snapshot.mjs b/claude-ops/scripts/account-rotation/cliproxy-pool-snapshot.mjsnew file mode 100644index 00000000..aa24e681--- /dev/null+++ b/claude-ops/scripts/account-rotation/cliproxy-pool-snapshot.mjs@@ -0,0 +1,371 @@+/**+ * Build a redacted CLIProxy pool snapshot from an auth-dir (json + .cds).+ * No emails, tokens, or auth filenames leak into the census view.+ */+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { createHash } from 'node:crypto';+import { detectCertainExhaust, parseTimestamp } from './cliproxy-heal-policy.mjs';++/**+ * Stable, non-reversible seat identifier. `stem(name)` below can produce a+ * raw account email straight from the auth/.cds filename; that raw value+ * must never reach persisted state, AI facts, or --json output. Only the+ * internal `rawId` field (used for auth-file mutation and reauth targeting)+ * keeps the original value.+ */+export function opaqueSeatId(rawId) {+ return createHash('sha256').update(String(rawId)).digest('hex').slice(0, 16);+}++function readJson(path) {+ try {+ return JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return null;+ }+}++function flattenError(value) {+ if (value == null) return '';+ if (typeof value === 'string') return value;+ if (typeof value === 'object') {+ const nested = value.message || value.error || value.reason || '';+ if (typeof nested === 'string') {+ try {+ const parsed = JSON.parse(nested);+ return flattenError(parsed) || nested;+ } catch {+ return nested;+ }+ }+ if (typeof nested === 'object') return flattenError(nested);+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+ }+ return String(value);+}++function extractResetsAt(blob) {+ if (!blob) return null;+ const m = String(blob).match(/"resets_at"\s*:\s*(\d+)/);+ if (m) return parseTimestamp(Number(m[1]));+ const iso = String(blob).match(/"resets_at"\s*:\s*"([^"]+)"/);+ if (iso) return parseTimestamp(iso[1]);+ return null;+}++function validRecover(ts) {+ return parseTimestamp(ts);+}++function recordSignals(record, now) {+ const quota = record?.quota && typeof record.quota === 'object' ? record.quota : {};+ const lastError = flattenError(record?.last_error || record?.reason || record?.status);+ const quotaReason = quota.reason || record?.reason || '';+ const remaining = quota.remaining ?? quota.remaining_percent ?? quota.remainingPercent ?? quota.left ?? null;+ const reschedule =+ validRecover(quota.next_recover_at) ||+ validRecover(record?.next_retry_after) ||+ extractResetsAt(lastError) ||+ extractResetsAt(JSON.stringify(quota));+ const retry = validRecover(record?.next_retry_after);+ const recover = validRecover(quota.next_recover_at);+ // cooling must agree with rescheduleAt above: a seat with only+ // quota.next_recover_at in the future (no next_retry_after) was reporting+ // itself as still cooling and must not be treated as currently servable.+ const cooling = (retry != null && retry > now) || (recover != null && recover > now);+ const exceeded = quota.exceeded === true;+ const certain = detectCertainExhaust({+ lastExhaustReason: quotaReason,+ lastExhaustBody: lastError,+ quotaExceeded: exceeded,+ quotaReason,+ });+ return {+ remainingQuota: remaining == null ? null : Number(remaining),+ quotaExceeded: typeof quota.exceeded === 'boolean' ? quota.exceeded : null,+ quotaReason: quotaReason || null,+ lastExhaustReason: quotaReason || record?.reason || null,+ lastExhaustBody: lastError || null,+ rescheduleAt: reschedule != null ? new Date(reschedule).toISOString() : null,+ cooling,+ certainQuotaExhausted: certain,+ hadQuotaSignal: exceeded || certain || remaining != null,+ };+}++function mergeRecords(records, now) {+ const list = Array.isArray(records) ? records.filter((r) => r && typeof r === 'object') : [];+ if (!list.length) {+ return {+ remainingQuota: null,+ quotaExceeded: null,+ quotaReason: null,+ lastExhaustReason: null,+ lastExhaustBody: null,+ rescheduleAt: null,+ cooling: false,+ certainQuotaExhausted: false,+ hadQuotaSignal: false,+ };+ }+ const signals = list.map((r) => recordSignals(r, now));+ const cooling = signals.some((s) => s.cooling);+ const certain = signals.some((s) => s.certainQuotaExhausted);+ const remaining = signals.map((s) => s.remainingQuota).find((n) => Number.isFinite(n) && n > 0);+ const anyRemaining = signals.map((s) => s.remainingQuota).find((n) => Number.isFinite(n));+ const exceeded = signals.some((s) => s.quotaExceeded === true)+ ? true+ : signals.every((s) => s.quotaExceeded === false)+ ? false+ : (signals.find((s) => typeof s.quotaExceeded === 'boolean')?.quotaExceeded ?? null);+ const withStamp = signals.find((s) => s.rescheduleAt);+ const withBody = signals.find((s) => s.lastExhaustBody);+ return {+ remainingQuota: remaining ?? anyRemaining ?? null,+ quotaExceeded: exceeded,+ quotaReason: withBody?.quotaReason || signals[0].quotaReason,+ lastExhaustReason: withBody?.lastExhaustReason || signals[0].lastExhaustReason,+ lastExhaustBody: withBody?.lastExhaustBody || signals[0].lastExhaustBody,+ rescheduleAt: withStamp?.rescheduleAt || null,+ cooling,+ certainQuotaExhausted: certain,+ hadQuotaSignal: signals.some((s) => s.hadQuotaSignal),+ };+}++function tokenLooksStale(auth, body) {+ const blob = [auth?.disabled_reason, auth?.reconcile_reason, body].filter(Boolean).join(' ');+ return /expired credentials|no auth context|PermissionDenied|invalid_grant/i.test(blob);+}++function providerOf(auth, cds, fileName) {+ const raw = auth?.type || auth?.provider || cds?.provider || cds?.type || fileName.split('-')[0] || 'unknown';+ return String(raw).toLowerCase();+}++function stem(name) {+ return name.replace(/\.(json|cds)$/i, '');+}++/**+ * Compare with the previous tick to mark newly observed quota.+ */+export function markNewQuota(seat, previous) {+ if (!previous) {+ return { ...seat, newQuotaObserved: false, quotaReset: seat.quotaExceeded === false && seat.hadQuotaSignal };+ }+ const remNow = Number(seat.remainingQuota);+ const remPrev = Number(previous.remainingQuota);+ const remainingGrew = Number.isFinite(remNow) && Number.isFinite(remPrev) && remNow > remPrev;+ const remainingAppeared = Number.isFinite(remNow) && remNow > 0 && !(Number.isFinite(remPrev) && remPrev > 0);+ const exceededCleared = previous.quotaExceeded === true && seat.quotaExceeded === false;+ return {+ ...seat,+ newQuotaObserved: remainingGrew || remainingAppeared || exceededCleared,+ quotaReset: exceededCleared || remainingAppeared,+ };+}++function indexKeys(value) {+ const raw = String(value || '')+ .trim()+ .toLowerCase();+ if (!raw) return [];+ const keys = new Set([raw, raw.replace(/@/g, '_')]);+ return [...keys];+}++function addIndex(map, key, path) {+ for (const k of indexKeys(key)) {+ if (!map.has(k)) map.set(k, path);+ }+}++function buildCdsIndex(authDir, files) {+ const byKey = new Map();+ const all = [];+ for (const name of files) {+ if (!name.endsWith('.cds')) continue;+ const path = join(authDir, name);+ const cds = readJson(path);+ all.push({ path, name, cds });+ addIndex(byKey, name.replace(/\.cds$/i, ''), path);+ if (cds && typeof cds === 'object') {+ addIndex(byKey, cds.auth_id, path);+ addIndex(byKey, cds.email, path);+ for (const rec of cds.records || []) {+ if (rec && typeof rec === 'object') {+ addIndex(byKey, rec.auth_id, path);+ addIndex(byKey, rec.email, path);+ }+ }+ }+ }+ return { byKey, all };+}++function lookupCds(byKey, auth, jsonName) {+ const email = auth?.email || '';+ const id = stem(jsonName);+ for (const candidate of [id, jsonName, email, id.replace(/@/g, '_')]) {+ for (const k of indexKeys(candidate)) {+ if (byKey.has(k)) return byKey.get(k);+ }+ }+ return null;+}++function seatFromParts({ id, provider, auth, authFile, cds, cdsFile, now, previous }) {+ const merged = mergeRecords(cds?.records, now);+ const disabled = auth?.disabled === true;+ const inRotation = !disabled && !merged.cooling;+ const opaque = opaqueSeatId(id);+ return markNewQuota(+ {+ id: opaque,+ rawId: id,+ provider,+ disabled,+ cooling: merged.cooling,+ inRotation,+ remainingQuota: Number.isFinite(merged.remainingQuota) ? merged.remainingQuota : null,+ quotaExceeded: merged.quotaExceeded,+ quotaReason: merged.quotaReason,+ lastExhaustReason: merged.lastExhaustReason,+ lastExhaustBody: merged.lastExhaustBody,+ rescheduleAt: merged.rescheduleAt,+ certainQuotaExhausted: merged.certainQuotaExhausted,+ hadQuotaSignal: merged.hadQuotaSignal,+ tokenStale: tokenLooksStale(auth || {}, merged.lastExhaustBody),+ paidSeat: auth?.paidSeat !== false,+ authFile: authFile || null,+ cdsFile: cdsFile || null,+ },+ previous[opaque],+ );+}++export function snapshotFromAuthDir(authDir, { now = Date.now(), previous = {} } = {}) {+ if (!authDir || !existsSync(authDir)) return { seats: [], census: emptyCensus(now) };+ const files = readdirSync(authDir);+ const jsonFiles = files.filter((n) => n.endsWith('.json') && !n.includes('.bak') && !n.endsWith('.tmp'));+ const cdsIndex = buildCdsIndex(authDir, files);+ const usedCds = new Set();+ const seats = [];++ for (const name of jsonFiles) {+ const authFile = join(authDir, name);+ const auth = readJson(authFile);+ if (!auth || typeof auth !== 'object') continue;+ const id = stem(name);+ const cdsFile = lookupCds(cdsIndex.byKey, auth, name);+ const cds = cdsFile ? readJson(cdsFile) : null;+ if (cdsFile) usedCds.add(cdsFile);+ seats.push(+ seatFromParts({+ id,+ provider: providerOf(auth, cds, name),+ auth,+ authFile,+ cds,+ cdsFile,+ now,+ previous,+ }),+ );+ }++ for (const entry of cdsIndex.all) {+ if (usedCds.has(entry.path)) continue;+ const cds = entry.cds && typeof entry.cds === 'object' ? entry.cds : {};+ const id = stem(entry.name);+ seats.push(+ seatFromParts({+ id,+ provider: providerOf(null, cds, entry.name),+ auth: { disabled: false },+ authFile: null,+ cds,+ cdsFile: entry.path,+ now,+ previous,+ }),+ );+ }++ return { seats, census: censusFromSeats(seats, now) };+}++function emptyCensus(now) {+ return {+ generatedAt: new Date(now).toISOString(),+ providers: {},+ totals: { seats: 0, enabled: 0, disabled: 0, cooling: 0, remainingQuota: 0, certainExhaust: 0 },+ };+}++export function censusFromSeats(seats, now = Date.now()) {+ const providers = {};+ const totals = { seats: 0, enabled: 0, disabled: 0, cooling: 0, remainingQuota: 0, certainExhaust: 0 };+ for (const seat of seats) {+ const p = seat.provider || 'unknown';+ if (!providers[p]) {+ providers[p] = {+ seats: 0,+ enabled: 0,+ disabled: 0,+ cooling: 0,+ remainingQuota: 0,+ certainExhaust: 0,+ nextRescheduleAt: null,+ };+ }+ const row = providers[p];+ row.seats += 1;+ totals.seats += 1;+ if (seat.disabled) {+ row.disabled += 1;+ totals.disabled += 1;+ } else {+ row.enabled += 1;+ totals.enabled += 1;+ }+ if (seat.cooling) {+ row.cooling += 1;+ totals.cooling += 1;+ }+ if (Number.isFinite(Number(seat.remainingQuota)) && Number(seat.remainingQuota) > 0) {+ row.remainingQuota += 1;+ totals.remainingQuota += 1;+ }+ if (seat.certainQuotaExhausted) {+ row.certainExhaust += 1;+ totals.certainExhaust += 1;+ }+ if (seat.rescheduleAt && (!row.nextRescheduleAt || seat.rescheduleAt < row.nextRescheduleAt)) {+ row.nextRescheduleAt = seat.rescheduleAt;+ }+ }+ return { generatedAt: new Date(now).toISOString(), providers, totals };+}++export function redactSeat(seat) {+ return {+ id: seat.id,+ provider: seat.provider,+ disabled: seat.disabled === true,+ cooling: seat.cooling === true,+ inRotation: seat.inRotation === true,+ remainingQuota: seat.remainingQuota ?? null,+ quotaExceeded: seat.quotaExceeded ?? null,+ certainQuotaExhausted: seat.certainQuotaExhausted === true,+ rescheduleAt: seat.rescheduleAt ?? null,+ tokenStale: seat.tokenStale === true,+ newQuotaObserved: seat.newQuotaObserved === true,+ };+}diff --git a/claude-ops/scripts/cliproxy-hub/cliproxy-reauth-one.sh b/claude-ops/scripts/cliproxy-hub/cliproxy-reauth-one.shnew file mode 100755index 00000000..8c3a5ea3--- /dev/null+++ b/claude-ops/scripts/cliproxy-hub/cliproxy-reauth-one.sh@@ -0,0 +1,93 @@+#!/bin/bash+# Per-seat reauth writer for cliproxy-heal-tick.+# Args: <provider> <seat-id> [auth-file]+# Exit 0 success, 2 checkpoint/human-only, 3 no writer / unusable seat.+# Never prints tokens, cookies, or raw emails.+set -euo pipefail+PROVIDER="${1:-}"+SEAT="${2:-}"+AUTH_FILE="${3:-}"+AUTH_DIR="${CLIPROXY_AUTH_DIR:-/opt/crsproxy/auths}"+ROOT="${CLIPROXY_ROOT:-/opt/crsproxy}"+if [ -x "${CLIPROXY_PYTHON:-}" ]; then+ PY="$CLIPROXY_PYTHON"+elif [ -x "$ROOT/venv/bin/python" ]; then+ PY="$ROOT/venv/bin/python"+else+ PY="$(command -v python3 || true)"+fi++if [ -z "$PROVIDER" ] || [ -z "$SEAT" ]; then+ echo "cliproxy-reauth-one: missing provider or seat" >&2+ exit 3+fi+if [ -z "$PY" ]; then+ echo "cliproxy-reauth-one: no python writer runtime" >&2+ exit 3+fi++if [ -z "$AUTH_FILE" ] || [ ! -f "$AUTH_FILE" ]; then+ if [ -f "$AUTH_DIR/$SEAT.json" ]; then+ AUTH_FILE="$AUTH_DIR/$SEAT.json"+ else+ AUTH_FILE=""+ fi+fi+if [ -z "$AUTH_FILE" ] || [ ! -f "$AUTH_FILE" ]; then+ echo "cliproxy-reauth-one: auth file not found" >&2+ exit 3+fi++# Resolve email + optional profile id without printing them.+eval "$("$PY" - "$AUTH_FILE" "$PROVIDER" "$ROOT/reauth_seats.json" <<'PY'+import json, os, sys+auth_path, provider, seats_path = sys.argv[1], sys.argv[2], sys.argv[3]+try:+ data = json.load(open(auth_path))+except Exception:+ print("echo cliproxy-reauth-one: unreadable auth >&2; exit 3")+ raise SystemExit(0)+email = data.get("email") or ""+if not email or "@" not in str(email):+ print("echo cliproxy-reauth-one: no email in auth >&2; exit 3")+ raise SystemExit(0)+profile = ""+if os.path.isfile(seats_path):+ try:+ raw = json.load(open(seats_path))+ seats = raw.get("seats") if isinstance(raw, dict) else raw+ for s in seats or []:+ if not isinstance(s, dict):+ continue+ if str(s.get("provider") or "").lower() != provider.lower():+ continue+ if str(s.get("email") or "").lower() != str(email).lower():+ continue+ profile = str(s.get("profile_id") or s.get("profileId") or "")+ break+ except Exception:+ profile = ""+# Export via env-safe quoted assignment without echoing.+def q(v):+ return "'" + str(v).replace("'", "'\"'\"'") + "'"+print("EMAIL=" + q(email))+print("PROFILE=" + q(profile))+PY+)"++if [ -z "${EMAIL:-}" ]; then+ echo "cliproxy-reauth-one: could not resolve seat identity" >&2+ exit 3+fi++if [ -n "${PROFILE:-}" ] && [ -f "$ROOT/bu_profile_reauth.py" ]; then+ exec "$PY" "$ROOT/bu_profile_reauth.py" -provider "$PROVIDER" -email "$EMAIL" -profile-id "$PROFILE"+fi+if [ "$PROVIDER" = "xai" ] && [ -f "$ROOT/xai_device_reauth.py" ]; then+ exec "$PY" "$ROOT/xai_device_reauth.py" -email "$EMAIL"+fi+if [ -f "$ROOT/bu_reauth_lib.py" ]; then+ exec "$PY" "$ROOT/bu_reauth_lib.py" -provider "$PROVIDER" -email "$EMAIL"+fi+echo "cliproxy-reauth-one: no writer for provider" >&2+exit 3diff --git a/claude-ops/scripts/cliproxy-hub/install-heal.sh b/claude-ops/scripts/cliproxy-hub/install-heal.shnew file mode 100755index 00000000..010316c7--- /dev/null+++ b/claude-ops/scripts/cliproxy-hub/install-heal.sh@@ -0,0 +1,100 @@+#!/usr/bin/env bash+# Install the CLIProxy healer onto a hub that already runs crsproxy.+# Copies policy/tick modules to /opt/crsproxy/heal and enables the systemd timer.+# Run on the hub as root. No secrets are written.+set -euo pipefail++SRC="$(cd "$(dirname "$0")/../account-rotation" && pwd)"+DEST="${CLIPROXY_HEAL_DEST:-/opt/crsproxy/heal}"+UNIT_DIR="${CLIPROXY_UNIT_DIR:-/etc/systemd/system}"+TEMPLATE_DIR="$(cd "$(dirname "$0")/../../templates" && pwd)"++# DEST is interpolated into a sed replacement (below) and, via the generated+# unit, into systemd directives (ExecStart=, Environment=CLIPROXY_REAUTH_CMD=).+# Rather than try to replicate systemd's own escaping rules for that context+# (% is systemd's specifier-expansion escape and must be doubled; backslash+# and quotes carry meaning inside unit file quoting) constrain DEST to a+# strict allow-list of characters that are inert in both a sed replacement+# and a systemd directive: it must be an absolute path built only from+# alphanumerics, underscore, dot, slash, and dash. Anything else — spaces,+# %, \, ", ', &, #, $, ; — is rejected outright.+if [[ ! "$DEST" =~ ^/[A-Za-z0-9_./-]+$ ]]; then+ echo "install-heal.sh: CLIPROXY_HEAL_DEST must be an absolute path using only [A-Za-z0-9_./-] (got: $DEST)" >&2+ exit 1+fi++# cliproxy-heal-ai.mjs uses AbortSignal.timeout(), added in Node 17.3 / 18.0.+# A pre-18 node on the hub would silently throw on the first advisor call+# instead of failing this install step, so enforce the floor here. Resolve+# the exact executable path (not just "node" by name) and reuse that same+# path in the generated unit's ExecStart, so validation and execution can+# never resolve two different Node.js binaries (e.g. a PATH that differs+# between an interactive install shell and systemd's ExecStart environment).+if command -v node >/dev/null 2>&1; then+ NODE_BIN="$(command -v node)"+ NODE_MAJOR="$("$NODE_BIN" -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')"+ if [ "${NODE_MAJOR:-0}" -lt 18 ]; then+ echo "install-heal.sh: node >=18 required (found $("$NODE_BIN" -v)); AbortSignal.timeout is used by cliproxy-heal-ai.mjs" >&2+ exit 1+ fi+else+ echo "install-heal.sh: node not found on PATH" >&2+ exit 1+fi++mkdir -p "$DEST"+install -m 0755 "$SRC/cliproxy-heal-tick.mjs" "$DEST/cliproxy-heal-tick.mjs"+install -m 0644 "$SRC/cliproxy-heal-policy.mjs" "$DEST/cliproxy-heal-policy.mjs"+install -m 0644 "$SRC/cliproxy-heal-ai.mjs" "$DEST/cliproxy-heal-ai.mjs"+install -m 0644 "$SRC/cliproxy-pool-snapshot.mjs" "$DEST/cliproxy-pool-snapshot.mjs"+install -m 0644 "$SRC/auto-auth-policy.mjs" "$DEST/auto-auth-policy.mjs"+install -m 0644 "$SRC/cliproxy-isolate-compat.mjs" "$DEST/cliproxy-isolate-compat.mjs"+HUB_SCRIPTS="$(cd "$(dirname "$0")" && pwd)"+install -m 0755 "$HUB_SCRIPTS/cliproxy-reauth-one.sh" "$DEST/cliproxy-reauth-one.sh"+mkdir -p /opt/crsproxy/isolated+if [ ! -f /opt/crsproxy/isolated/manifest.json ]; then+ printf '%s\n' '{"providers":["opencode-go"],"reasons":{"opencode-go":"upstream CreditsError/RegionError: no payment method / China-host opt-in"}}' >/opt/crsproxy/isolated/manifest.json+ chmod 0644 /opt/crsproxy/isolated/manifest.json+fi++# Second unattended-healing gate: a filesystem marker, not another env var.+# automatedAuthAllowed() (auto-auth-policy.mjs) requires both+# CLIPROXY_HUB_HEAL=1 (a process env var, settable by editing the unit's+# Environment= lines or exporting it in a shell) AND this marker file's+# CONTENT matching CLIPROXY_HEAL_OPTIN_TOKEN (settable only by running this+# install script against /opt/crsproxy). Content, not mere existence, is+# required so that pointing at some other pre-existing file cannot forge the+# gate. The token literal below must stay in sync with+# CLIPROXY_HEAL_OPTIN_TOKEN in account-rotation/auto-auth-policy.mjs.+# Running this script is the deliberate "provision this host for unattended+# healing" step; writing the marker here — not via Environment= in the unit+# template — keeps that decision on a different control plane than the+# env var, so editing the unit alone cannot satisfy both gates.+printf '%s\n' "cliproxy-heal-optin-v1" >/opt/crsproxy/.heal-account-optin+chmod 0600 /opt/crsproxy/.heal-account-optin++# Escape DEST and NODE_BIN for use as sed replacement text: sed treats `&` as+# "the whole match" and `\` as an escape in the replacement, and `#` is the+# delimiter this script uses for the s### command, so any of those three+# characters in an unescaped path would corrupt the generated unit (or the+# sed command itself) instead of producing the requested path.+sed_escape_repl() { printf '%s' "$1" | sed -e 's/[\&#]/\\&/g'; }+DEST_ESCAPED="$(sed_escape_repl "$DEST")"+NODE_BIN_ESCAPED="$(sed_escape_repl "$NODE_BIN")"++# The template hardcodes /opt/crsproxy/heal (ExecStart, CLIPROXY_REAUTH_CMD)+# and /usr/local/bin/node (ExecStart). When CLIPROXY_HEAL_DEST overrides the+# install dir, or the validated node binary lives elsewhere, the generated+# unit must point at those same paths, not silently keep referencing the+# template's defaults.+sed -e "s#/opt/crsproxy/heal#${DEST_ESCAPED}#g" -e "s#/usr/local/bin/node#${NODE_BIN_ESCAPED}#g" \+ "$TEMPLATE_DIR/cliproxy-heal.service" >"$UNIT_DIR/cliproxy-heal.service"+chmod 0644 "$UNIT_DIR/cliproxy-heal.service"+install -m 0644 "$TEMPLATE_DIR/cliproxy-heal.timer" "$UNIT_DIR/cliproxy-heal.timer"++if command -v systemctl >/dev/null 2>&1; then+ systemctl daemon-reload+ systemctl enable --now cliproxy-heal.timer+fi++echo "installed $DEST and cliproxy-heal.timer"diff --git a/claude-ops/templates/cliproxy-heal.service b/claude-ops/templates/cliproxy-heal.servicenew file mode 100644index 00000000..41607962--- /dev/null+++ b/claude-ops/templates/cliproxy-heal.service@@ -0,0 +1,29 @@+[Unit]+Description=CLIProxy autonomous quota healer (hard rules + AI advisor)+After=crsproxy.service+Wants=crsproxy.service++[Service]+Type=oneshot+User=crsproxy+Group=crsproxy+WorkingDirectory=/opt/crsproxy+Environment=HOME=/opt/crsproxy+# CLIPROXY_HUB_HEAL is the first of two required unattended-healing gates.+# The second gate is the presence of /opt/crsproxy/.heal-account-optin, a+# marker file written only by install-heal.sh — not by this unit's+# Environment= lines — so editing this file alone cannot satisfy both gates.+Environment=CLIPROXY_HUB_HEAL=1+Environment=CLIPROXY_AUTH_DIR=/opt/crsproxy/auths+Environment=CLIPROXY_HEAL_STATE=/opt/crsproxy/.cliproxy-heal-state.json+Environment=CLIPROXY_HEAL_BASE_URL=http://127.0.0.1:8317+Environment=CLIPROXY_CONFIG=/opt/crsproxy/config.yaml+Environment=CLIPROXY_REAUTH_CMD=/opt/crsproxy/heal/cliproxy-reauth-one.sh+Environment=CLIPROXY_ROOT=/opt/crsproxy+Environment=PYTHONUNBUFFERED=1+ExecStart=/usr/local/bin/node /opt/crsproxy/heal/cliproxy-heal-tick.mjs+TimeoutStartSec=180+Nice=10++[Install]+WantedBy=multi-user.targetdiff --git a/claude-ops/templates/cliproxy-heal.timer b/claude-ops/templates/cliproxy-heal.timernew file mode 100644index 00000000..f3d9c618--- /dev/null+++ b/claude-ops/templates/cliproxy-heal.timer@@ -0,0 +1,12 @@+[Unit]+Description=Run CLIProxy autonomous quota healer every 2 minutes++[Timer]+OnBootSec=45s+OnUnitActiveSec=120s+AccuracySec=15s+Persistent=true+Unit=cliproxy-heal.service++[Install]+WantedBy=timers.targetdiff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex 8d95221f..3166be39 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -42,6 +42,7 @@ run_suite "$TESTS_DIR/test-run-pressure-monitor-if-needed.sh"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-cliproxy-heal.sh"run_suite "$TESTS_DIR/test-model-args.sh"run_suite "$TESTS_DIR/test-account-recovery.sh"run_suite "$TESTS_DIR/test-claude-invoke.sh"diff --git a/claude-ops/tests/test-cliproxy-heal.sh b/claude-ops/tests/test-cliproxy-heal.shnew file mode 100755index 00000000..b21d82a2--- /dev/null+++ b/claude-ops/tests/test-cliproxy-heal.sh@@ -0,0 +1,5 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+node "$ROOT/scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjs"+node "$ROOT/scripts/account-rotation/__tests__/cliproxy-isolate-compat.test.mjs"diff --git a/claude-ops/tests/test-rotate-cliproxy-integration.sh b/claude-ops/tests/test-rotate-cliproxy-integration.shindex cc5f9911..67601e30 100755--- a/claude-ops/tests/test-rotate-cliproxy-integration.sh+++ b/claude-ops/tests/test-rotate-cliproxy-integration.sh@@ -72,3 +72,6 @@ for (const authArg of ['--setup', '--magic-link']) {console.log('CLIProxy direct-writer policy tests: PASS');NODE++node "$ROOT/scripts/account-rotation/__tests__/cliproxy-heal-policy.test.mjs"+node "$ROOT/scripts/account-rotation/__tests__/cliproxy-isolate-compat.test.mjs"