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
refactor(telegram): env-templated channel-mcp leader gate (PID→env) (#578)
Aurora Capital2bd44e0ff59d
diff --git a/claude-ops/scripts/account-rotation/ai-brain.mjs b/claude-ops/scripts/account-rotation/ai-brain.mjsindex aa95348d..31b9f7bc 100644--- a/claude-ops/scripts/account-rotation/ai-brain.mjs+++ b/claude-ops/scripts/account-rotation/ai-brain.mjs@@ -444,9 +444,7 @@ export async function scrapeBillingState(page, log = () => {}) {// credits_usd — first dollar amount near a "credit"/"balance" mention.let credits_usd = null;- const creditLine = text- .split('\n')- .find((l) => /credit|balance/i.test(l) && /\$\s?\d/.test(l));+ const creditLine = text.split('\n').find((l) => /credit|balance/i.test(l) && /\$\s?\d/.test(l));const dollarMatch = (creditLine || '').match(/\$\s?([\d,]+(?:\.\d{1,2})?)/);if (dollarMatch) {const n = parseFloat(dollarMatch[1].replace(/,/g, ''));@@ -462,9 +460,7 @@ export async function scrapeBillingState(page, log = () => {}) {// extra_usage_enabled — "extra usage" / "overage" on/off copy.let extra_usage_enabled = null;- const extraMatch = text.match(- /(?:extra usage|overage)[^\n]*?\b(on|off|enabled|disabled)\b/i,- );+ const extraMatch = text.match(/(?:extra usage|overage)[^\n]*?\b(on|off|enabled|disabled)\b/i);if (extraMatch) {extra_usage_enabled = /on|enabled/i.test(extraMatch[1]);}diff --git a/claude-ops/scripts/account-rotation/provider-router.mjs b/claude-ops/scripts/account-rotation/provider-router.mjsindex 2b350bfd..821cdecb 100644--- a/claude-ops/scripts/account-rotation/provider-router.mjs+++ b/claude-ops/scripts/account-rotation/provider-router.mjs@@ -96,10 +96,16 @@ const server = http.createServer((req, res) => {if (route.mode === 'bedrock') {// PHASE 2 not yet implemented — fail loud rather than silently meter.res.writeHead(501, { 'content-type': 'application/json' });- res.end(JSON.stringify({- type: 'error',- error: { type: 'not_implemented', message: 'router bedrock leg not yet built; set mode=oauth or use env-gated CLAUDE_CODE_USE_BEDROCK fallback' },- }));+ res.end(+ JSON.stringify({+ type: 'error',+ error: {+ type: 'not_implemented',+ message:+ 'router bedrock leg not yet built; set mode=oauth or use env-gated CLAUDE_CODE_USE_BEDROCK fallback',+ },+ }),+ );log(`501 bedrock leg unimplemented (path ${req.url})`);return;}@@ -121,7 +127,9 @@ const server = http.createServer((req, res) => {headers.authorization = `Bearer ${token}`;const betas = new Set(String(headers['anthropic-beta'] || '')- .split(',').map((s) => s.trim()).filter(Boolean),+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean),);betas.add(OAUTH_BETA);headers['anthropic-beta'] = [...betas].join(',');diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex bf8aab32..294f32b6 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -55,14 +55,12 @@ const __dirname = dirname(fileURLToPath(import.meta.url));// setup-account.mjs, Rule 0: no real account data in the committed repo).// Prefer it; fall back to the committed repo default at __dirname/config.json.const CONFIG_USER_PATH = join(- process.env.CLAUDE_PLUGIN_DATA_DIR ||- join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace'),+ process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace'),'account-rotation-config.json',);const CONFIG_REPO_PATH = join(__dirname, 'config.json');const CONFIG_PATH =- process.env.CLAUDE_ROTATOR_CONFIG ||- (existsSync(CONFIG_USER_PATH) ? CONFIG_USER_PATH : CONFIG_REPO_PATH);+ process.env.CLAUDE_ROTATOR_CONFIG || (existsSync(CONFIG_USER_PATH) ? CONFIG_USER_PATH : CONFIG_REPO_PATH);const STATE_PATH = join(__dirname, 'state.json');const LOCK_PATH = join(__dirname, '.rotating');const LOG_PATH = join(__dirname, 'rotation.log');diff --git a/claude-ops/scripts/ops-deploy-monitor.sh b/claude-ops/scripts/ops-deploy-monitor.shindex 394ffbe1..1a3c7865 100755--- a/claude-ops/scripts/ops-deploy-monitor.sh+++ b/claude-ops/scripts/ops-deploy-monitor.sh@@ -7,6 +7,10 @@set -uPLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"+# Load deploy-fix library (provides lock_acquire, dispatch_fix_agent, config, etc.)+# shellcheck disable=SC1091+source "$PLUGIN_ROOT/scripts/lib/deploy-fix-common.sh"+# Single-instance guard - prevent stacking on rapid spawnssource "$HOME/.claude/scripts/lib/once.sh"REPO="${1:?usage: $0 <owner/repo> <pr_number>}"diff --git a/claude-ops/telegram-server/channel-mcp.mjs b/claude-ops/telegram-server/channel-mcp.mjsindex c3596fbf..bcac4702 100644--- a/claude-ops/telegram-server/channel-mcp.mjs+++ b/claude-ops/telegram-server/channel-mcp.mjs@@ -23,6 +23,16 @@* TELEGRAM_STATE_DIR — override ~/.claude/channels/telegram/* TELEGRAM_POLL_TIMEOUT — long-poll timeout in seconds (default 25)*+ * Fleet single-owner gate (env contract — no PID/proc/marker files):+ * DEVBOT_TELEGRAM_OWNER — the designated owner session exports it as '1'.+ * Unset/empty → plain single-session install → FAIL OPEN (poll normally).+ * '1' → this session owns Telegram. Any other value → a sibling owns it →+ * stand down. Durable across /ops:ops-update and portable to any OS.+ * TELEGRAM_CHANNEL_POLL — optional poll opt-out. '0' → do NOT poll getUpdates+ * even when leader (an external poller owns inbound); the leader-gated+ * reply/outbound tool stays available. Unset/anything-else → poll when+ * leader (default). Polling is never disabled by default.+ ** Self-test (no network, no real token required):* node telegram-server/channel-mcp.mjs --selftest*@@ -81,37 +91,36 @@ function loadSecretsEnv() {}const secretsEnv = loadSecretsEnv();+// ── Fleet single-owner gate (env contract) ──────────────────────────────────+// Every Claude Code fleet session loads this plugin and would otherwise spawn a+// channel-mcp polling Telegram getUpdates on the SAME bot token. Telegram+// delivers each update to exactly ONE long-poller, so multiple consumers steal+// each other's updates (409 conflict). The gate elects a single owner via a pure+// env contract — no PID, no /proc walk, no marker files — so it is durable across+// `/ops:ops-update`, portable to any OS, and not coupled to process trees.+//+// Two env vars govern the gate:+//+// DEVBOT_TELEGRAM_OWNER — the single-owner election.+// • unset / empty → plain single-session install (no fleet) → FAIL OPEN,+// this session owns Telegram and polls normally.+// • '1' → this session is the designated owner → poll + reply.+// • any other value→ a sibling session owns Telegram → stand down.+//+// TELEGRAM_CHANNEL_POLL — optional poll opt-out (read at the poll site).+// • unset / anything but '0' → poll getUpdates when leader (default).+// • '0' → do NOT poll getUpdates even when leader (an+// external poller owns inbound); the leader-gated+// `reply`/outbound tool stays available.function thisSessionIsLeader() {- // FAIL OPEN by default: the leader-gate is an opt-in fleet feature. A plain- // claude-ops install (no fleet supervisor) or a non-Linux host (no /proc) must- // poll normally — the gate only LOCKS OUT a session when it can positively prove- // a *different* live session leads. Anything it can't prove → poll.- let marker;- try {- marker = readFileSync(join(homedir(), '.claude', 'state', 'fleet-supervisor.leader'), 'utf8');- } catch {- return true; // no fleet marker → not a managed fleet → poll normally- }- const m = marker.match(/pid:(\d+)/);- if (!m) return true; // marker without a pid → can't enforce → poll- const leaderPid = m[1];- let pid = String(process.pid);- for (let i = 0; i < 64; i++) {- if (pid === leaderPid) return true; // this process is in the leader's tree- let stat;- try {- stat = readFileSync(`/proc/${pid}/stat`, 'utf8');- } catch {- return true; // /proc unreadable (non-Linux / process gone) → can't prove → poll- }- const after = stat- .slice(stat.lastIndexOf(')') + 2)- .trim()- .split(/\s+/);- pid = after[1];- if (!pid || pid === '0' || pid === '1') return false; // reached init: NOT the leader's tree- }- return false; // ran out of hops without matching → treat as non-leader+ // Fleet single-owner gate — pure env, no PID/proc-tree/marker files.+ // The designated owner session exports DEVBOT_TELEGRAM_OWNER=1. FAIL OPEN:+ // when unset/empty this is a plain single-session install (no fleet) → poll+ // normally. Any explicit value other than '1' means a sibling session owns+ // Telegram → stand down.+ const v = process.env.DEVBOT_TELEGRAM_OWNER;+ if (v === undefined || v === '') return true;+ return v === '1';}const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || prefs.bot_token || secretsEnv.TELEGRAM_BOT_TOKEN || '';@@ -388,12 +397,25 @@ await mcp.connect(new StdioServerTransport());// Poll runs after MCP transport is up so notifications can be dispatched.let backoffMs = 0;+// TELEGRAM_CHANNEL_POLL=0 disables getUpdates polling even when this session is+// the leader (for setups where an external poller owns inbound). The+// leader-gated reply/outbound tool stays available either way. Default (unset or+// any value but '0') = poll when leader. Never disabled by default.+const POLL_ENABLED = process.env.TELEGRAM_CHANNEL_POLL !== '0';+async function poll() {if (shuttingDown) return;if (!BOT_TOKEN) {setTimeout(poll, 30_000).unref();return;}+ if (!POLL_ENABLED) {+ process.stderr.write(+ 'telegram-channel: TELEGRAM_CHANNEL_POLL=0 — getUpdates polling disabled (external poller owns inbound); ' ++ 'leader-gated reply tool stays available.\n',+ );+ return;+ }if (!thisSessionIsLeader()) {setTimeout(poll, 15_000).unref();return;diff --git a/claude-ops/tests/mocks/once.sh b/claude-ops/tests/mocks/once.shnew file mode 100755index 00000000..b7e4a2b7--- /dev/null+++ b/claude-ops/tests/mocks/once.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+# Mock once.sh — always permit (return 0) so tests can run multiple times+# without rate-limit throttling from the real once.sh guard.+#+# Usage: source this instead of $HOME/.claude/scripts/lib/once.sh+#+claude_once() {+ # Accept key + optional throttle but ignore them; always return success+ return 0+}diff --git a/claude-ops/tests/test-deploy-fix-hooks.sh b/claude-ops/tests/test-deploy-fix-hooks.shindex 1c299500..42d136c0 100755--- a/claude-ops/tests/test-deploy-fix-hooks.sh+++ b/claude-ops/tests/test-deploy-fix-hooks.sh@@ -63,14 +63,18 @@ new_isolated_env() {TEST_STATE="$SUITE_TMP/$id/state"TEST_LOGS="$SUITE_TMP/$id/logs"TEST_BIN="$SUITE_TMP/$id/bin"- mkdir -p "$TEST_STATE" "$TEST_LOGS" "$TEST_BIN"+ TEST_HOME="$SUITE_TMP/$id/home"+ mkdir -p "$TEST_STATE" "$TEST_LOGS" "$TEST_BIN" "$TEST_HOME/.claude/scripts/lib"# Symlink mocks into a private bin so we control PATH orderingfor m in gh claude curl terminal-notifier; doln -sf "$MOCKS/$m" "$TEST_BIN/$m"done+ # Provide mock once.sh so monitor tests don't rate-limit+ ln -sf "$MOCKS/once.sh" "$TEST_HOME/.claude/scripts/lib/once.sh"export OPS_DEPLOY_FIX_STATE="$TEST_STATE"export OPS_DEPLOY_FIX_LOGS="$TEST_LOGS"export CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT"+ export HOME="$TEST_HOME"export MOCK_GH_LOG_FILE="$TEST_LOGS/gh.log"export MOCK_CLAUDE_LOG="$TEST_LOGS/claude.log"export MOCK_CLAUDE_PROMPT_OUT="$TEST_LOGS/claude-prompt.txt"