Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(account-rotation): Linux port — file-based vault + headless Chromium + systemd service (#350)

Aurora Capitalbd9308f8c077
diff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjs
index 688ba056..cb21018f 100644
--- a/claude-ops/scripts/account-rotation/daemon.mjs
+++ b/claude-ops/scripts/account-rotation/daemon.mjs
@@ -30,7 +30,12 @@ const LOG_PATH = join(__dirname, 'rotation.log');
const PID_FILE = join(__dirname, '.daemon.pid');
const ROTATE_SCRIPT = join(__dirname, 'rotate.mjs');
-// Keychain account name — must match rotate.mjs convention.
+// ── Platform ─────────────────────────────────────────────────────────────────
+const IS_LINUX = process.platform === 'linux';
+// Top-level await: pre-load vault on Linux so credential helpers stay synchronous.
+const _vault = IS_LINUX ? await import('./vault-linux.mjs') : null;
+
+// Keychain account name — must match rotate.mjs convention (macOS only).
const KEYCHAIN_ACCOUNT =
process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';
@@ -60,15 +65,18 @@ function log(msg) {
function notify(title, msg) {
try {
- // Use execFileSync to avoid shell interpretation of quotes in title/msg
- execFileSync(
- 'osascript',
- [
- '-e',
- `display notification "${msg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" with title "${title.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`,
- ],
- { timeout: 5000 },
- );
+ if (IS_LINUX) {
+ spawnSync('notify-send', [title, msg], { timeout: 3000 });
+ } else {
+ execFileSync(
+ 'osascript',
+ [
+ '-e',
+ `display notification "${msg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" with title "${title.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`,
+ ],
+ { timeout: 5000 },
+ );
+ }
} catch {}
}
@@ -134,6 +142,9 @@ function tokenExpired(json) {
function readStoredToken(account) {
const svc = `Claude-Rotation-${accountKey(account)}`;
+ if (IS_LINUX) {
+ try { return _vault.readEntry(svc); } catch { return null; }
+ }
try {
const result = spawnSync('security', ['find-generic-password', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-g'], {
timeout: 5000,
@@ -148,6 +159,9 @@ function readStoredToken(account) {
}
function readActiveKeychainToken() {
+ if (IS_LINUX) {
+ try { return _vault.readEntry('Claude Code-credentials'); } catch { return null; }
+ }
try {
const r = spawnSync(
'security',
@@ -321,20 +335,24 @@ async function shouldRotate(config, state) {
log('[active-refresh] Active token expiring — attempting in-place refresh');
const refreshed = await refreshSingleToken(account);
if (refreshed) {
- // Also update the active keychain so running sessions pick it up on next /login
+ // Also update the active credential store so running sessions pick it up on next /login
try {
const freshToken = readStoredToken(account);
if (freshToken) {
const svc = 'Claude Code-credentials';
- execFileSync(
- 'security',
- ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', freshToken],
- { timeout: 5000 },
- );
- log('[active-refresh] Active keychain updated — sessions will auto-recover');
+ if (IS_LINUX) {
+ _vault.writeEntry(svc, freshToken);
+ } else {
+ execFileSync(
+ 'security',
+ ['add-generic-password', '-U', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', freshToken],
+ { timeout: 5000 },
+ );
+ }
+ log('[active-refresh] Active credentials updated — sessions will auto-recover');
}
} catch (err) {
- log(`[active-refresh] Keychain update failed: ${err.message?.substring(0, 60)}`);
+ log(`[active-refresh] Credential update failed: ${err.message?.substring(0, 60)}`);
}
return { should: false }; // Refreshed in-place, no rotation needed
}
diff --git a/claude-ops/scripts/account-rotation/keychain-swap.mjs b/claude-ops/scripts/account-rotation/keychain-swap.mjs
index 2732461b..193ed89d 100644
--- a/claude-ops/scripts/account-rotation/keychain-swap.mjs
+++ b/claude-ops/scripts/account-rotation/keychain-swap.mjs
@@ -4,6 +4,10 @@
* Reuses the same `security` CLI approach as rotate.mjs but is self-contained
* so importing it has no side effects (rotate.mjs has top-level CLI execution).
*
+ * Platform:
+ * macOS — macOS security(1) Keychain
+ * Linux — file-based vault via vault-linux.mjs
+ *
* Exports:
* - readCurrentToken() → raw JSON string of active Claude credentials
* - writeCurrentToken(json) → overwrite active Claude credentials
@@ -15,6 +19,10 @@
import { execFileSync, spawnSync } from 'child_process';
+const IS_LINUX = process.platform === 'linux';
+// Top-level await: pre-load vault on Linux so all exports stay synchronous.
+const _vault = IS_LINUX ? await import('./vault-linux.mjs') : null;
+
const KEYCHAIN_SERVICE = 'Claude Code-credentials';
const KEYCHAIN_ACCOUNT =
process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';
@@ -28,8 +36,13 @@ function tokenService(email, label) {
return `${TOKEN_PREFIX}-${accountKey(email, label)}`;
}
-function readSecurityEntry(svc, acct = KEYCHAIN_ACCOUNT) {
- const result = spawnSync('security', ['find-generic-password', '-s', svc, '-a', acct, '-g'], {
+// ── Low-level read/write — platform-aware ────────────────────────────────────
+
+function readEntry(svc) {
+ if (IS_LINUX) {
+ return _vault.readEntry(svc);
+ }
+ const result = spawnSync('security', ['find-generic-password', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-g'], {
timeout: 5000,
encoding: 'utf8',
});
@@ -39,31 +52,39 @@ function readSecurityEntry(svc, acct = KEYCHAIN_ACCOUNT) {
return m[1].replace(/\\"/g, '"');
}
-function writeSecurityEntry(json, svc, acct = KEYCHAIN_ACCOUNT) {
+function writeEntry(svc, json) {
+ if (IS_LINUX) {
+ _vault.writeEntry(svc, json);
+ return;
+ }
try {
- execFileSync('security', ['delete-generic-password', '-s', svc, '-a', acct], { stdio: 'ignore' });
+ execFileSync('security', ['delete-generic-password', '-s', svc, '-a', KEYCHAIN_ACCOUNT], { stdio: 'ignore' });
} catch {
/* not present, ignore */
}
- execFileSync('security', ['add-generic-password', '-s', svc, '-a', acct, '-w', json], { timeout: 5000 });
+ execFileSync('security', ['add-generic-password', '-s', svc, '-a', KEYCHAIN_ACCOUNT, '-w', json], {
+ timeout: 5000,
+ });
}
+// ── Public exports ───────────────────────────────────────────────────────────
+
export function readCurrentToken() {
- const json = readSecurityEntry(KEYCHAIN_SERVICE);
- if (!json) throw new Error(`No active Claude keychain entry (${KEYCHAIN_SERVICE})`);
+ const json = readEntry(KEYCHAIN_SERVICE);
+ if (!json) throw new Error(`No active Claude credential entry (${KEYCHAIN_SERVICE})`);
return json;
}
export function writeCurrentToken(json) {
- writeSecurityEntry(json, KEYCHAIN_SERVICE);
+ writeEntry(KEYCHAIN_SERVICE, json);
}
export function readStoredToken(email, label) {
- return readSecurityEntry(tokenService(email, label));
+ return readEntry(tokenService(email, label));
}
/**
- * Swap the active keychain to the given email's stored token.
+ * Swap the active token to the given email's stored token.
* Returns the previous (now-replaced) token JSON so the caller can restore it.
* Throws if the target email has no stored token or it's malformed.
*/
diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjs
index 25f3e1bf..2e7ff8c8 100644
--- a/claude-ops/scripts/account-rotation/rotate.mjs
+++ b/claude-ops/scripts/account-rotation/rotate.mjs
@@ -44,6 +44,12 @@ import { tmpdir } from 'os';
import { createHmac } from 'node:crypto';
import { askAIBrain, executeAIAction, AI_BRAIN_MAX_DECISIONS } from './ai-brain.mjs';
+// ── Platform: Linux uses file-based vault; macOS uses security(1) keychain ───
+const IS_LINUX = process.platform === 'linux';
+// Top-level await: pre-load vault synchronously at module init so all
+// readKeychain/writeKeychain calls below can use it without being async.
+let _linuxVault = IS_LINUX ? await import('./vault-linux.mjs') : null;
+
const __dirname = dirname(fileURLToPath(import.meta.url));
const CONFIG_PATH = join(__dirname, 'config.json');
const STATE_PATH = join(__dirname, 'state.json');
@@ -59,8 +65,12 @@ const KEYCHAIN_ACCOUNT =
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ── Bootstrap: verify dependencies ───────────────────────────────────────────
-// The only browser driver is Playwright-over-CDP to Chrome or Chrome Beta
-// (never Comet — reserved for user, never Chromium — bundled browser banned).
+// macOS: Playwright-over-CDP to Chrome or Chrome Beta (never Comet/bundled Chromium).
+// Linux: Playwright headless Chromium (no real Chrome required).
+function _hasCmd(bin) {
+ return spawnSync('which', [bin], { timeout: 2000 }).status === 0;
+}
+
function ensureMCPServersAndTools() {
const actions = [];
const earlyLog = (m) => {
@@ -69,41 +79,46 @@ function ensureMCPServersAndTools() {
} catch {}
};
- // 1. Chrome or Chrome Beta binary (Comet is off-limits)
- const realChromes = [
- '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta',
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- ];
- const foundChrome = realChromes.find((p) => existsSync(p));
- if (foundChrome) {
- actions.push(`chrome-binary: ${foundChrome.split('/').pop()}`);
+ if (IS_LINUX) {
+ // Linux: headless Chromium via Playwright — no real Chrome binary needed
+ actions.push('platform: linux — headless Chromium mode');
+ if (_hasCmd('npx')) {
+ actions.push('playwright: available via npx');
+ } else {
+ actions.push('playwright: WARNING — npx not found; browser fallback may fail');
+ }
} else {
- actions.push('chrome-binary: WARNING — no Chrome/Chrome Beta found');
- }
+ // macOS: require real Chrome/Chrome Beta binary + CDP
+ const realChromes = [
+ '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta',
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ ];
+ const foundChrome = realChromes.find((p) => existsSync(p));
+ if (foundChrome) {
+ actions.push(`chrome-binary: ${foundChrome.split('/').pop()}`);
+ } else {
+ actions.push('chrome-binary: WARNING — no Chrome/Chrome Beta found');
+ }
- // 2. Chrome CDP port 9222 — probe (driver will launch Chrome if needed)
- try {
- execSync(`curl -sf http://localhost:9222/json/version >/dev/null 2>&1`, {
- timeout: 1500,
- });
- actions.push('chrome-cdp: reachable on :9222');
- } catch {
- actions.push('chrome-cdp: not reachable (driver will launch Chrome)');
- }
+ // Chrome CDP port 9222 — probe (driver will launch Chrome if needed)
+ const cdpProbe = spawnSync('curl', ['-sf', 'http://localhost:9222/json/version'], { timeout: 1500 });
+ if (cdpProbe.status === 0) {
+ actions.push('chrome-cdp: reachable on :9222');
+ } else {
+ actions.push('chrome-cdp: not reachable (driver will launch Chrome)');
+ }
- // 3. dcli (Dashlane) — required for primary token path
- try {
- execSync(`command -v dcli >/dev/null 2>&1`, { timeout: 1000 });
- actions.push('dcli: available');
- } catch {
- actions.push('dcli: MISSING — primary token path will fail');
+ // security(1) keychain — required for token writes on macOS
+ if (!_hasCmd('security')) {
+ actions.push('security(1): MISSING — keychain writes will fail');
+ }
}
- // 4. security (macOS keychain) — required for token writes
- try {
- execSync(`command -v security >/dev/null 2>&1`, { timeout: 1000 });
- } catch {
- actions.push('security(1): MISSING — keychain writes will fail');
+ // dcli (Dashlane) — primary token path on both platforms
+ if (_hasCmd('dcli')) {
+ actions.push('dcli: available');
+ } else {
+ actions.push('dcli: MISSING — primary token path will fall back to browser');
}
for (const a of actions) earlyLog(a);
@@ -127,15 +142,20 @@ function log(msg) {
function notify(title, msg) {
try {
- // Use execFileSync to avoid shell interpretation of quotes in title/msg
- execFileSync(
- 'osascript',
- [
- '-e',
- `display notification "${msg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" with title "${title.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`,
- ],
- { timeout: 5000 },
- );
+ if (IS_LINUX) {
+ // notify-send (libnotify) — no-op if display is unavailable (e.g. headless server)
+ spawnSync('notify-send', [title, msg], { timeout: 3000 });
+ } else {
+ // Use execFileSync to avoid shell interpretation of quotes in title/msg
+ execFileSync(
+ 'osascript',
+ [
+ '-e',
+ `display notification "${msg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" with title "${title.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`,
+ ],
+ { timeout: 5000 },
+ );
+ }
} catch {}
}
@@ -427,9 +447,17 @@ function pickNextAccount(config, state, liveUtil = {}, opts = {}) {
return null;
}
-// ── Keychain ─────────────────────────────────────────────────────────────────
+// ── Keychain / vault ──────────────────────────────────────────────────────────
+// macOS: security(1) Keychain. Linux: file-based vault (vault-linux.mjs).
function readKeychain(svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {
+ if (IS_LINUX) {
+ const vault = _linuxVault;
+ if (!vault) throw new Error('vault-linux not loaded yet');
+ const json = vault.readEntry(svc);
+ if (!json) throw new Error(`No vault entry for ${svc}`);
+ return json;
+ }
const result = spawnSync('security', ['find-generic-password', '-s', svc, '-a', acct, '-g'], {
timeout: 5000,
encoding: 'utf8',
@@ -441,6 +469,12 @@ function readKeychain(svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {
}
function writeKeychain(json, svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {
+ if (IS_LINUX) {
+ const vault = _linuxVault;
+ if (!vault) throw new Error('vault-linux not loaded yet');
+ vault.writeEntry(svc, json);
+ return;
+ }
try {
execFileSync('security', ['delete-generic-password', '-s', svc, '-a', acct], {
stdio: 'ignore',
@@ -1083,12 +1117,20 @@ function isAppRunning(appName) {
}
function gracefullyQuitApp(appName) {
+ if (IS_LINUX) {
+ // No AppleScript on Linux — send SIGTERM and wait
+ spawnSync('pkill', ['-f', appName], { timeout: 3000 });
+ for (let i = 0; i < 10; i++) {
+ if (!isAppRunning(appName)) return true;
+ spawnSync('sleep', ['0.5']);
+ }
+ return false;
+ }
try {
- execSync(`osascript -e 'tell application "${appName}" to quit' 2>/dev/null`, { timeout: 8000 });
- // Wait up to 5s for it to actually quit
+ execFileSync('osascript', ['-e', `tell application "${appName}" to quit`], { timeout: 8000 });
for (let i = 0; i < 10; i++) {
if (!isAppRunning(appName)) return true;
- execSync('sleep 0.5');
+ spawnSync('sleep', ['0.5']);
}
} catch {}
return false;
@@ -1097,6 +1139,34 @@ function gracefullyQuitApp(appName) {
async function makePlaywrightDriver() {
const { chromium } = await import('playwright');
+ // ── Linux: headless Chromium (no real Chrome on servers) ─────────────────
+ if (IS_LINUX) {
+ log('[playwright] Linux mode — launching headless Chromium');
+ const profileDir = join(__dirname, '.chromium-linux-profile');
+ const browser = await chromium.launchPersistentContext(profileDir, {
+ headless: true,
+ args: [
+ '--no-sandbox',
+ '--disable-setuid-sandbox',
+ '--disable-dev-shm-usage',
+ '--disable-blink-features=AutomationControlled',
+ '--disable-background-networking',
+ '--disable-component-update',
+ '--disable-default-apps',
+ '--disable-sync',
+ '--disable-notifications',
+ ],
+ });
+ const page = browser.pages()[0] || (await browser.newPage());
+ return buildPageDriver(
+ 'playwright-linux',
+ page,
+ async () => { try { await browser.close(); } catch {} },
+ browser,
+ );
+ }
+
+ // ── macOS: attach to real Chrome via CDP ──────────────────────────────────
// 1. Try attaching to already-running Chrome on CDP
let attached = await tryConnectCDP(chromium);
let weSpawnedChrome = false;
diff --git a/claude-ops/scripts/account-rotation/vault-linux.mjs b/claude-ops/scripts/account-rotation/vault-linux.mjs
new file mode 100644
index 00000000..f6916efd
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/vault-linux.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+/**
+ * vault-linux.mjs — Linux file-based credential vault
+ *
+ * Drop-in replacement for the macOS `security` keychain CLI.
+ * No native dependencies — uses the filesystem only.
+ *
+ * Active credentials: ~/.claude/.credentials.json (Claude Code's own file)
+ * Per-account vault: ~/.local/share/claude-rotation/<sha256(service)[0:16]>.json (chmod 600)
+ *
+ * Exports (same interface consumed by rotate.mjs + daemon.mjs + keychain-swap.mjs):
+ * readEntry(service) → raw JSON string or null
+ * writeEntry(service, json) → void
+ * deleteEntry(service) → void
+ */
+
+import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from 'fs';
+import { createHash } from 'node:crypto';
+import { join } from 'path';
+
+const HOME = process.env.HOME || process.env.USERPROFILE || '/root';
+export const ACTIVE_SERVICE = 'Claude Code-credentials';
+const ACTIVE_CREDS_PATH = join(HOME, '.claude', '.credentials.json');
+const VAULT_DIR = join(HOME, '.local', 'share', 'claude-rotation');
+
+function ensureVaultDir() {
+ mkdirSync(VAULT_DIR, { recursive: true, mode: 0o700 });
+}
+
+function vaultPath(service) {
+ const hash = createHash('sha256').update(service).digest('hex').slice(0, 24);
+ return join(VAULT_DIR, `${hash}.json`);
+}
+
+/**
+ * Read a stored credential entry.
+ * Returns raw JSON string on success, null if not found.
+ */
+export function readEntry(service) {
+ if (service === ACTIVE_SERVICE) {
+ if (!existsSync(ACTIVE_CREDS_PATH)) return null;
+ try {
+ return readFileSync(ACTIVE_CREDS_PATH, 'utf8').trim();
+ } catch {
+ return null;
+ }
+ }
+ const p = vaultPath(service);
+ if (!existsSync(p)) return null;
+ try {
+ return readFileSync(p, 'utf8').trim();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Write a credential entry.
+ * Active-service writes go directly to ~/.claude/.credentials.json.
+ * All others land in the vault dir as chmod-600 files.
+ */
+export function writeEntry(service, json) {
+ if (service === ACTIVE_SERVICE) {
+ writeFileSync(ACTIVE_CREDS_PATH, json, { mode: 0o600 });
+ return;
+ }
+ ensureVaultDir();
+ writeFileSync(vaultPath(service), json, { mode: 0o600 });
+}
+
+/**
+ * Delete a vault entry (no-op for the active-service entry — never delete live creds).
+ */
+export function deleteEntry(service) {
+ if (service === ACTIVE_SERVICE) return;
+ const p = vaultPath(service);
+ try {
+ if (existsSync(p)) unlinkSync(p);
+ } catch {}
+}
diff --git a/claude-ops/scripts/install-account-rotator-linux.sh b/claude-ops/scripts/install-account-rotator-linux.sh
new file mode 100755
index 00000000..c367d841
--- /dev/null
+++ b/claude-ops/scripts/install-account-rotator-linux.sh
@@ -0,0 +1,107 @@
+#!/usr/bin/env bash
+# install-account-rotator-linux.sh
+#
+# Purpose : Install the Claude account-rotation daemon as a systemd --user service.
+# Platform: Linux (Amazon Linux 2023 / Debian / Ubuntu — anything with systemd ≥ 232)
+# Schedule: Always-on (KeepAlive equivalent). The daemon polls every 15 s internally.
+# Rollback: systemctl --user disable --now claude-account-rotator.service
+# rm ~/.config/systemd/user/claude-account-rotator.service
+# systemctl --user daemon-reload
+#
+# Usage: bash install-account-rotator-linux.sh [--dry-run]
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+SERVICE_NAME="claude-account-rotator"
+UNIT_FILE="$HOME/.config/systemd/user/${SERVICE_NAME}.service"
+DAEMON_SCRIPT="$SCRIPT_DIR/account-rotation/daemon.mjs"
+LOG_DIR="$SCRIPT_DIR/account-rotation"
+DRY_RUN=0
+
+[[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
+
+log() { echo "[install-account-rotator] $*"; }
+die() { echo "[install-account-rotator] ERROR: $*" >&2; exit 1; }
+
+# ── Preflight ────────────────────────────────────────────────────────────────
+
+command -v node >/dev/null 2>&1 || die "node not found (need Node 20+)"
+command -v npx >/dev/null 2>&1 || die "npx not found"
+node --version | grep -qE 'v(2[0-9]|[3-9][0-9])' || die "Node 20+ required (got $(node --version))"
+[[ -f "$DAEMON_SCRIPT" ]] || die "daemon.mjs not found at $DAEMON_SCRIPT"
+
+# ── Dry-run validation ────────────────────────────────────────────────────────
+
+log "Dry-run: testing daemon starts cleanly..."
+TIMEOUT_EXIT=0
+timeout 5 node "$DAEMON_SCRIPT" --status >/dev/null 2>&1 || TIMEOUT_EXIT=$?
+# exit 1 = no pid file (expected on first run), anything else = real error
+if [[ $TIMEOUT_EXIT -gt 1 && $TIMEOUT_EXIT -ne 124 ]]; then
+ die "daemon.mjs --status exited $TIMEOUT_EXIT — fix errors before installing"
+fi
+log "Dry-run passed (exit $TIMEOUT_EXIT — ok)"
+
+[[ $DRY_RUN -eq 1 ]] && { log "--dry-run: skipping install"; exit 0; }
+
+# ── Write unit file ───────────────────────────────────────────────────────────
+
+mkdir -p "$(dirname "$UNIT_FILE")"
+
+cat > "$UNIT_FILE" <<EOF
+# claude-account-rotator.service
+# Generated by install-account-rotator-linux.sh — $(date -u +%Y-%m-%dT%H:%M:%SZ)
+#
+# Purpose : Claude Max account rotation daemon — monitors usage and swaps
+# OAuth tokens automatically as 5-hour / 7-day caps approach.
+# Platform: Linux (file-based vault in ~/.local/share/claude-rotation/)
+# Rollback: systemctl --user disable --now claude-account-rotator.service
+
+[Unit]
+Description=Claude Max account rotation daemon
+After=network.target
+
+[Service]
+Type=simple
+ExecStart=$(command -v node) $DAEMON_SCRIPT
+Restart=on-failure
+RestartSec=30
+# Give it 10 s to shut down cleanly before SIGKILL
+TimeoutStopSec=10
+
+# Logs
+StandardOutput=append:${LOG_DIR}/account-rotation/rotation.log
+StandardError=append:${LOG_DIR}/account-rotation/rotation.log
+
+# Environment
+Environment=HOME=$HOME
+Environment=NODE_ENV=production
+Environment=CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT=${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-${USER:-ec2-user}}
+
+[Install]
+WantedBy=default.target
+EOF
+
+log "Unit file written: $UNIT_FILE"
+
+# ── Enable & start ────────────────────────────────────────────────────────────
+
+systemctl --user daemon-reload
+systemctl --user enable "$SERVICE_NAME"
+systemctl --user restart "$SERVICE_NAME"
+
+# ── Health check ─────────────────────────────────────────────────────────────
+
+sleep 2
+STATUS=$(systemctl --user is-active "$SERVICE_NAME" 2>&1)
+if [[ "$STATUS" == "active" ]]; then
+ log "READY — ${SERVICE_NAME}.service is active"
+ systemctl --user status "$SERVICE_NAME" --no-pager -n 5
+else
+ echo ""
+ log "NEEDS_FIXES — service status: $STATUS"
+ systemctl --user status "$SERVICE_NAME" --no-pager -n 20
+ echo ""
+ log "Remediation: check logs with: journalctl --user -u ${SERVICE_NAME}.service -n 50"
+ exit 1
+fi