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(statusline): templatable cockpit + /ops:statusline + /ops-setup wizard + registry auto-suggest (phase-16) (#583)
Aurora Capitalde391a4c8ed6
diff --git a/claude-ops/bin/ops-statusline-suggest b/claude-ops/bin/ops-statusline-suggestnew file mode 100755index 00000000..d529d21f--- /dev/null+++ b/claude-ops/bin/ops-statusline-suggest@@ -0,0 +1,261 @@+#!/bin/sh+# ops-statusline-suggest — registry-driven statusline.config.json generator.+#+# Reads the ops partner registry and project list from preferences.json, detects+# which integrations are actually configured (by checking env vars, plugin+# settings, and prefs keys), then emits a recommended statusline.config.json+# tailored to the user's configured stack.+#+# Usage:+# ops-statusline-suggest [--preset minimal|cockpit|full] [--theme <name>]+#+# Output: JSON on stdout, diagnostics on stderr.+# Exit 0 on success. Uses only jq + POSIX sh — no network, no npm.++set -e++# ── Args ─────────────────────────────────────────────────────────────────────+PRESET="cockpit"+THEME="cockpit"++while [ $# -gt 0 ]; do+ case "$1" in+ --preset) PRESET="$2"; shift 2 ;;+ --theme) THEME="$2"; shift 2 ;;+ *) shift ;;+ esac+done++case "$PRESET" in+ minimal|cockpit|full) ;;+ *) echo "Unknown preset '$PRESET', defaulting to cockpit" >&2; PRESET="cockpit" ;;+esac++# ── Paths ─────────────────────────────────────────────────────────────────────+PREFS_PATH="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1)}"++# ── Detect configured integrations ────────────────────────────────────────────+# Returns 0 (configured) or 1 (not configured) for each integration.+# Detection order: preferences.json flag → env var → non-empty prefs value.+is_configured() {+ _svc="$1"+ # Check *_enabled flag in prefs+ _flag=$(jq -r --arg k "${_svc}_enabled" '.[$k] // false' "$PREFS_PATH" 2>/dev/null)+ [ "$_flag" = "true" ] && return 0+ # Check env var presence+ _envkey=$(printf '%s' "$_svc" | tr '[:lower:]' '[:upper:]')+ eval "_envval=\${${_envkey}_API_KEY:-}\${${_envkey}_SECRET_KEY:-}\${${_envkey}_TOKEN:-}"+ [ -n "$_envval" ] && return 0+ return 1+}++# Read prefs safely+_prefs_exists=0+[ -f "$PREFS_PATH" ] && _prefs_exists=1++# ── Detect project registry ───────────────────────────────────────────────────+_registry_file="${PLUGIN_ROOT}scripts/registry.json"+[ ! -f "$_registry_file" ] && _registry_file="${HOME}/.claude/config/registry.json"++_project_count=0+_projects_json="[]"+if [ -f "$_registry_file" ] 2>/dev/null; then+ _project_count=$(jq '. | if type == "array" then length elif type == "object" then (.projects // [] | length) else 0 end' "$_registry_file" 2>/dev/null || echo 0) || true+fi++# Also check prefs for project list+if [ "$_prefs_exists" = "1" ]; then+ _prefs_proj=$(jq -r '(.projects // []) | length' "$PREFS_PATH" 2>/dev/null || echo 0) || true+ [ "${_prefs_proj:-0}" -gt "${_project_count:-0}" ] && _project_count="$_prefs_proj" || true+fi++echo "Detected ${_project_count} projects in registry" >&2++# ── Service detection ─────────────────────────────────────────────────────────+# For each service, detect if it's configured and classify into widget categories.+_has_stripe=0; _has_revenuecat=0; _has_shopify=0+_has_ecs=0; _has_sentry=0; _has_linear=0+_has_meta=0; _has_klaviyo=0; _has_ga4=0+_has_spotify=0; _has_shipbob=0; _has_doppler=0++if [ "$_prefs_exists" = "1" ]; then+ _has_stripe=$(jq -r 'if (.stripe_enabled == true or (.stripe_secret_key // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_revenuecat=$(jq -r 'if (.revenuecat_enabled == true or (.revenuecat_api_key // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_shopify=$(jq -r 'if (.shopify_enabled == true or (.shopify_store_url // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_sentry=$(jq -r 'if (.sentry_enabled == true or (.sentry_org // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_linear=$(jq -r 'if (.linear_enabled == true or (.linear_team // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_meta=$(jq -r 'if (.meta_ads_enabled == true or (.meta_ads_token // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_klaviyo=$(jq -r 'if (.klaviyo_enabled == true or (.klaviyo_private_key // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_ga4=$(jq -r 'if (.ga4_enabled == true or ((.ga4_property_id // 0) > 0)) then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_doppler=$(jq -r 'if (.doppler_enabled == true or (.doppler_project // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+ _has_shipbob=$(jq -r 'if (.shipbob_enabled == true or (.shipbob_access_token // "") != "") then 1 else 0 end' "$PREFS_PATH" 2>/dev/null || echo 0)+fi++# Check env vars as fallback+[ -n "${STRIPE_SECRET_KEY:-}${STRIPE_API_KEY:-}" ] && _has_stripe=1+[ -n "${REVENUECAT_API_KEY:-}" ] && _has_revenuecat=1+[ -n "${SHOPIFY_STORE_URL:-}${SHOPIFY_ADMIN_TOKEN:-}" ] && _has_shopify=1+[ -n "${SENTRY_AUTH_TOKEN:-}${SENTRY_ORG:-}" ] && _has_sentry=1+[ -n "${LINEAR_API_KEY:-}" ] && _has_linear=1+[ -n "${META_ADS_TOKEN:-}${META_ACCESS_TOKEN:-}" ] && _has_meta=1+[ -n "${KLAVIYO_PRIVATE_KEY:-}" ] && _has_klaviyo=1+[ -n "${GA4_PROPERTY_ID:-}" ] && _has_ga4=1+[ -n "${DOPPLER_TOKEN:-}" ] && _has_doppler=1++# Check for ECS/AWS integration (aws CLI available and region configured)+# C3: non-fatal — aws probe can fail (no creds, no network) without aborting the run+command -v aws >/dev/null 2>&1 && aws sts get-caller-identity >/dev/null 2>&1 && _has_ecs=1 || true++echo "Integrations detected: stripe=${_has_stripe} revenuecat=${_has_revenuecat} shopify=${_has_shopify} sentry=${_has_sentry} linear=${_has_linear} ecs=${_has_ecs} meta=${_has_meta} klaviyo=${_has_klaviyo} ga4=${_has_ga4}" >&2++# ── Build projects array ──────────────────────────────────────────────────────+# Read project registry and map each project to suggested badges based on stack.+_projects_out="[]"++_read_projects() {+ # Try registry.json first+ if [ -f "$_registry_file" ]; then+ jq -r '+ (if type == "array" then . elif type == "object" then (.projects // []) else [] end)+ | .[] | "\(.alias // .name // .key // "unknown") \(.infra.platform // "unknown") \(.revenue.model // "unknown") \(.org // "")"+ ' "$_registry_file" 2>/dev/null+ fi+}++# Build project entries from registry+_proj_entries=""+_idx=0++while IFS=' ' read -r _alias _platform _revenue_model _org; do+ [ -z "$_alias" ] && continue+ [ "$_idx" -ge 8 ] && break # cap at 8 projects for readability++ # Determine badge set from project type + configured integrations+ _badges="[]"+ _labels=""+ _match=$(printf '%s' "$_alias" | tr '[:upper:]' '[:lower:]')++ # ECS/infra badge (AWS platform)+ case "$_platform" in aws|ecs|fargate)+ [ "$_has_ecs" = "1" ] && _labels="${_labels}\"ecs\"," ;;+ esac++ # Revenue badges based on model+ case "$_revenue_model" in+ saas|subscription)+ [ "$_has_stripe" = "1" ] && _labels="${_labels}\"mrr\","+ [ "$_has_revenuecat" = "1" ] && _labels="${_labels}\"mobile_subs\","+ ;;+ marketplace|ecom*)+ [ "$_has_shopify" = "1" ] && _labels="${_labels}\"orders\","+ [ "$_has_stripe" = "1" ] && _labels="${_labels}\"revenue\","+ ;;+ esac++ # Error tracking+ [ "$_has_sentry" = "1" ] && _labels="${_labels}\"errors\","+ # Issue tracking+ [ "$_has_linear" = "1" ] && _labels="${_labels}\"issues\","++ # Remove trailing comma and wrap as JSON array+ _labels="${_labels%,}"+ [ -z "$_labels" ] && _labels_json="[]" || _labels_json="[${_labels}]"++ # H2: use jq to build the JSON entry so special chars in alias/match can't break it+ _entry=$(jq -n --arg k "$_alias" --arg l "$_alias" --arg m "$_match" \+ --argjson b "$_labels_json" \+ '{"key":$k,"label":$l,"match":$m,"badges":$b}') || true++ if [ -n "$_entry" ]; then+ if [ -z "$_proj_entries" ]; then+ _proj_entries="$_entry"+ else+ _proj_entries="${_proj_entries},${_entry}"+ fi+ fi++ _idx=$(( _idx + 1 ))+done << EOF+$(_read_projects)+EOF++[ -n "$_proj_entries" ] && _projects_out="[${_proj_entries}]"++# ── Preset-specific settings ──────────────────────────────────────────────────+case "$PRESET" in+ minimal)+ _ctx_w=6; _quota_w=5; _carousel=15+ _fleet_bg="false"; _fleet_rot="true"; _fleet_sdk="false"; _fleet_cache="false"+ _sys_cpu="false"; _sys_ram="true"; _sys_disk="false"+ _carousel_pool='["cost","global_ops"]'+ ;;+ full)+ _ctx_w=12; _quota_w=10; _carousel=15+ _fleet_bg="true"; _fleet_rot="true"; _fleet_sdk="true"; _fleet_cache="true"+ _sys_cpu="true"; _sys_ram="true"; _sys_disk="true"+ _carousel_pool='["cost","lines","global_ops"]'+ ;;+ cockpit|*)+ _ctx_w=10; _quota_w=8; _carousel=15+ _fleet_bg="true"; _fleet_rot="true"; _fleet_sdk="true"; _fleet_cache="true"+ _sys_cpu="true"; _sys_ram="true"; _sys_disk="true"+ _carousel_pool='["cost","lines","global_ops"]'+ ;;+esac++# ── Emit config JSON ──────────────────────────────────────────────────────────+cat <<JSONEOF+{+ "_comment": "Auto-generated by ops-statusline-suggest on $(date -u +%Y-%m-%dT%H:%M:%SZ). Edit freely — re-run /ops:statusline config to regenerate.",+ "_detected": {+ "preset": "${PRESET}",+ "projects_found": ${_project_count},+ "integrations": {+ "stripe": $([ "$_has_stripe" = "1" ] && echo true || echo false),+ "revenuecat": $([ "$_has_revenuecat" = "1" ] && echo true || echo false),+ "shopify": $([ "$_has_shopify" = "1" ] && echo true || echo false),+ "sentry": $([ "$_has_sentry" = "1" ] && echo true || echo false),+ "linear": $([ "$_has_linear" = "1" ] && echo true || echo false),+ "ecs_aws": $([ "$_has_ecs" = "1" ] && echo true || echo false),+ "meta_ads": $([ "$_has_meta" = "1" ] && echo true || echo false),+ "klaviyo": $([ "$_has_klaviyo" = "1" ] && echo true || echo false),+ "ga4": $([ "$_has_ga4" = "1" ] && echo true || echo false)+ }+ },++ "theme": "${THEME}",++ "gauge_width": {+ "ctx": ${_ctx_w},+ "quota": ${_quota_w}+ },++ "carousel_interval_sec": ${_carousel},++ "widgets": {+ "line1": ["ctx_gauge", "quota_gauge", "pace_badge", "cache_badge", "plan_badge", "account_arrow"],+ "line2": ["location", "model", "git_branch", "tasks", "fleet", "sys_metrics", "carousel"],+ "line3": ["project_rotate"]+ },++ "fleet": {+ "show_bg_agents": ${_fleet_bg},+ "show_rotation": ${_fleet_rot},+ "show_sdk_fallback": ${_fleet_sdk},+ "show_cache_ttl": ${_fleet_cache}+ },++ "sys_metrics": {+ "show_cpu": ${_sys_cpu},+ "show_ram": ${_sys_ram},+ "show_disk": ${_sys_disk},+ "show_load_warning": true,+ "show_disk_warning": true+ },++ "carousel_pool": ${_carousel_pool},++ "projects": ${_projects_out}+}+JSONEOFdiff --git a/claude-ops/skills/ops-statusline/SKILL.md b/claude-ops/skills/ops-statusline/SKILL.mdnew file mode 100644index 00000000..e2f9ee1e--- /dev/null+++ b/claude-ops/skills/ops-statusline/SKILL.md@@ -0,0 +1,344 @@+---+name: ops-statusline+description: Statusline command center — preview, configure, switch themes, validate, and reset the Claude Code cockpit statusline. Subcommands: preview, config, theme, doctor, reset.+argument-hint: "[preview|config|theme <name>|doctor|reset]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Edit+ - AskUserQuestion+effort: low+maxTurns: 20+---++## Runtime Context++Before any subcommand, resolve paths:++```bash+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1)}"+STATUSLINE_CMD="$HOME/.claude/statusline-command.sh"+STATUSLINE_CFG="$HOME/.claude/statusline.config.json"+THEMES_FILE="${PLUGIN_ROOT}templates/statusline/themes.json"+SETTINGS_FILE="$HOME/.claude/settings.json"+SUGGEST_BIN="${PLUGIN_ROOT}bin/ops-statusline-suggest"+```++---++# OPS ► STATUSLINE++Manages the Claude Code cockpit statusline — a 3-line terminal status bar showing+context-window health, quota gauges, burn rate, git branch, fleet state, sys metrics,+and per-project ops badges.++Parse `$ARGUMENTS` and route:++| Argument (first word) | Action |+|-----------------------|--------|+| `preview` or empty | Render a sample output at current terminal width |+| `config` | Re-run the wizard: preset, theme, projects, gauge widths |+| `theme <name>` | Switch theme in config |+| `doctor` | Validate config, settings.json wiring, renderer path |+| `reset` | Restore default config from template |+| (anything else) | Show help + current status |++---++## Subcommand: preview++Render the statusline using the current config against a built-in sample payload.+Never touches real config or settings files.++### Step 1 — Build sample payload++```bash+COLS="${COLUMNS:-$(tput cols 2>/dev/null || echo 120)}"+SAMPLE_PAYLOAD=$(cat <<'JSON'+{+ "workspace": { "current_dir": "/home/user/Projects/my-app" },+ "model": { "display_name": "Claude Sonnet 4.6" },+ "rate_limits": {+ "five_hour": { "used_percentage": 42, "resets_at": 0 },+ "seven_day": { "used_percentage": 18, "resets_at": 0 }+ },+ "context_window": { "used_percentage": 31 },+ "cost": { "total_cost_usd": 0.14, "total_lines_added": 120, "total_lines_removed": 40 },+ "session_id": "preview-sample",+ "transcript_path": ""+}+JSON+)+```++### Step 2 — Run renderer++```bash+COLUMNS="$COLS" printf '%s' "$SAMPLE_PAYLOAD" | "$STATUSLINE_CMD" 2>/dev/null+```++If `$STATUSLINE_CMD` is not executable, fall back to the template:++```bash+COLUMNS="$COLS" printf '%s' "$SAMPLE_PAYLOAD" | sh "${PLUGIN_ROOT}templates/statusline/statusline-command.sh" 2>/dev/null+```++Print the rendered output between ruler lines so the user sees the actual width context:++```+──────────────────────────────────────── (preview at 120 cols)+<rendered lines>+────────────────────────────────────────+```++If rendering fails (exit non-zero), print:+```+○ Preview failed — renderer returned non-zero.+ Check: /ops:statusline doctor+```++---++## Subcommand: config++Re-run the wizard — preset, theme, projects, and gauge widths. Calls the suggest+engine to seed a recommended config, then lets the user confirm or adjust each section.+Writing to `~/.claude/statusline.config.json` (never touches the real settings.json+statusLine wiring — that is only changed by /ops:setup).++### Step 1 — Run suggest engine++```bash+SUGGESTED=$("$SUGGEST_BIN" 2>/tmp/ops-statusline-suggest.log)+```++Parse the `_detected` block to present context to the user:++```bash+PROJ_COUNT=$(printf '%s' "$SUGGESTED" | jq -r '._detected.projects_found // 0')+INTEGRATIONS=$(printf '%s' "$SUGGESTED" | jq -r '._detected.integrations | to_entries | map(select(.value)) | map(.key) | join(", ") // "none"')+```++Print detection summary:+```+Detected N projects · integrations: <list>+```++### Step 2 — Preset selection++Use `AskUserQuestion` (max 4 options per CLAUDE.md Rule 1):++```+Which preset?+ [cockpit — full color, all widgets (Recommended)]+ [minimal — essentials only, low noise]+ [full — all metrics, widest gauges]+ [Keep current preset]+```++Re-run suggest with chosen preset:+```bash+SUGGESTED=$("$SUGGEST_BIN" --preset "$CHOSEN_PRESET" 2>/dev/null)+```++### Step 3 — Theme selection++Use `AskUserQuestion`:++```+Which theme?+ [cockpit — rich color, graded gauges (Default)]+ [minimal — two shades, no color grading]+ [nord — cool blues]+ [mono — bold only, no color]+```++Patch the suggested config with chosen theme:+```bash+SUGGESTED=$(printf '%s' "$SUGGESTED" | jq --arg t "$CHOSEN_THEME" '.theme = $t')+```++### Step 4 — Write config++```bash+TMP=$(mktemp)+printf '%s\n' "$SUGGESTED" | jq 'del(._comment, ._detected)+ | . + {"_comment": "Configured by /ops:statusline config on '"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'."}' > "$TMP"+mv "$TMP" "$STATUSLINE_CFG"+```++Validate the written JSON:+```bash+jq . "$STATUSLINE_CFG" >/dev/null 2>&1 && echo "✓ Config written to $STATUSLINE_CFG" || echo "✗ JSON validation failed"+```++### Step 5 — Offer preview++Use `AskUserQuestion`:+```+Config saved. Preview now?+ [Yes — show preview] [No — done]+```++On Yes, run the preview subcommand inline.++---++## Subcommand: theme++Switch the theme key in the existing config without touching other settings.++```bash+NEW_THEME="${ARGUMENTS#theme }"+NEW_THEME=$(printf '%s' "$NEW_THEME" | tr -d '[:space:]')+```++Validate theme exists in themes.json:+```bash+VALID=$(jq -e --arg t "$NEW_THEME" '.[$t] // empty' "$THEMES_FILE" 2>/dev/null)+```++If invalid, list available themes and error:+```bash+AVAILABLE=$(jq -r 'keys | join(", ")' "$THEMES_FILE" 2>/dev/null)+echo "Unknown theme '$NEW_THEME'. Available: $AVAILABLE"+exit 1+```++If valid, merge into existing config:+```bash+TMP=$(mktemp)+if [ -f "$STATUSLINE_CFG" ]; then+ jq --arg t "$NEW_THEME" '.theme = $t' "$STATUSLINE_CFG" > "$TMP"+else+ jq -n --arg t "$NEW_THEME" '{"theme": $t}' > "$TMP"+fi+mv "$TMP" "$STATUSLINE_CFG"+echo "✓ Theme set to '$NEW_THEME'"+```++Run a quick preview automatically after switching.++---++## Subcommand: doctor++Validate that all statusline components are healthy. Check and report:++### Check 1 — Renderer exists and is executable++```bash+if [ -x "$STATUSLINE_CMD" ]; then+ echo "✓ Renderer: $STATUSLINE_CMD"+else+ echo "✗ Renderer not found at $STATUSLINE_CMD"+ echo " Fix: /ops:setup → Statusline section, or run:"+ echo " cp '${PLUGIN_ROOT}templates/statusline/statusline-command.sh' '$STATUSLINE_CMD' && chmod +x '$STATUSLINE_CMD'"+fi+```++### Check 2 — settings.json statusLine wiring++```bash+if [ -f "$SETTINGS_FILE" ]; then+ SL_CMD=$(jq -r '.statusLine.command // empty' "$SETTINGS_FILE" 2>/dev/null)+ if [ -n "$SL_CMD" ]; then+ echo "✓ settings.json statusLine.command: $SL_CMD"+ # Verify it points at an executable+ eval SL_EXPANDED="$SL_CMD"+ [ -x "$SL_EXPANDED" ] || echo " ⚠ command path is not executable — may need /ops:setup statusline"+ else+ echo "○ settings.json has no statusLine.command — statusline not wired"+ echo " Fix: /ops:setup → Statusline section"+ fi+else+ echo "○ ~/.claude/settings.json not found — statusline not wired"+fi+```++### Check 3 — Config JSON validity++```bash+if [ -f "$STATUSLINE_CFG" ]; then+ if jq . "$STATUSLINE_CFG" >/dev/null 2>&1; then+ THEME=$(jq -r '.theme // "cockpit"' "$STATUSLINE_CFG")+ PROJ_COUNT=$(jq -r '(.projects // []) | length' "$STATUSLINE_CFG")+ echo "✓ Config: $STATUSLINE_CFG (theme=$THEME, projects=$PROJ_COUNT)"+ else+ echo "✗ Config JSON invalid: $STATUSLINE_CFG"+ echo " Fix: /ops:statusline reset"+ fi+else+ echo "○ No config at $STATUSLINE_CFG — using built-in defaults"+fi+```++### Check 4 — Themes file present++```bash+if [ -f "$THEMES_FILE" ]; then+ THEMES=$(jq -r 'keys | join(", ")' "$THEMES_FILE" 2>/dev/null)+ echo "✓ Themes: $THEMES"+else+ echo "⚠ themes.json missing at $THEMES_FILE — theme switching may fail"+fi+```++### Check 5 — Quick render smoke test++```bash+PAYLOAD='{"model":{"display_name":"Test"},"rate_limits":{},"context_window":{},"cost":{}}'+RESULT=$(printf '%s' "$PAYLOAD" | COLUMNS=80 "$STATUSLINE_CMD" 2>/dev/null)+if [ -n "$RESULT" ]; then+ echo "✓ Render smoke test: PASS ($(printf '%s' "$RESULT" | wc -l | tr -d ' ') lines)"+else+ echo "✗ Render smoke test: FAIL — no output"+fi+```++Print final verdict: **OK** (all checks pass) or **Issues found** (with remediation steps).++---++## Subcommand: reset++Restore `~/.claude/statusline.config.json` from the default template.++Use `AskUserQuestion`:+```+Reset statusline config to defaults?+ [Yes — overwrite ~/.claude/statusline.config.json] [Cancel]+```++On Yes:+```bash+cp "${PLUGIN_ROOT}templates/statusline/statusline.config.default.json" "$STATUSLINE_CFG"+echo "✓ Config reset to defaults"+```++Then run preview.++---++## CLI/API Reference++| Command | Effect |+|---------|--------|+| `/ops:statusline preview` | Render sample output |+| `/ops:statusline config` | Re-run wizard |+| `/ops:statusline theme cockpit\|minimal\|mono\|nord` | Switch theme |+| `/ops:statusline doctor` | Validate all components |+| `/ops:statusline reset` | Restore default config |++### Key files++| File | Purpose |+|------|---------|+| `~/.claude/statusline-command.sh` | The renderer script |+| `~/.claude/statusline.config.json` | User config (theme, widgets, projects) |+| `~/.claude/settings.json` | Contains `.statusLine.command` wiring |+| `${PLUGIN_ROOT}templates/statusline/statusline-command.sh` | Canonical renderer template |+| `${PLUGIN_ROOT}templates/statusline/themes.json` | Available themes |+| `${PLUGIN_ROOT}templates/statusline/statusline.config.default.json` | Default config |+| `${PLUGIN_ROOT}bin/ops-statusline-suggest` | Registry-driven config generator |diff --git a/claude-ops/skills/ops/SKILL.md b/claude-ops/skills/ops/SKILL.mdindex 4c3cb643..dd7dc959 100644--- a/claude-ops/skills/ops/SKILL.md+++ b/claude-ops/skills/ops/SKILL.md@@ -54,6 +54,7 @@ Route `$ARGUMENTS` to the correct ops skill:| orchestrate, subagents, agents, dispatch, run | `/ops:ops-orchestrate $ARGUMENTS` || secret-sync, secrets, doppler-sync, drift | `/ops:ops-secret-sync $ARGUMENTS` || home, homey, lights, flow, scene, energy, climate, presence, alarm, smart-home, iot, thermostat, dim, door, lock | `/ops:ops-home $ARGUMENTS` |+| statusline, status-line, cockpit | `/ops:statusline $ARGUMENTS` |If `$ARGUMENTS` is empty, launch the interactive dashboard: invoke `/ops:ops-dash` directly.diff --git a/claude-ops/skills/setup/SKILL.md b/claude-ops/skills/setup/SKILL.mdindex ee521f3c..f08d95b1 100644--- a/claude-ops/skills/setup/SKILL.md+++ b/claude-ops/skills/setup/SKILL.md@@ -223,7 +223,7 @@ How would you like to run setup?If the user selects "Set up everything", select ALL sections across all batches and run them in order (Step 2 → 2b → 2c → 3 → 4 → 5 → 5b → 6 → 6.5 → 7), skipping any already fully configured. Within each step, use the "Configure all" fast-path where available.-If the user selects "Re-run a specific section", use sequential `AskUserQuestion` calls (paginated 4 options per page per Rule 1) to let the user pick from the section names (cli, daemon, channels, mcp, registry, prefs, deploy-fix, env, ecom, mktg, voice, revenue, network), then jump directly to that step. The `deploy-fix` section routes to Step 6.5; `network` routes to Step 3q-network.+If the user selects "Re-run a specific section", use sequential `AskUserQuestion` calls (paginated 4 options per page per Rule 1) to let the user pick from the section names (cli, daemon, statusline, channels, mcp, registry, prefs, deploy-fix, env, ecom, mktg, voice, revenue, network), then jump directly to that step. The `deploy-fix` section routes to Step 6.5; `network` routes to Step 3q-network.If the user selects "Pick sections", proceed with the batched selection below.@@ -709,6 +709,174 @@ Print:Manage anytime: /ops:recap status | tail | configure | restart```+Continue to Step 2e.++---++## Step 2e — Statusline Cockpit (if selected)++Configures the Claude Code `statusLine` setting — a 3-line terminal cockpit showing context-window health, quota gauges, git branch, fleet state, sys metrics, and per-project ops badges.++**Rule Zero**: every Bash call in this step MUST use `run_in_background: true`.++### Step 2e.1 — Resolve paths (run_in_background: true)++```bash+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1)}"+RENDERER_SRC="${PLUGIN_ROOT}templates/statusline/statusline-command.sh"+RENDERER_DST="$HOME/.claude/statusline-command.sh"+SETTINGS_FILE="$HOME/.claude/settings.json"+CFG_DST="$HOME/.claude/statusline.config.json"+SUGGEST_BIN="${PLUGIN_ROOT}bin/ops-statusline-suggest"+THEMES_FILE="${PLUGIN_ROOT}templates/statusline/themes.json"+```++If `RENDERER_SRC` does not exist, print:+```+○ Statusline template not found at expected plugin path. Skipping statusline step.+ (Re-run /ops:setup after updating the plugin: ops-statusline-suggest should be at+ ${PLUGIN_ROOT}bin/ops-statusline-suggest)+```+Then skip the rest of this step and continue to Step 3.++### Step 2e.2 — Ask preset (max 4 options per Rule 1)++Use `AskUserQuestion`:++```+Configure the Claude Code cockpit statusline?+ [Yes — cockpit (full color, gauges, per-project badges)]+ [Yes — minimal (essentials, low noise)]+ [Yes — full (all metrics, widest gauges)]+ [Skip — configure later with /ops:statusline config]+```++On Skip: write `statusline.enabled = false` to `$PREFS_PATH` and continue to Step 3.++Set `CHOSEN_PRESET` from the user's choice (`cockpit`, `minimal`, or `full`).++### Step 2e.3 — Ask theme (max 4 options per Rule 1)++Use `AskUserQuestion`:++```+Which color theme?+ [cockpit — rich color, graded gauges (Default)]+ [minimal — two shades, no color grading]+ [nord — cool blues and greens]+ [mono — bold only, no color]+```++Set `CHOSEN_THEME`.++### Step 2e.4 — Run registry auto-suggest (run_in_background: true)++```bash+SUGGESTED=$("$SUGGEST_BIN" --preset "$CHOSEN_PRESET" --theme "$CHOSEN_THEME" 2>/tmp/ops-statusline-suggest.log)+PROJ_COUNT=$(printf '%s' "$SUGGESTED" | jq -r '._detected.projects_found // 0' 2>/dev/null || echo 0)+```++Print detection summary: `Detected $PROJ_COUNT projects from registry.`++### Step 2e.5 — Install renderer (run_in_background: true)++```bash+cp "$RENDERER_SRC" "$RENDERER_DST"+chmod +x "$RENDERER_DST"+```++Validate: `[ -x "$RENDERER_DST" ] && echo "✓ Renderer installed at $RENDERER_DST"`++### Step 2e.6 — Write config (run_in_background: true)++```bash+TMP=$(mktemp)+printf '%s\n' "$SUGGESTED" | jq 'del(._comment, ._detected)+ | . + {"_comment": "Configured by /ops:setup on '"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'."}' > "$TMP"+mv "$TMP" "$CFG_DST"+jq . "$CFG_DST" >/dev/null 2>&1 && echo "✓ Config written" || echo "✗ Config JSON invalid"+```++### Step 2e.7 — Merge settings.json statusLine (run_in_background: true)++**IMPORTANT**: use `jq` to *merge* — never clobber the entire settings.json.++```bash+STATUSLINE_CMD_STR="\$HOME/.claude/statusline-command.sh"++if [ ! -f "$SETTINGS_FILE" ]; then+ # H5: write to tempfile then atomic mv — Claude Code reads settings.json every frame+ TMP=$(mktemp)+ jq -n --arg cmd "$STATUSLINE_CMD_STR" '{"statusLine": {"command": $cmd}}' > "$TMP" \+ && mv "$TMP" "$SETTINGS_FILE"+else+ EXISTING=$(jq -r '.statusLine.command // empty' "$SETTINGS_FILE" 2>/dev/null)+ if [ -n "$EXISTING" ]; then+ # statusLine already set — ask whether to overwrite+ echo "existing_statusline=$EXISTING"+ else+ # H5: backup existing file, then atomic write via tmp+ cp "$SETTINGS_FILE" "${SETTINGS_FILE}.bak" 2>/dev/null || true+ TMP=$(mktemp)+ jq --arg cmd "$STATUSLINE_CMD_STR" '.statusLine = {"command": $cmd}' "$SETTINGS_FILE" > "$TMP" \+ && mv "$TMP" "$SETTINGS_FILE"+ echo "✓ statusLine wired in ~/.claude/settings.json"+ fi+fi+```++If `existing_statusline` is non-empty, use `AskUserQuestion`:+```+~/.claude/settings.json already has a statusLine.command. Overwrite?+ [Yes — replace with the cockpit renderer]+ [No — keep existing and skip]+```+On Yes: run the merge above with the new command.+On No: skip the merge and note `statusline.settings_wired = false`.++### Step 2e.8 — Quick preview (run_in_background: true)++```bash+PAYLOAD='{"model":{"display_name":"Claude Sonnet"},"rate_limits":{"five_hour":{"used_percentage":30}},"context_window":{"used_percentage":20},"cost":{"total_cost_usd":0.05}}'+printf '%s' "$PAYLOAD" | COLUMNS=100 "$RENDERER_DST" 2>/dev/null+```++Print between ruler lines so the user sees the cockpit preview inline.++If the render fails (exit non-zero or empty output), print a non-fatal note:+```+○ Preview failed — renderer may need Claude Code restart to load new settings.json.+ Manage with: /ops:statusline preview | doctor | config+```++### Step 2e.9 — Persist preferences (run_in_background: true)++```bash+jq -n \+ --arg preset "$CHOSEN_PRESET" \+ --arg theme "$CHOSEN_THEME" \+ --argjson proj_count "$PROJ_COUNT" \+ '{+ "statusline": {+ "enabled": true,+ "preset": $preset,+ "theme": $theme,+ "projects_detected": $proj_count,+ "renderer": "~/.claude/statusline-command.sh",+ "config": "~/.claude/statusline.config.json"+ }+ }' | jq -s '.[0] * .[1]' "$PREFS_PATH" - > /tmp/prefs-sl-merge.json \+ && mv /tmp/prefs-sl-merge.json "$PREFS_PATH" \+ && echo "✓ Preferences saved"+```++Print summary:+```+✓ Statusline cockpit configured (preset=$CHOSEN_PRESET, theme=$CHOSEN_THEME, projects=$PROJ_COUNT).+ Restart Claude Code to activate the statusLine in your terminal.+ Manage anytime: /ops:statusline preview | config | theme | doctor | reset+```+Continue to Step 3.---diff --git a/claude-ops/templates/statusline/README.md b/claude-ops/templates/statusline/README.mdnew file mode 100644index 00000000..cacf19c6--- /dev/null+++ b/claude-ops/templates/statusline/README.md@@ -0,0 +1,182 @@+# statusline — Claude Code cockpit statusline++A config-driven, 3-line terminal statusline for Claude Code that shows context-window+health, quota burn rate, account rotation state, and per-project ops metrics — all+rendered in under 50ms with no blocking external calls.++## Install++Copy the script and wire it into `~/.claude/settings.json`:++```json+{+ "statusLine": {+ "command": "$HOME/.claude/statusline-command.sh"+ }+}+```++Then copy `statusline-command.sh` to `~/.claude/statusline-command.sh` and make it+executable:++```sh+cp templates/statusline/statusline-command.sh ~/.claude/statusline-command.sh+chmod +x ~/.claude/statusline-command.sh+```++Optionally copy the default config and customise it:++```sh+cp templates/statusline/statusline.config.default.json ~/.claude/statusline.config.json+```++## Config file++Resolved in this order (first match wins):++1. `$CLAUDE_STATUSLINE_CONFIG`+2. `~/.claude/statusline.config.json`+3. Built-in defaults (zero-config works out of the box)++### Schema++```jsonc+{+ // Named theme from themes.json. Built-in: "cockpit" | "minimal" | "mono" | "nord"+ "theme": "cockpit",++ // Gauge bar widths (number of fill characters)+ "gauge_width": {+ "ctx": 10, // context-window gauge+ "quota": 8 // 5h / 7d quota gauges+ },++ // How often the carousel slot and line-3 project cycle (seconds, epoch-based)+ "carousel_interval_sec": 15,++ // Widget visibility toggles — omit a key to keep the default (all on)+ "widgets": {+ "line1": ["ctx_gauge", "quota_gauge", "pace_badge", "cache_badge", "plan_badge", "account_arrow"],+ "line2": ["location", "model", "git_branch", "tasks", "fleet", "sys_metrics", "carousel"],+ "line3": ["project_rotate"]+ },++ // Fleet badges (bg agents, rotation pool, SDK fallback, cache TTL countdown)+ "fleet": {+ "show_bg_agents": true,+ "show_rotation": true,+ "show_sdk_fallback": true,+ "show_cache_ttl": true+ },++ // System metrics on line 2+ "sys_metrics": {+ "show_cpu": true,+ "show_ram": true,+ "show_disk": true,+ "show_load_warning": true,+ "show_disk_warning": true,+ // Peer metrics sync (multi-machine: Mac + EC2)+ "publish_peer": true, // write ~/.claude/.sysinfo/<hostname>.json on each render (throttled to 10s)+ "show_peer": true // read sibling *.json files and show compact peer badge on line 2+ },++ // What to include in the rotating carousel slot on line 2+ "carousel_pool": ["cost", "lines", "global_ops"],++ // Per-project badge groups for line 3 (empty = line 3 falls back to carousel)+ "projects": [+ {+ "key": "myapp", // internal identifier+ "label": "MyApp", // display label+ "match": "myapp", // substring matched against cwd (lowercase)+ "badges": ["ecs", "orders"] // which metric badge types to show+ // Badge data is read from:+ // ~/.claude/plugins/data/ops-ops-marketplace/cache/project-<key>.json+ // Write that file from your own daemon or /ops:ops-go precompute step.+ }+ ]+}+```++### Project badge file format++The renderer reads `$ops_dir/project-<key>.json` (precomputed by your ops daemon):++```json+{+ "label": "MyApp",+ "badges": [+ { "icon": "◉", "value": "3/3", "color": "ok" },+ { "icon": "🛒", "value": "12·€340", "color": "ok" }+ ]+}+```++`color` is one of `"ok"`, `"warn"`, `"danger"`, `"dim"`.++## Themes++Themes live in `themes.json` alongside this script. Available built-in themes:++| Theme | Description |+|-----------|--------------------------------------------------|+| `cockpit` | Default — rich color, graded gauges |+| `minimal` | Two shades only — no color grading |+| `mono` | Monochrome — bold for emphasis, no color at all |+| `nord` | Nord palette — cool blues and muted tones |++To add a custom theme, add a key to `themes.json` with the same semantic role fields+and set `"theme": "<your-key>"` in your config.++## Line layout++```+Line 1 (instruments):+ ctx ████████░░ 82% │ 5h ██████░░ 74% │ 7d ████░░░░ 45% │ ▸ 0.3%/m │ ✦2m │ ● Max │ acct→next++Line 2 (session + system + fleet + carousel):+ ⚑ FRA │ Opus 4.8 │ ⎇feature/x │ ⟳2(1/3) │ 🤖 0 │ 🔄acct⚡1 │ cpu12% ram4G df80G │ <carousel>++Line 3 (per-project, rotates every 15s):+ MyApp ◉ 3/3 │ 🛒 12·€340+```++## Width handling++Every line is packed greedily left-to-right with ` │ ` dividers. Segments that+don't fit are silently dropped — nothing is ever truncated mid-segment. On narrow+terminals (`$COLUMNS < 80`) line 2 collapses to a single rotating metric.++## Peer system-metrics sync++When `sys_metrics.publish_peer` is `true` (default), each render writes this+machine's CPU, RAM, load, and disk metrics to:++```+~/.claude/.sysinfo/<short-hostname>.json+```++The write is async and throttled — the file is only rewritten when it is older+than 10 seconds, so the render path is never blocked.++When `sys_metrics.show_peer` is `true` (default), the renderer reads any+**other** `*.json` files in that directory (i.e. the peer machine) and shows a+compact badge on line 2:++```+ams cpu8% ram12G df88G # fresh — color-graded (red if load>8 or ram<2G)+ams stale # greyed when peer file is older than 5 minutes+```++**Cross-machine transport** reuses your existing `~/.claude/` rsync / Tailscale+sync (a launchd/systemd timer or any folder-sync you already run). No new transport is built — the+sync daemon copies `~/.claude/.sysinfo/` along with the rest of `~/.claude/`.+Each machine publishes its own file; the peer's file arrives via rsync.++## Performance++All external calls (`claude auth status`, `git`, `claude agents`) are async:+the render reads a cache file written by a locked background job on the previous+frame. Warm render target is under 50ms. No synchronous network or subprocess+calls on the hot path.diff --git a/claude-ops/templates/statusline/statusline-command.sh b/claude-ops/templates/statusline/statusline-command.shnew file mode 100644index 00000000..b81df8ef--- /dev/null+++ b/claude-ops/templates/statusline/statusline-command.sh@@ -0,0 +1,968 @@+#!/bin/sh+# statusline-command.sh — config-driven 3-line Claude Code cockpit statusline.+# Wire into ~/.claude/settings.json: { "statusLine": { "command": "/path/to/this" } }+#+# Config file resolution (first wins):+# $CLAUDE_STATUSLINE_CONFIG → ~/.claude/statusline.config.json → built-in defaults+#+# Hard constraints:+# - Every external call is async — render reads caches, never blocks.+# - No line exceeds $COLUMNS visible characters (ANSI-stripped + emoji+1).+# - POSIX sh, BMP-safe glyphs (works over mosh/tmux/SSH).+# - Target <50ms warm render.+# - No user-specific data; all project config comes from statusline.config.json.++LC_ALL=C; export LC_ALL+ESC=$(printf '\033')+input=$(cat)+now=$(date +%s)+uid=$(id -u)+# Cache base — overridable so tests (and multi-tenant setups) can isolate caches+# instead of colliding on the shared uid-keyed /tmp paths. Defaults to /tmp.+CACHE_DIR="${CLAUDE_STATUSLINE_CACHE_DIR:-/tmp}"+[ -d "$CACHE_DIR" ] || CACHE_DIR=/tmp++# ── Portable mtime ────────────────────────────────────────────────────────────+mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; }++# ── async_cache <cache_file> <ttl_sec> <command…> ────────────────────────────+# Never blocks the render. Returns cached content; refreshes in a locked+# background job when stale. Core cockpit principle: read instruments, never+# go fetch fuel mid-frame.+async_cache() {+ _cf=$1; _ttl=$2; shift 2+ if [ ! -s "$_cf" ] || [ $(( now - $(mtime "$_cf") )) -ge "$_ttl" ]; then+ _lk="${_cf}.lock"+ [ -d "$_lk" ] && [ $(( now - $(mtime "$_lk") )) -gt 30 ] && rmdir "$_lk" 2>/dev/null+ if mkdir "$_lk" 2>/dev/null; then+ ( "$@" > "${_cf}.tmp" 2>/dev/null && [ -s "${_cf}.tmp" ] && mv "${_cf}.tmp" "$_cf"+ rmdir "$_lk" 2>/dev/null ) >/dev/null 2>&1 &+ fi+ fi+ [ -s "$_cf" ] && cat "$_cf"+}++# ── gauge <pct> <width> → sets GAUGE_BAR and GAUGE_C ────────────────────────+# Color-graded fill bar. Green (calm) → yellow → orange → bold-red at >=90%.+# GAUGE_C is the last-used color code (for the trailing pct label).+gauge() {+ _p=$1; _w=$2+ case "$_p" in ''|*[!0-9]*) _p=0;; esac+ _f=$(( _p * _w / 100 )); [ "$_f" -gt "$_w" ] && _f=$_w; [ "$_f" -lt 0 ] && _f=0+ _e=$(( _w - _f ))+ if [ "$_p" -ge 90 ]; then GAUGE_C="${T_gauge_crit:-1;31}"+ elif [ "$_p" -ge 75 ]; then GAUGE_C="${T_gauge_hot:-38;5;208}"+ elif [ "$_p" -ge 50 ]; then GAUGE_C="${T_gauge_warn:-33}"+ else GAUGE_C="${T_gauge_ok:-32}"; fi+ _b="${ESC}[${GAUGE_C}m"+ _i=0; while [ "$_i" -lt "$_f" ]; do _b="${_b}█"; _i=$(( _i + 1 )); done+ _b="${_b}${ESC}[${T_gauge_empty:-38;5;236}m"+ _i=0; while [ "$_i" -lt "$_e" ]; do _b="${_b}░"; _i=$(( _i + 1 )); done+ GAUGE_BAR="${_b}${ESC}[0m"+}++# ── visible_width <string> → echoes char count (ANSI-stripped, true display width) ──────+# Uses python3 unicodedata for accurate 2-cell glyph accounting when available.+# Falls back to wc -m + expanded emoji allowlist on plain POSIX environments.+if [ "$(uname -s)" = "Darwin" ]; then _u8lc="en_US.UTF-8"; else _u8lc="C.UTF-8"; fi+vis_width() {+ _s=$(printf '%s' "$1" | sed "s/${ESC}\[[0-9;]*m//g")+ if command -v python3 >/dev/null 2>&1; then+ printf '%s' "$_s" | python3 -c "+import sys, unicodedata+s = sys.stdin.read()+w = 0+for c in s:+ ew = unicodedata.east_asian_width(c)+ if ew in ('W', 'F'):+ w += 2+ elif unicodedata.category(c) == 'Mn':+ pass # combining mark — zero width+ else:+ w += 1+print(w)+" 2>/dev/null || printf '%s' "$_s" | LC_ALL=$_u8lc wc -m | tr -d ' '+ else+ _cw=$(printf '%s' "$_s" | LC_ALL=$_u8lc wc -m | tr -d ' ')+ # Each wide emoji/symbol costs an extra column (they render in 2 cells).+ # Allowlist covers ALL non-ASCII glyphs the renderer can emit:+ _ew=$(printf '%s' "$_s" | LC_ALL=$_u8lc grep -o \+ -e '🤖' -e '📬' -e '🚧' -e '🔥' -e '💾' -e '⚡' -e '📣' \+ -e '🛒' -e '📈' -e '🥊' -e '🎧' -e '❄' -e '✦' -e '🔄' -e '🔴' \+ -e '⚑' -e '⌂' -e '▥' -e '▲' -e '▸' -e '▪' -e '⟳' -e '✓' \+ -e '⎇' -e '●' -e '░' -e '█' -e '↻' -e '→' \+ 2>/dev/null | wc -l | tr -d ' ')+ echo $(( _cw + _ew ))+ fi+}++# ── Config load — single jq call, fall back to built-in defaults ──────────────+_cfg_file=""+if [ -n "$CLAUDE_STATUSLINE_CONFIG" ] && [ -f "$CLAUDE_STATUSLINE_CONFIG" ]; then+ _cfg_file="$CLAUDE_STATUSLINE_CONFIG"+elif [ -f "$HOME/.claude/statusline.config.json" ]; then+ _cfg_file="$HOME/.claude/statusline.config.json"+fi++# Built-in defaults (used when cfg file absent or key missing):+CFG_theme="cockpit"+CFG_ctx_w=10+CFG_quota_w=8+CFG_carousel_sec=15+CFG_fleet_bg=1+CFG_fleet_rot=1+CFG_fleet_sdk=1+CFG_fleet_cache=1+CFG_sys_cpu=1+CFG_sys_ram=1+CFG_sys_disk=1+CFG_sys_publish_peer=1+CFG_sys_show_peer=1+CFG_carousel_pool="cost lines global_ops"+CFG_widgets_line1="ctx_gauge quota_gauge pace_badge cache_badge plan_badge account_arrow"+CFG_widgets_line2="location model git_branch tasks fleet sys_metrics carousel"+CFG_widgets_line3="project_rotate"++if [ -n "$_cfg_file" ]; then+ eval $(jq -r '+ @sh "CFG_theme=\(.theme // "cockpit")",+ @sh "CFG_ctx_w=\(.gauge_width.ctx // 10)",+ @sh "CFG_quota_w=\(.gauge_width.quota // 8)",+ @sh "CFG_carousel_sec=\(.carousel_interval_sec // 15)",+ @sh "CFG_fleet_bg=\(if .fleet.show_bg_agents == false then 0 else 1 end)",+ @sh "CFG_fleet_rot=\(if .fleet.show_rotation == false then 0 else 1 end)",+ @sh "CFG_fleet_sdk=\(if .fleet.show_sdk_fallback== false then 0 else 1 end)",+ @sh "CFG_fleet_cache=\(if .fleet.show_cache_ttl == false then 0 else 1 end)",+ @sh "CFG_sys_cpu=\(if .sys_metrics.show_cpu == false then 0 else 1 end)",+ @sh "CFG_sys_ram=\(if .sys_metrics.show_ram == false then 0 else 1 end)",+ @sh "CFG_sys_disk=\(if .sys_metrics.show_disk == false then 0 else 1 end)",+ @sh "CFG_sys_publish_peer=\(if .sys_metrics.publish_peer == false then 0 else 1 end)",+ @sh "CFG_sys_show_peer=\(if .sys_metrics.show_peer == false then 0 else 1 end)"+ ' "$_cfg_file" 2>/dev/null) 2>/dev/null || true+ CFG_carousel_pool=$(jq -r '(.carousel_pool // ["cost","lines","global_ops"]) | join(" ")' "$_cfg_file" 2>/dev/null) || true+ CFG_widgets_line1=$(jq -r '(.widgets.line1 // ["ctx_gauge","quota_gauge","pace_badge","cache_badge","plan_badge","account_arrow"]) | join(" ")' "$_cfg_file" 2>/dev/null) || true+ CFG_widgets_line2=$(jq -r '(.widgets.line2 // ["location","model","git_branch","tasks","fleet","sys_metrics","carousel"]) | join(" ")' "$_cfg_file" 2>/dev/null) || true+ CFG_widgets_line3=$(jq -r '(.widgets.line3 // ["project_rotate"]) | join(" ")' "$_cfg_file" 2>/dev/null) || true+fi++# ── Theme colors — one jq from themes.json bundled alongside this script ─────+_themes_file="$(dirname "$0")/themes.json"+# Theme-adaptive contrast contract: text/labels use terminal DEFAULT fg (39);+# dim + gauge-empty use 90 (bright-black, works on light AND dark); accents/gauges+# use NAMED ANSI (theme-mapped); badges use REVERSE video (7) for guaranteed contrast.+# Do NOT hardcode 38;5;N for text/label/empty-track roles (breaks on light terminals).+T_ok="32"; T_warn="33"; T_danger="91"; T_dim="90"+T_acc="36"; T_acc2="35"+T_gauge_ok="32"; T_gauge_warn="33"; T_gauge_hot="38;5;208"; T_gauge_crit="91"+T_gauge_empty="90"+T_loc_remote="1;7;31"; T_loc_home="1;7"++if [ -f "$_themes_file" ]; then+ eval $(jq -r --arg t "$CFG_theme" '+ .[$t] // .cockpit |+ @sh "T_ok=\(.ok // "32")",+ @sh "T_warn=\(.warn // "33")",+ @sh "T_danger=\(.danger // "91")",+ @sh "T_dim=\(.dim // "90")",+ @sh "T_acc=\(.accent // "36")",+ @sh "T_acc2=\(.accent2 // "35")",+ @sh "T_gauge_ok=\(.gauge_ok // "32")",+ @sh "T_gauge_warn=\(.gauge_warn // "33")",+ @sh "T_gauge_hot=\(.gauge_hot // "38;5;208")",+ @sh "T_gauge_crit=\(.gauge_crit // "91")",+ @sh "T_gauge_empty=\(.gauge_empty // "90")",+ @sh "T_loc_remote=\(.loc_remote // "1;7;31")",+ @sh "T_loc_home=\(.loc_home // "1;7")"+ ' "$_themes_file" 2>/dev/null) 2>/dev/null || true+fi++# Convert raw codes to full sequences for convenience:+T_ok="${ESC}[${T_ok}m"; T_warn="${ESC}[${T_warn}m"; T_danger="${ESC}[${T_danger}m"+T_dim="${ESC}[${T_dim}m"; T_acc="${ESC}[${T_acc}m"; T_acc2="${ESC}[${T_acc2}m"+R="${ESC}[0m"++# ── Project list from config ──────────────────────────────────────────────────+# Each project: { "key": "myapp", "label": "MyApp", "match": "myapp", "badges": ["ecs","orders"] }+# Built-in default: empty (no per-project badges).+CFG_proj_slugs=""+CFG_proj_count=0+if [ -n "$_cfg_file" ]; then+ CFG_proj_count=$(jq -r '(.projects // []) | length' "$_cfg_file" 2>/dev/null || echo 0)+ if [ "${CFG_proj_count:-0}" -gt 0 ] 2>/dev/null; then+ CFG_proj_slugs=$(jq -r '(.projects // []) | map(.key) | join(" ")' "$_cfg_file" 2>/dev/null)+ fi+fi++# ── Column width ──────────────────────────────────────────────────────────────+cols=${COLUMNS:-0}+[ "$cols" -eq 0 ] && cols=$(tput cols 2>/dev/null || echo 120)++# ── Parse input JSON ─────────────────────────────────────────────────────────+eval $(printf '%s' "$input" | jq -r '+ @sh "cwd=\(.workspace.current_dir // .cwd // "")",+ @sh "model=\(.model.display_name // "")",+ @sh "rl_5h=\(.rate_limits.five_hour.used_percentage // "")",+ @sh "rl_7d=\(.rate_limits.seven_day.used_percentage // "")",+ @sh "rl_5h_reset=\(.rate_limits.five_hour.resets_at // 0)",+ @sh "rl_7d_reset=\(.rate_limits.seven_day.resets_at // 0)",+ @sh "ctx_used=\(.context_window.used_percentage // "")",+ @sh "cost=\(.cost.total_cost_usd // "")",+ @sh "lines_add=\(.cost.total_lines_added // 0)",+ @sh "lines_rm=\(.cost.total_lines_removed // 0)",+ @sh "session_id=\(.session_id // "")",+ @sh "transcript_path=\(.transcript_path // "")"+' 2>/dev/null)++# ── Location badge ────────────────────────────────────────────────────────────+# Linux/remote: derive from hostname. Mac: cache in ~/.claude/.statusline-location.+# Linux never trusts the Mac's cached value (prevents masquerading).+loc_file="$HOME/.claude/.statusline-location"+host=$(hostname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')+if [ "$(uname -s)" != "Darwin" ]; then+ case "$host" in+ *fra*) loc="⚑ FRA" ;;+ *) loc="⚑ ${host}" ;;+ esac+ printf '%s' "$loc" > "$loc_file" 2>/dev/null+elif [ -s "$loc_file" ]; then+ loc=$(cat "$loc_file")+else+ loc="⌂ $(hostname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')"+ printf '%s' "$loc" > "$loc_file" 2>/dev/null+fi+case "$loc" in+ "⚑ "*) loc_badge="${ESC}[${T_loc_remote}m ${loc} ${R}" ;;+ "⌂ "*) loc_badge="${ESC}[${T_loc_home}m ${loc} ${R}" ;;+ *) loc_badge="${T_acc}${loc}${R}" ;;+esac++# ── Auth cache (async, 45s TTL) ───────────────────────────────────────────────+auth_cache="${CACHE_DIR}/claude-authjson-${session_id}"+auth_age=$(( now - $(mtime "$auth_cache") ))+if [ ! -s "$auth_cache" ] || [ "$auth_age" -ge 45 ]; then+ _lk="${auth_cache}.lock"+ [ -d "$_lk" ] && [ $(( now - $(mtime "$_lk") )) -gt 30 ] && rmdir "$_lk" 2>/dev/null+ if mkdir "$_lk" 2>/dev/null; then+ ( claude auth status > "${auth_cache}.tmp" 2>/dev/null \+ && [ -s "${auth_cache}.tmp" ] && mv "${auth_cache}.tmp" "$auth_cache"+ rmdir "$_lk" 2>/dev/null ) >/dev/null 2>&1 &+ fi+fi+account_email=""; _sub=""; _method=""+[ -s "$auth_cache" ] && eval $(jq -r '+ @sh "account_email=\(.email // "")",+ @sh "_sub=\(.subscriptionType // "")",+ @sh "_method=\(.authMethod // "")"+' "$auth_cache" 2>/dev/null)+# Sanitize email for use in filenames: strip / and " to prevent path traversal / injection+_email_safe=$(printf '%s' "$account_email" | tr -d '/"')++# Billing mode+billing_cache="${CACHE_DIR}/claude-billing-${session_id}"+if [ "${CLAUDE_CODE_USE_BEDROCK:-}" = "1" ]; then+ sub_type="bedrock"+elif [ -n "$_sub" ] && [ "$_sub" != "null" ]; then+ sub_type="$_sub"+elif [ "$_method" = "claude.ai" ]; then+ sub_type="max"+elif [ -s "$billing_cache" ]; then+ sub_type=$(cat "$billing_cache")+else+ sub_type="api"+fi+[ "$sub_type" != "api" ] && printf '%s' "$sub_type" > "$billing_cache" 2>/dev/null+case "$sub_type" in max|pro|team|enterprise) is_sub=1 ;; *) is_sub="" ;; esac++# ── Account alias helper ──────────────────────────────────────────────────────+# Maps email → short label. Falls back to domain-sans-TLD for unknown addresses.+# Customize by adding entries in your config or by overriding this function in a+# wrapper script — the shipped version contains no personal emails.+acct_alias() {+ case "$1" in+ *@*) _d=${1#*@}; printf '%s' "${_d%%.*}" ;;+ *) printf '%s' "$1" ;;+ esac+}++# ── Export rate limits for rotation daemon ────────────────────────────────────+rot_dir="$HOME/.claude/scripts/account-rotation"+if { [ -n "$rl_5h" ] || [ -n "$rl_7d" ]; } && [ -d "$rot_dir" ]; then+ jq -n \+ --argjson fh "${rl_5h:-0}" --argjson fr "${rl_5h_reset:-0}" \+ --argjson sh "${rl_7d:-0}" --argjson sr "${rl_7d_reset:-0}" \+ --arg ae "${account_email}" --argjson ts "$now" \+ '{"five_hour":{"pct":$fh,"reset":$fr},"seven_day":{"pct":$sh,"reset":$sr},"account_email":$ae,"ts":$ts}' \+ > "$rot_dir/.rate-limits.json" 2>/dev/null+fi++# Per-account session count (multi-session badge)+sessions_n=0+if [ -n "$account_email" ]; then+ pid_file="${CACHE_DIR}/claude-pids-${_email_safe}"+ new_content="$PPID"+ if [ -f "$pid_file" ]; then+ while IFS= read -r p; do+ [ -z "$p" ] && continue; [ "$p" = "$PPID" ] && continue+ kill -0 "$p" 2>/dev/null && new_content="${new_content}+${p}"+ done < "$pid_file"+ fi+ printf '%s\n' "$new_content" > "$pid_file" 2>/dev/null+ sessions_n=$(printf '%s\n' "$new_content" | grep -c .)+fi++# ── Git branch (async, 10s TTL) ───────────────────────────────────────────────+git_part=""+if [ -n "$cwd" ] && [ -d "$cwd" ]; then+ git_cache="${CACHE_DIR}/claude-gitbranch-${uid}-$(printf '%s' "$cwd" | cksum | cut -d' ' -f1)"+ branch=$(async_cache "$git_cache" 10 git -C "$cwd" --no-optional-locks rev-parse --abbrev-ref HEAD)+ [ -n "$branch" ] && git_part="${T_acc}⎇${branch}${R}"+fi++# ── Model badge ───────────────────────────────────────────────────────────────+model_part=""+# Shorten verbose display names: "Claude Opus 4.8 (1M context)" → "Opus 4.8"+model=$(printf '%s' "$model" | sed -E 's/^Claude //; s/ *\([^)]*\)//g; s/ +$//')+[ -n "$model" ] && model_part="${T_warn}${model}${R}"++# ── Plan badge ────────────────────────────────────────────────────────────────+case "$sub_type" in+ max) plan_badge="${T_acc2}●${R} ${ESC}[1;${T_acc2#*[}Max${R}" ;;+ pro) plan_badge="${T_acc}●${R} ${ESC}[1;${T_acc#*[}Pro${R}" ;;+ team) plan_badge="${T_acc2}●${R} ${ESC}[1;${T_acc2#*[}Team${R}" ;;+ enterprise) plan_badge="${T_acc2}●${R} ${ESC}[1;${T_acc2#*[}Ent${R}" ;;+ bedrock) plan_badge="${T_warn}●${R} ${ESC}[1;${T_warn#*[}Bedrock${R}" ;;+ *) plan_badge="${T_warn}●${R} ${ESC}[1;${T_warn#*[}API${R}" ;;+esac++# Simplified inline variant (no bold prefix dot):+case "$sub_type" in+ max) plan_short="${ESC}[35mMax${R}" ;;+ pro) plan_short="${T_acc}Pro${R}" ;;+ team) plan_short="${ESC}[35mTeam${R}" ;;+ enterprise) plan_short="${ESC}[35mEnt${R}" ;;+ bedrock) plan_short="${T_warn}BDR${R}" ;;+ *) plan_short="${T_warn}API${R}" ;;+esac++# ── Tasks badge ───────────────────────────────────────────────────────────────+tasks_part=""+if [ -n "$session_id" ] && [ -d "$HOME/.claude/tasks/$session_id" ]; then+ set -- "$HOME/.claude/tasks/$session_id"/[!.]*.json+ if [ -e "$1" ]; then+ total=$#+ running=$(grep -l '"status":"in_progress"' "$@" 2>/dev/null | grep -c .)+ done_count=$(grep -l '"status":"completed"' "$@" 2>/dev/null | grep -c .)+ if [ "$running" -gt 0 ]; then+ tasks_part="${T_ok}⟳${running}${R}${T_dim}(${done_count}/${total})${R}"+ else+ tasks_part="${T_dim}✓${done_count}/${total}${R}"+ fi+ fi+fi++# ── Active subagents count ────────────────────────────────────────────────────+agents_n=0+if [ -n "$session_id" ]; then+ agents_n=$( {+ for taskdir in ${CACHE_DIR}/claude-${uid}/*/"$session_id"/tasks; do+ [ -d "$taskdir" ] || continue+ find "$taskdir" -maxdepth 1 -name 'a*.output' -mmin -5 2>/dev/null \+ | sed 's|.*/||; s|\.output$||'+ done+ for subdir in "$HOME"/.claude/projects/*/"$session_id"/subagents; do+ [ -d "$subdir" ] || continue+ find "$subdir" -maxdepth 1 -name 'agent-*.jsonl' -mmin -5 2>/dev/null \+ | sed 's|.*/agent-||; s|\.jsonl$||'+ done+ } | sort -u | grep -c . )+fi+if [ "$agents_n" -gt 0 ]; then+ agents_part="${T_acc}🤖 ${agents_n}${R}"+else+ agents_part="${T_dim}🤖 0${R}"+fi++# ── Rate-limit badges ─────────────────────────────────────────────────────────+rl_5h_int=0; rl_7d_int=0+[ -n "$rl_5h" ] && rl_5h_int=$(printf '%.0f' "${rl_5h}" 2>/dev/null || echo 0)+[ -n "$rl_7d" ] && rl_7d_int=$(printf '%.0f' "${rl_7d}" 2>/dev/null || echo 0)+_rl_pick=$rl_5h_int; [ "$rl_7d_int" -gt "$_rl_pick" ] && _rl_pick=$rl_7d_int+if [ "$_rl_pick" -ge 90 ]; then rl_col="$T_danger"+elif [ "$_rl_pick" -ge 50 ]; then rl_col="$T_warn"+else rl_col="$T_ok"; fi++rl_part=""; rl_short=""+if [ -n "$rl_5h" ] || [ -n "$rl_7d" ]; then+ # Account prefix+ acct_label=""+ if [ -n "$account_email" ]; then+ a=$(acct_alias "$account_email")+ if [ "$sessions_n" -gt 1 ]; then+ acct_label="${T_dim}${a}${R}${T_acc}×${sessions_n}${R} "+ else+ acct_label="${T_dim}${a}${R} "+ fi+ fi+ # 5h reset countdown+ reset_label=""+ case "$rl_5h_reset" in+ ''|*[!0-9]*) ;;+ *)+ if [ "$rl_5h_reset" -gt "$now" ]; then+ rsec=$(( rl_5h_reset - now ))+ rh=$(( rsec / 3600 )); rm_=$(( (rsec % 3600) / 60 ))+ if [ "$rh" -gt 0 ]; then reset_label=" ${T_dim}↻${rh}h${rm_}m${R}"+ else reset_label=" ${T_dim}↻${rm_}m${R}"; fi+ fi ;;+ esac+ # Next-rotation target (memoized 30s)+ next_label=""+ next_cache="${CACHE_DIR}/claude-nexttarget-${uid}"+ if [ -s "$next_cache" ] && [ $(( now - $(mtime "$next_cache") )) -lt 30 ]; then+ next_line=$(cat "$next_cache")+ else+ next_line=""+ next_file="$rot_dir/.next-rotation-target.json"+ [ -f "$next_file" ] && next_line=$(jq -r '"\(.email // "") \(.pct // 0 | floor)"' "$next_file" 2>/dev/null)+ _ne=${next_line% *}+ if { [ -z "$_ne" ] || [ "$_ne" = "$account_email" ]; } \+ && [ -f "$rot_dir/config.json" ] && [ -f "$rot_dir/state.json" ]; then+ next_line=$(jq -r --arg cur "$account_email" --slurpfile cfg "$rot_dir/config.json" '+ ($cfg[0].accounts | map(select(.disabled != true) | {(.label // .email): .email}) | add) as $k2e+ | (.accounts // {}) | to_entries+ | map(select($k2e[.key] != null))+ | map({email: $k2e[.key], pct: (.value.lastUtilization.pct // null)})+ | map(select(.pct != null and .email != $cur))+ | sort_by(.pct) | .[0] // empty+ | "\(.email) \(.pct|floor)"' "$rot_dir/state.json" 2>/dev/null)+ fi+ printf '%s' "$next_line" > "$next_cache" 2>/dev/null+ fi+ next_email=${next_line% *}; next_pct=${next_line##* }+ [ -n "$next_email" ] && [ "$next_email" != "$account_email" ] && \+ next_label=" ${T_dim}→$(acct_alias "$next_email") (${next_pct}%)${R}"++ rl_part="${acct_label}${rl_col}⚡ ${rl_5h_int}%${R}${T_dim}/${R}${rl_col}▥ ${rl_7d_int}%${R}${reset_label}${next_label}"+ rl_short="${rl_col}⚡ ${rl_5h_int}%${R}${T_dim}/${R}${rl_col}▥ ${rl_7d_int}%${R}"+fi++# ── Cost / lines badges ───────────────────────────────────────────────────────+cost_part=""+if [ -n "$cost" ]; then+ cost_fmt=$(printf '%.2f' "$cost")+ if [ -n "$is_sub" ]; then+ cost_part="${ESC}[9;90m\$${cost_fmt}${R}"+ elif [ "$sub_type" = "bedrock" ]; then+ cost_part="${T_warn}\$${cost_fmt}${R}"+ else+ cost_part="${T_acc}\$${cost_fmt}${R}"+ fi+fi++lines_part=""+if [ "${lines_add:-0}" -gt 0 ] || [ "${lines_rm:-0}" -gt 0 ]; then+ lines_part="${T_ok}+${lines_add:-0}${R}${T_danger}-${lines_rm:-0}${R}"+fi++# ── Prompt-cache freshness ────────────────────────────────────────────────────+cache_badge=""+if [ -n "$transcript_path" ] && [ -f "$transcript_path" ]; then+ cache_age=$(( now - $(mtime "$transcript_path") ))+ if [ "$cache_age" -ge 300 ]; then+ cache_badge="${T_danger}❄ cold${R}"+ else+ left=$(( 300 - cache_age )); lm=$(( left / 60 )); ls_=$(( left % 60 ))+ if [ "$left" -lt 60 ]; then cache_badge="${T_warn}✦${ls_}s${R}"+ else cache_badge="${T_ok}✦${lm}m${R}"; fi+ fi+fi++# ── Gauge widths — scale down on narrow terminals ────────────────────────────+_ctx_w=$CFG_ctx_w; _quota_w=$CFG_quota_w+if [ "$cols" -lt 100 ]; then _ctx_w=6; _quota_w=5; fi+if [ "$cols" -lt 80 ]; then _ctx_w=4; _quota_w=4; fi++# ── Context-window gauge (L1) ─────────────────────────────────────────────────+ctx_bar=""+if [ -n "$ctx_used" ]; then+ gauge "$ctx_used" "$_ctx_w"+ ctx_bar="${T_dim}ctx${R} ${GAUGE_BAR} ${ESC}[${GAUGE_C}m${ctx_used}%${R}"+fi++# ── Quota gauges 5h + 7d (L1) ────────────────────────────────────────────────+quota_bar=""+if [ -n "$rl_5h" ] || [ -n "$rl_7d" ]; then+ gauge "${rl_5h_int}" "$_quota_w"+ g5="${T_dim}5h${R} ${GAUGE_BAR} ${ESC}[${GAUGE_C}m${rl_5h_int}%${R}"+ gauge "${rl_7d_int}" "$_quota_w"+ g7="${T_dim}7d${R} ${GAUGE_BAR} ${ESC}[${GAUGE_C}m${rl_7d_int}%${R}"+ quota_bar="${g5} ${T_dim}│${R} ${g7}"+fi++# ── Burn-rate speedometer (L1) ────────────────────────────────────────────────+# Samples binding quota %/min; answers: will I hit rotation before 5h resets?+pace_badge=""+if [ -n "$rl_5h" ] || [ -n "$rl_7d" ]; then+ q5=${rl_5h_int}; q7=${rl_7d_int}+ qpick=$q5; [ "$q7" -gt "$qpick" ] && qpick=$q7+ burn_file="${CACHE_DIR}/claude-burn-${_email_safe:-default}"+ rate10=0+ if [ -s "$burn_file" ]; then+ IFS=' ' read -r prev_pct prev_ts < "$burn_file"+ case "${prev_pct}${prev_ts}" in ''|*[!0-9]*) prev_pct=0; prev_ts=0;; esac+ dt=$(( now - prev_ts )); dp=$(( qpick - prev_pct ))+ [ "$dt" -ge 20 ] && [ "$dp" -gt 0 ] && rate10=$(( dp * 600 / dt ))+ fi+ [ ! -s "$burn_file" ] || [ $(( now - $(mtime "$burn_file") )) -ge 20 ] && \+ printf '%s %s' "$qpick" "$now" > "$burn_file" 2>/dev/null+ reset_min=0+ case "$rl_5h_reset" in ''|*[!0-9]*) ;;+ *) [ "$rl_5h_reset" -gt "$now" ] && reset_min=$(( (rl_5h_reset - now) / 60 )) ;; esac+ if [ "$qpick" -ge 90 ]; then+ pace_badge="${T_danger}🔴 rotating${R}"+ elif [ "$rate10" -le 0 ]; then+ pace_badge="${T_dim}▪ idle${R}"+ else+ dist=$(( 90 - qpick )); [ "$dist" -lt 0 ] && dist=0+ eta_rot=$(( dist * 10 / rate10 ))+ r1=$(( rate10 / 10 )); r2=$(( rate10 % 10 ))+ if [ "$reset_min" -gt 0 ] && [ "$eta_rot" -lt "$reset_min" ]; then+ pace_badge="${T_danger}🔥 ${r1}.${r2}%/m rot~${eta_rot}m${R}"+ elif [ "$rate10" -ge 20 ]; then+ pace_badge="${T_warn}▲ ${r1}.${r2}%/m${R}"+ else+ pace_badge="${T_ok}▸ ${r1}.${r2}%/m${R}"+ fi+ fi+fi++# ── Account → next-rotation arrow (L1) ───────────────────────────────────────+account_arrow=""+if [ -n "$account_email" ]; then+ a=$(acct_alias "$account_email")+ if [ -n "${next_email:-}" ] && [ "$next_email" != "$account_email" ]; then+ account_arrow="${T_dim}${a}${R}${T_dim}→$(acct_alias "$next_email")${R}"+ else+ account_arrow="${T_dim}${a}${R}"+ fi+ [ "$sessions_n" -gt 1 ] && account_arrow="${account_arrow}${T_acc}×${sessions_n}${R}"+fi++# ── System metrics (L2) ───────────────────────────────────────────────────────+if [ -r /proc/loadavg ]; then+ load1=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null)+ ncpu=$(nproc 2>/dev/null || echo 4)+ ram_free_g=$(awk '/MemAvailable/{printf "%.0f", $2/1048576}' /proc/meminfo 2>/dev/null)+else+ load1=$(sysctl -n vm.loadavg 2>/dev/null | awk '{print $2}')+ ncpu=$(sysctl -n hw.ncpu 2>/dev/null || echo 8)+ pagesz=$(sysctl -n hw.pagesize 2>/dev/null || echo 16384)+ ram_free_g=$(vm_stat 2>/dev/null | awk -v ps="$pagesz" '/Pages (free|inactive|speculative)/{gsub(/\./,"",$NF); s+=$NF} END{printf "%.0f", s*ps/1073741824}')+fi+df_free_g=$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2{printf "%.0f", $4/1048576}')+disk_pct=$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2 {gsub(/%/,"",$5); print $5}')+case "$disk_pct" in *[!0-9]*|'') disk_pct=0;; esac+load_int=${load1%%.*}; case "$load_int" in *[!0-9]*|'') load_int=0;; esac+cpu_pct=$(awk -v l="${load1:-0}" -v n="${ncpu:-4}" 'BEGIN{printf "%.0f", (l/n)*100}')++sys_part=""+if [ "$CFG_sys_cpu" = "1" ]; then+ ld_col="$T_dim"+ [ "$cpu_pct" -ge 70 ] && ld_col="$T_warn"+ [ "$cpu_pct" -gt 100 ] && ld_col="$T_danger"+ sys_part="${ld_col}cpu${cpu_pct}%${R}"+fi+if [ "$CFG_sys_ram" = "1" ]; then+ ram_col="$T_dim"+ case "$ram_free_g" in ''|*[!0-9]*) ;; *) [ "$ram_free_g" -lt 2 ] && ram_col="$T_danger";; esac+ sys_part="${sys_part:+$sys_part }${ram_col}ram${ram_free_g:-?}G${R}"+fi+if [ "$CFG_sys_disk" = "1" ]; then+ sys_part="${sys_part:+$sys_part }${T_dim}df${df_free_g:-?}G${R}"+fi++# Discrete warning badges (only appear past threshold):+load_warn=""+[ "$load_int" -gt "${ncpu:-4}" ] && load_warn="${T_danger}🔥 load${load1}${R}"+disk_warn=""+[ "$disk_pct" -ge 90 ] && disk_warn="${T_danger}💾 ${disk_pct}%${R}"++# ── Peer system-metrics publish/read ─────────────────────────────────────────+# Publish: write this machine's metrics to ~/.claude/.sysinfo/<short-hostname>.json+# at most once per 10s (async, never blocks render).+# Read: any OTHER *.json in that dir = peer; render compact badge on line 2.+# Cross-machine transport reuses the existing rsync/tailscale sync of ~/.claude/+# — no new transport is built here.+_sysinfo_dir="${HOME}/.claude/.sysinfo"+peer_badge=""+if [ "$CFG_sys_publish_peer" = "1" ]; then+ mkdir -p "$_sysinfo_dir" 2>/dev/null+ _self_file="${_sysinfo_dir}/${host}.json"+ _self_age=$(( now - $(mtime "$_self_file") ))+ if [ "$_self_age" -ge 10 ]; then+ # Non-blocking background write — gather values already computed above.+ ( printf '{"host":"%s","cpu_pct":%s,"ram_free_g":%s,"load1":"%s","df_free_g":%s,"ts":%s}\n' \+ "${host}" "${cpu_pct:-0}" "${ram_free_g:-0}" "${load1:-0}" "${df_free_g:-0}" "${now}" \+ > "${_self_file}.tmp" 2>/dev/null \+ && mv "${_self_file}.tmp" "$_self_file" 2>/dev/null ) >/dev/null 2>&1 &+ fi+fi++if [ "$CFG_sys_show_peer" = "1" ]; then+ _peer_file=""; _peer_host=""+ for _f in "${_sysinfo_dir}"/*.json; do+ [ -e "$_f" ] || continue+ _fn=$(basename "$_f" .json)+ [ "$_fn" = "$host" ] && continue+ # Take the most-recently-modified peer file if multiple exist+ if [ -z "$_peer_file" ] || [ $(mtime "$_f") -gt $(mtime "$_peer_file") ]; then+ _peer_file="$_f"; _peer_host="$_fn"+ fi+ done+ if [ -n "$_peer_file" ]; then+ _peer_age=$(( now - $(mtime "$_peer_file") ))+ _stale_sec=300 # >5min = stale+ if [ "$_peer_age" -ge "$_stale_sec" ]; then+ # Greyed stale badge+ peer_badge="${T_dim}${_peer_host} stale${R}"+ else+ # Parse peer JSON — one jq call+ eval $(jq -r '+ @sh "p_cpu=\(.cpu_pct // 0)",+ @sh "p_ram=\(.ram_free_g // 0)",+ @sh "p_df=\(.df_free_g // 0)",+ @sh "p_load=\(.load1 // "0")"+ ' "$_peer_file" 2>/dev/null) 2>/dev/null || true+ # Color-grade: red if load > ncpu (ncpu unknown for peer, use 8 as safe default)+ _p_cpu_int=${p_cpu%%.*}; case "$_p_cpu_int" in *[!0-9]*|'') _p_cpu_int=0;; esac+ _p_ram_int=${p_ram%%.*}; case "$_p_ram_int" in *[!0-9]*|'') _p_ram_int=0;; esac+ _p_load_int=${p_load%%.*}; case "$_p_load_int" in *[!0-9]*|'') _p_load_int=0;; esac+ _p_cpu_col="$T_dim"+ [ "$_p_cpu_int" -ge 90 ] && _p_cpu_col="$T_danger"+ _p_ram_col="$T_dim"+ [ "$_p_ram_int" -lt 2 ] && _p_ram_col="$T_danger"+ _p_load_col="$T_dim"+ [ "$_p_load_int" -gt 8 ] && _p_load_col="$T_danger"+ peer_badge="${T_dim}${_peer_host}${R} ${_p_cpu_col}cpu${p_cpu}%${R} ${_p_ram_col}ram${p_ram}G${R} ${T_dim}df${p_df}G${R}"+ fi+ fi+fi++# ── Separators ───────────────────────────────────────────────────────────────+# SEP (0x1F unit-separator) divides carousel pool entries.+# SEP_PB (0x1D group-separator) divides per-project badge groups in proj_badges.+# Must be defined BEFORE the slow_cache block — the cache-miss path builds+# proj_badges using SEP_PB, so it must exist at that point (not just on cache-hit).+SEP=$(printf '\037')+SEP_PB=$(printf '\035')++# ── Slow-cache (60s TTL): global ops badges read from daemon output files ─────+slow_cache="${CACHE_DIR}/claude-statusline-slow-${uid}"+if [ -s "$slow_cache" ] && [ $(( now - $(mtime "$slow_cache") )) -lt 60 ]; then+ . "$slow_cache" 2>/dev/null+else+ ops_global=""+ ops_dir="$HOME/.claude/plugins/data/ops-ops-marketplace/cache"+ # Unread email count (briefing cache)+ bf="$ops_dir/briefing.json"+ if [ -s "$bf" ] && [ $(( now - $(mtime "$bf") )) -lt 7200 ]; then+ unread=$(jq -r '.email.unread_count // 0' "$bf" 2>/dev/null)+ case "$unread" in *[!0-9]*|'') unread=0;; esac+ [ "$unread" -gt 0 ] && ops_global="${ops_global}${T_acc}📬 ${unread}${R} "+ fi+ # Projects needing attention+ ph="$ops_dir/projects_health.json"+ if [ -s "$ph" ] && [ $(( now - $(mtime "$ph") )) -lt 7200 ]; then+ attn=$(jq -r '(.summary.needs_attention // 0) + (.summary.blocked // 0)' "$ph" 2>/dev/null)+ case "$attn" in *[!0-9]*|'') attn=0;; esac+ [ "$attn" -gt 0 ] && ops_global="${ops_global}${T_warn}🚧 ${attn}${R} "+ fi+ ops_global="${ops_global% }"++ # Per-project badge groups from config+ # For each project in config, read its badge file from the ops cache dir.+ # Badge file: $ops_dir/project-<key>.json — daemon precomputes it.+ # Generic schema: { "badges": [ { "icon": "◉", "value": "3/3", "color": "ok|warn|danger|dim" } ] }+ proj_badges=""+ if [ "${CFG_proj_count:-0}" -gt 0 ] 2>/dev/null; then+ for _pk in $CFG_proj_slugs; do+ _pbf="$ops_dir/project-${_pk}.json"+ if [ -s "$_pbf" ] && [ $(( now - $(mtime "$_pbf") )) -lt 7200 ]; then+ _label=$(jq -r '.label // ""' "$_pbf" 2>/dev/null)+ # C2: jq emits a sentinel string; sed replaces it with the real ESC byte.+ _bdgs=$(jq -r '(.badges // []) | map(+ (if .color == "ok" then "32"+ elif .color == "warn" then "33"+ elif .color == "danger" then "1;31"+ else "38;5;245" end) as $c+ | "ESC_PH[" + $c + "m" + (.icon // "") + " " + (.value // "") + "ESC_PH[0m"+ ) | join(" ")' "$_pbf" 2>/dev/null | sed "s/ESC_PH/${ESC}/g")+ if [ -n "$_bdgs" ]; then+ _pgrp="${T_acc}${_label:-$_pk}${R} ${_bdgs}"+ proj_badges="${proj_badges}${_pgrp}${SEP_PB}"+ fi+ fi+ done+ fi++ esc1() { printf '%s' "$1" | sed "s/'/'\\\\''/g"; }+ printf "ops_global='%s'\nproj_badges='%s'\n" "$(esc1 "$ops_global")" "$(esc1 "$proj_badges")" \+ > "$slow_cache" 2>/dev/null+fi++# ── Fleet badges (L2) — bg agents, rotation, SDK fallback ────────────────────+line2_fleet=""+if [ "$CFG_fleet_bg" = "1" ]; then+ bg_cache="${CACHE_DIR}/claude-bgcount-${uid}"+ bg_ttl=30+ bg_age=$(( now - $(mtime "$bg_cache") ))+ # M2: prefer python3 for JSON parsing; fall back to jq when python3 is absent.+ if command -v python3 >/dev/null 2>&1; then+ _bg_cmd='claude agents --json 2>/dev/null | python3 -c "+import json,sys+try:+ d=json.load(sys.stdin)+ print(len([a for a in d if a.get(\"status\")==\"running\"]), len(d))+except Exception:+ print(0,0)"'+ else+ _bg_cmd='r=$(claude agents --json 2>/dev/null); total=$(printf "%s" "$r" | jq "length" 2>/dev/null || echo 0); running=$(printf "%s" "$r" | jq "[.[]|select(.status=="running")]|length" 2>/dev/null || echo 0); printf "%s %s" "$running" "$total"'+ fi+ bg_counts=$(async_cache "$bg_cache" "$bg_ttl" sh -c "$_bg_cmd")+ IFS=' ' read -r bg_running bg_total <<EOF+$bg_counts+EOF+ : "${bg_running:=0}"; : "${bg_total:=0}"+ if [ "${bg_running:-0}" -gt 0 ] 2>/dev/null; then+ line2_fleet="${line2_fleet}${line2_fleet:+${T_dim}│${R}}${T_acc}🤖${bg_running}/${bg_total}${R}"+ fi+fi++if [ "$CFG_fleet_rot" = "1" ]; then+ rot_state="$rot_dir/state.json"+ if [ -s "$rot_state" ]; then+ active_acct=$(jq -r '.activeAccount // ""' "$rot_state" 2>/dev/null)+ rl_locked=$(jq -r '[.accounts | to_entries[] | select(.value.rateLimited == true or (.value.lastUtilization.pct // 0) >= 90)] | length' "$rot_state" 2>/dev/null)+ if [ -n "$active_acct" ]; then+ rc="${T_ok}"; [ "${rl_locked:-0}" -gt 0 ] && rc="${T_warn}"+ rot_badge="${rc}🔄$(acct_alias "$active_acct")${R}"+ [ "${rl_locked:-0}" -gt 0 ] && rot_badge="${rot_badge}${T_dim}⚡${rl_locked}${R}"+ line2_fleet="${line2_fleet}${line2_fleet:+${T_dim}│${R}}${rot_badge}"+ fi+ fi+fi++if [ "$CFG_fleet_sdk" = "1" ]; then+ sdk_flag="$HOME/.claude/state/quota-fallback/sdk-mode.active"+ sdk_spend="$HOME/.claude/state/quota-fallback/sdk-usage.log"+ if [ -f "$sdk_flag" ]; then+ sdk_turns=$(grep -c . "$sdk_spend" 2>/dev/null || echo 0)+ line2_fleet="${line2_fleet}${line2_fleet:+${T_dim}│${R}}${T_warn}⚠${sdk_turns}${R}"+ fi+fi++# Cache-refresh countdown (only when bg-agent cache is active)+if [ "$CFG_fleet_cache" = "1" ] && [ "$CFG_fleet_bg" = "1" ] && [ -n "$line2_fleet" ]; then+ refresh_left=$(( bg_ttl - bg_age ))+ [ "$refresh_left" -lt 0 ] && refresh_left=0+ line2_fleet="${line2_fleet} ${T_dim}↻${refresh_left}s${R}"+fi++# ── Current project detection from cwd ───────────────────────────────────────+cur_proj=""+if [ "${CFG_proj_count:-0}" -gt 0 ] 2>/dev/null && [ -n "$_cfg_file" ]; then+ cwd_lc=$(printf '%s' "$cwd" | tr '[:upper:]' '[:lower:]')+ # Check each configured project's match substring+ for _pk in $CFG_proj_slugs; do+ _match=$(jq -r --arg k "$_pk" '.projects[] | select(.key==$k) | .match // ""' "$_cfg_file" 2>/dev/null)+ [ -n "$_match" ] || continue+ case "$cwd_lc" in+ *"$_match"*) cur_proj="$_pk"; break ;;+ esac+ done+fi++# ── Carousel pool (L2) ────────────────────────────────────────────────────────+# Rotates every $CFG_carousel_sec seconds (epoch-based, sessions stay in sync).+cpool=""+for _cp_item in $CFG_carousel_pool; do+ _cp_seg=""+ case "$_cp_item" in+ cost) _cp_seg="$cost_part" ;;+ lines) _cp_seg="$lines_part" ;;+ global_ops) _cp_seg="$ops_global" ;;+ rate_limit|rl|quota) _cp_seg="$rl_part" ;;+ esac+ [ -n "$_cp_seg" ] && cpool="${cpool}${SEP}${_cp_seg}"+done++# Per-project badge groups NOT matching the current project go in carousel too+if [ -n "$proj_badges" ]; then+ _oIFS=$IFS; IFS=$(printf '\035')+ set -f+ for _pg in $proj_badges; do+ [ -z "$_pg" ] && continue+ if [ -n "$cur_proj" ] && [ -n "$_cfg_file" ]; then+ _plabel=$(jq -r --arg k "$cur_proj" '.projects[] | select(.key==$k) | .label // .key' "$_cfg_file" 2>/dev/null)+ case "$_pg" in *"${_plabel:-$cur_proj}"*) continue ;; esac+ fi+ cpool="${cpool}${SEP}${_pg}"+ done+ set +f; IFS=$_oIFS+fi++carousel_slot=""+cpool=${cpool#"$SEP"}+if [ -n "$cpool" ]; then+ cn=0; _oIFS=$IFS; IFS=$SEP; set -f+ for c in $cpool; do cn=$(( cn + 1 )); done+ if [ "$cn" -gt 0 ]; then+ pick=$(( (now / CFG_carousel_sec) % cn )); i=0+ for c in $cpool; do+ [ "$i" -eq "$pick" ] && { carousel_slot="$c"; break; }+ i=$(( i + 1 ))+ done+ fi+ set +f; IFS=$_oIFS+fi++# ── Width-limited line packer ─────────────────────────────────────────────────+# Greedy: takes segments, packs with " │ " dividers until $cols is exhausted.+# Never truncates mid-segment; overflow is silently dropped.+pack_line() {+ # $1 = max width; remaining args = segments (may be empty, skipped)+ _max=$1; shift+ _out=""; _used=0; _div=" ${T_dim}│${R} "+ _div_w=5 # " │ " = 2 + 1 (│ U+2502, width=1) + 2 = 5 visible chars+ for _seg; do+ [ -z "$_seg" ] && continue+ _sw=$(vis_width "$_seg")+ if [ -z "$_out" ]; then+ [ $(( _used + _sw )) -le "$_max" ] && { _out="$_seg"; _used=$(( _used + _sw )); }+ else+ [ $(( _used + _div_w + _sw )) -le "$_max" ] && {+ _out="${_out}${_div}${_seg}"+ _used=$(( _used + _div_w + _sw ))+ }+ fi+ done+ printf '%s' "$_out"+}++# ── Line 3 — per-project rotate ───────────────────────────────────────────────+# One project per tick (15s), cycling through configured project badge groups.+line3=""+line3_is_proj=0 # 1 = came from proj_badges, 0 = carousel fallback+if [ "${CFG_proj_count:-0}" -gt 0 ] 2>/dev/null && [ -n "$proj_badges" ]; then+ pn=0; _oIFS=$IFS; IFS=$(printf '\035')+ set -f+ for _pg in $proj_badges; do [ -n "$_pg" ] && pn=$(( pn + 1 )); done+ set +f; IFS=$_oIFS+ if [ "$pn" -gt 0 ]; then+ pslot=$(( (now / CFG_carousel_sec) % pn )); pi=0+ _oIFS=$IFS; IFS=$(printf '\035'); set -f+ for _pg in $proj_badges; do+ [ -z "$_pg" ] && continue+ [ "$pi" -eq "$pslot" ] && { line3="$_pg"; line3_is_proj=1; break; }+ pi=$(( pi + 1 ))+ done+ set +f; IFS=$_oIFS+ fi+fi+# Fall back to just the cpool carousel if no project badges configured+[ -z "$line3" ] && line3="$carousel_slot"++# ── Assemble Line 1 (cockpit instruments) ────────────────────────────────────+set --+for _w in $CFG_widgets_line1; do+ case "$_w" in+ ctx_gauge) [ -n "$ctx_bar" ] && set -- "$@" "$ctx_bar" ;;+ quota_gauge) [ -n "$quota_bar" ] && set -- "$@" "$quota_bar" ;;+ pace_badge) [ -n "$pace_badge" ] && set -- "$@" "$pace_badge" ;;+ cache_badge) [ -n "$cache_badge" ] && set -- "$@" "$cache_badge" ;;+ plan_badge) [ -n "$plan_badge" ] && set -- "$@" "$plan_badge" ;;+ account_arrow) [ -n "$account_arrow" ] && set -- "$@" "$account_arrow" ;;+ esac+done+line1=$(pack_line "$cols" "$@")++# ── Assemble Line 2 (session + system + fleet + carousel) ────────────────────+if [ "$cols" -lt 80 ]; then+ # Narrow: single rotating metric+ pool2=""+ for p in "$model_part" "$git_part" "$tasks_part" "${rl_short:-$rl_part}" "$cost_part" "$lines_part"; do+ [ -n "$p" ] && pool2="${pool2}${SEP}${p}"+ done+ pool2=${pool2#"$SEP"}+ if [ -n "$pool2" ]; then+ pn=0; _oIFS=$IFS; IFS=$SEP; set -f+ for p in $pool2; do pn=$(( pn + 1 )); done+ if [ "$pn" -gt 0 ]; then+ ps=$(( (now / CFG_carousel_sec) % pn )); pi=0; chosen=""+ for p in $pool2; do+ [ "$pi" -eq "$ps" ] && { chosen="$p"; break; }+ pi=$(( pi + 1 ))+ done+ set +f; IFS=$_oIFS+ line2=$(pack_line "$cols" "$loc_badge" "$chosen")+ else+ set +f; IFS=$_oIFS+ line2=$(pack_line "$cols" "$loc_badge" "$plan_short")+ fi+ else+ line2=$(pack_line "$cols" "$loc_badge" "$plan_short")+ fi+else+ # Wide: loc + model + git + tasks + project_slot + fleet + sys + carousel+ proj_slot=""+ if [ -n "$cur_proj" ] && [ -n "$proj_badges" ]; then+ _oIFS=$IFS; IFS=$(printf '\035'); set -f+ for _pg in $proj_badges; do+ [ -z "$_pg" ] && continue+ # match by prefix (label is first word)+ _plabel=$(jq -r --arg k "$cur_proj" '.projects[] | select(.key==$k) | .label // .key' "$_cfg_file" 2>/dev/null)+ case "$_pg" in *"${_plabel:-$cur_proj}"*) proj_slot="$_pg"; break;; esac+ done+ set +f; IFS=$_oIFS+ fi+ set --+ for _w in $CFG_widgets_line2; do+ case "$_w" in+ location) [ -n "$loc_badge" ] && set -- "$@" "$loc_badge" ;;+ model) [ -n "$model_part" ] && set -- "$@" "$model_part" ;;+ git_branch) [ -n "$git_part" ] && set -- "$@" "$git_part" ;;+ tasks) [ -n "$tasks_part" ] && set -- "$@" "$tasks_part" ;;+ fleet)+ [ -n "$agents_part" ] && set -- "$@" "$agents_part"+ [ -n "$proj_slot" ] && set -- "$@" "$proj_slot"+ [ -n "$line2_fleet" ] && set -- "$@" "$line2_fleet"+ ;;+ sys_metrics)+ [ -n "$sys_part" ] && set -- "$@" "$sys_part"+ [ -n "$peer_badge" ] && set -- "$@" "$peer_badge"+ [ -n "$load_warn" ] && set -- "$@" "$load_warn"+ [ -n "$disk_warn" ] && set -- "$@" "$disk_warn"+ ;;+ carousel) [ -n "$carousel_slot" ] && set -- "$@" "$carousel_slot" ;;+ esac+ done+ line2=$(pack_line "$cols" "$@")+fi++# ── Output ────────────────────────────────────────────────────────────────────+# Always emit line1 and line2 (guaranteed non-empty: at minimum the plan badge).+# Line3: print when it carries project badge content (line3_is_proj=1) not already+# on line2, OR when it is a carousel entry that differs from what line2 already shows.+_print_l3=0+if [ "$line3_is_proj" = "1" ]; then+ [ -n "$line3" ] && [ "$line3" != "${proj_slot:-}" ] && _print_l3=1+elif [ -n "$line3" ] && [ "$line3" != "$carousel_slot" ]; then+ _print_l3=1+fi+if [ "$_print_l3" = "1" ]; then+ line3_out=$(pack_line "$cols" "$line3")+ printf '%s\n%s\n%s' "$line1" "$line2" "$line3_out"+else+ printf '%s\n%s' "$line1" "$line2"+fidiff --git a/claude-ops/templates/statusline/statusline.config.default.json b/claude-ops/templates/statusline/statusline.config.default.jsonnew file mode 100644index 00000000..c7085d64--- /dev/null+++ b/claude-ops/templates/statusline/statusline.config.default.json@@ -0,0 +1,39 @@+{+ "_comment": "Default statusline config — generic cockpit preset. Copy to ~/.claude/statusline.config.json and customise. All fields are optional; omitted fields fall back to these defaults.",++ "theme": "cockpit",++ "gauge_width": {+ "ctx": 10,+ "quota": 8+ },++ "carousel_interval_sec": 15,++ "widgets": {+ "line1": ["ctx_gauge", "quota_gauge", "pace_badge", "cache_badge", "plan_badge", "account_arrow"],+ "line2": ["location", "model", "git_branch", "tasks", "fleet", "sys_metrics", "carousel"],+ "line3": ["project_rotate"]+ },++ "fleet": {+ "show_bg_agents": true,+ "show_rotation": true,+ "show_sdk_fallback": true,+ "show_cache_ttl": true+ },++ "sys_metrics": {+ "show_cpu": true,+ "show_ram": true,+ "show_disk": true,+ "show_load_warning": true,+ "show_disk_warning": true,+ "publish_peer": true,+ "show_peer": true+ },++ "carousel_pool": ["cost", "lines", "global_ops"],++ "projects": []+}diff --git a/claude-ops/templates/statusline/tests/fixtures/input-basic.json b/claude-ops/templates/statusline/tests/fixtures/input-basic.jsonnew file mode 100644index 00000000..55ca50d1--- /dev/null+++ b/claude-ops/templates/statusline/tests/fixtures/input-basic.json@@ -0,0 +1,12 @@+{+ "workspace": { "current_dir": "/home/user/projects/myapp" },+ "model": { "display_name": "Claude Sonnet 4.6" },+ "rate_limits": {+ "five_hour": { "used_percentage": 45, "resets_at": 9999999999 },+ "seven_day": { "used_percentage": 20, "resets_at": 9999999999 }+ },+ "context_window": { "used_percentage": 30 },+ "cost": { "total_cost_usd": 0.12, "total_lines_added": 42, "total_lines_removed": 7 },+ "session_id": "test-session-basic",+ "transcript_path": ""+}diff --git a/claude-ops/templates/statusline/tests/fixtures/input-danger.json b/claude-ops/templates/statusline/tests/fixtures/input-danger.jsonnew file mode 100644index 00000000..d434b8a3--- /dev/null+++ b/claude-ops/templates/statusline/tests/fixtures/input-danger.json@@ -0,0 +1,12 @@+{+ "workspace": { "current_dir": "/home/user/projects/myapp" },+ "model": { "display_name": "Claude Opus 4.8 (1M context)" },+ "rate_limits": {+ "five_hour": { "used_percentage": 91, "resets_at": 9999999999 },+ "seven_day": { "used_percentage": 85, "resets_at": 9999999999 }+ },+ "context_window": { "used_percentage": 93 },+ "cost": { "total_cost_usd": 2.5, "total_lines_added": 0, "total_lines_removed": 0 },+ "session_id": "test-session-danger",+ "transcript_path": ""+}diff --git a/claude-ops/templates/statusline/tests/fixtures/input-minimal.json b/claude-ops/templates/statusline/tests/fixtures/input-minimal.jsonnew file mode 100644index 00000000..990771ee--- /dev/null+++ b/claude-ops/templates/statusline/tests/fixtures/input-minimal.json@@ -0,0 +1,9 @@+{+ "workspace": { "current_dir": "" },+ "model": { "display_name": "" },+ "rate_limits": {},+ "context_window": {},+ "cost": {},+ "session_id": "",+ "transcript_path": ""+}diff --git a/claude-ops/templates/statusline/tests/fixtures/peer-danger.json b/claude-ops/templates/statusline/tests/fixtures/peer-danger.jsonnew file mode 100644index 00000000..d31e3fec--- /dev/null+++ b/claude-ops/templates/statusline/tests/fixtures/peer-danger.json@@ -0,0 +1,8 @@+{+ "host": "ams",+ "cpu_pct": 95,+ "ram_free_g": 1,+ "load1": "12.3",+ "df_free_g": 2,+ "ts": 0+}diff --git a/claude-ops/templates/statusline/tests/fixtures/peer-fresh.json b/claude-ops/templates/statusline/tests/fixtures/peer-fresh.jsonnew file mode 100644index 00000000..bb0368c7--- /dev/null+++ b/claude-ops/templates/statusline/tests/fixtures/peer-fresh.json@@ -0,0 +1,8 @@+{+ "host": "ams",+ "cpu_pct": 8,+ "ram_free_g": 12,+ "load1": "0.5",+ "df_free_g": 88,+ "ts": 0+}diff --git a/claude-ops/templates/statusline/tests/run-tests.sh b/claude-ops/templates/statusline/tests/run-tests.shnew file mode 100755index 00000000..4cd3d971--- /dev/null+++ b/claude-ops/templates/statusline/tests/run-tests.sh@@ -0,0 +1,431 @@+#!/bin/sh+# run-tests.sh — statusline test suite (POSIX sh)+# Tests: width, gauge boundaries, pace badge, config, peer metrics, dedup.+# Uses a temp HOME so no real ~/.claude/ dirs are touched.+set -eu++TESTS_DIR="$(cd "$(dirname "$0")" && pwd)"+SCRIPT="$(cd "$TESTS_DIR/.." && pwd)/statusline-command.sh"+FIXTURES="$TESTS_DIR/fixtures"++pass=0; fail=0++ok() { pass=$(( pass + 1 )); printf ' [ ok ] %s\n' "$1"; }+nok() { fail=$(( fail + 1 )); printf ' [FAIL] %s\n' "$1"; }++assert_exit0() {+ _label="$1"; shift+ if "$@" >/dev/null 2>&1; then ok "$_label"; else nok "$_label"; fi+}++# strip_ansi: remove ESC[...m sequences+strip_ansi() { printf '%s' "$1" | sed 's/\x1b\[[0-9;]*m//g'; }++# display_width: measure true terminal display width of a plain (ANSI-stripped) string.+# Uses python3 unicodedata.east_asian_width for accurate 2-cell glyph accounting.+# Falls back to wc -m + expanded emoji allowlist when python3 is absent (L3/H3 guard).+if [ "$(uname -s)" = "Darwin" ]; then _u8lc="en_US.UTF-8"; else _u8lc="C.UTF-8"; fi+display_width() {+ _dw_s="$1"+ if command -v python3 >/dev/null 2>&1; then+ printf '%s' "$_dw_s" | python3 -c "+import sys, unicodedata+s = sys.stdin.read()+w = 0+for c in s:+ ew = unicodedata.east_asian_width(c)+ if ew in ('W', 'F'):+ w += 2+ elif unicodedata.category(c) == 'Mn':+ pass+ else:+ w += 1+print(w)+" 2>/dev/null || printf '%s' "$_dw_s" | LC_ALL=$_u8lc wc -m | tr -d ' '+ else+ _dw_cw=$(printf '%s' "$_dw_s" | LC_ALL=$_u8lc wc -m | tr -d ' ')+ _dw_ew=$(printf '%s' "$_dw_s" | LC_ALL=$_u8lc grep -o \+ -e '🤖' -e '📬' -e '🚧' -e '🔥' -e '💾' -e '⚡' -e '📣' \+ -e '🛒' -e '📈' -e '🥊' -e '🎧' -e '❄' -e '✦' -e '🔄' -e '🔴' \+ -e '⚑' -e '⌂' -e '▥' -e '▲' -e '▸' -e '▪' -e '⟳' -e '✓' \+ -e '⎇' -e '●' -e '░' -e '█' -e '↻' -e '→' \+ 2>/dev/null | wc -l | tr -d ' ')+ echo $(( _dw_cw + _dw_ew ))+ fi+}++# render <input_file> <COLUMNS> <HOME_dir>+render() {+ HOME="$3" COLUMNS="$2" sh "$SCRIPT" < "$1" 2>/dev/null+}++# ── Setup temp HOME ──────────────────────────────────────────────────────────+TMPDIR_BASE=$(mktemp -d)+trap 'rm -rf "$TMPDIR_BASE"' EXIT INT TERM++# Helper script for gauge color testing (avoids inline single-quote escaping)+GAUGE_HELPER="$TMPDIR_BASE/gauge_helper.sh"+cat > "$GAUGE_HELPER" << 'GAUGEEOF'+#!/bin/sh+# Usage: sh gauge_helper.sh <pct>+_p=$1+case "$_p" in ''|*[!0-9]*) _p=0;; esac+if [ "$_p" -ge 90 ]; then printf '1;31'+elif [ "$_p" -ge 75 ]; then printf '38;5;208'+elif [ "$_p" -ge 50 ]; then printf '33'+else printf '32'+fi+GAUGEEOF++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "1. Width: no line exceeds COLUMNS"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++for cols in 60 80 110 160 220; do+ THOME="$TMPDIR_BASE/home_w${cols}"+ mkdir -p "$THOME/.claude/.sysinfo" "$THOME/.claude/scripts/account-rotation"+ output=$(render "$FIXTURES/input-basic.json" "$cols" "$THOME")+ width_ok=1+ _lineno=0+ while IFS= read -r _line; do+ _lineno=$(( _lineno + 1 ))+ # Strip ANSI escape sequences first, then measure true display width (H3/M1)+ _vis=$(printf '%s' "$_line" | sed 's/\x1b\[[0-9;]*m//g')+ # Use display_width (python3 unicodedata or fallback) for accurate 2-cell glyph accounting+ _w=$(display_width "$_vis")+ # Guard: if measure returns non-numeric, skip+ case "$_w" in *[!0-9]*|'') continue;; esac+ if [ "$_w" -gt "$cols" ]; then+ width_ok=0+ nok "width@${cols} line${_lineno}: ${_w} visible chars > ${cols}: $(printf '%s' "$_vis" | cut -c1-60)..."+ fi+ done << LINEEOF+$output+LINEEOF+ [ "$width_ok" = "1" ] && ok "width@${cols}: all lines within ${cols} cols"+done++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "2. Gauge color boundaries"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++gauge_test() {+ _pct="$1"; _expect="$2"; _label="$3"+ _got=$(sh "$GAUGE_HELPER" "$_pct")+ if [ "$_got" = "$_expect" ]; then ok "$_label"; else nok "$_label (got '$_got', want '$_expect')"; fi+}++gauge_test 0 "32" "gauge@0% → green (32)"+gauge_test 49 "32" "gauge@49% → green (32)"+gauge_test 50 "33" "gauge@50% → yellow (33)"+gauge_test 74 "33" "gauge@74% → yellow (33)"+gauge_test 75 "38;5;208" "gauge@75% → orange (38;5;208)"+gauge_test 89 "38;5;208" "gauge@89% → orange (38;5;208)"+gauge_test 90 "1;31" "gauge@90% → bold-red (1;31)"+gauge_test 100 "1;31" "gauge@100% → bold-red (1;31)"++# ctx gauge at >=90% → line1 contains bold-red escape code+THOME2="$TMPDIR_BASE/home_gauge2"+mkdir -p "$THOME2/.claude/.sysinfo"+out_danger=$(render "$FIXTURES/input-danger.json" 160 "$THOME2")+line1_danger=$(printf '%s' "$out_danger" | head -1)+if printf '%s' "$line1_danger" | grep -q '1;31m'; then+ ok "ctx@93%: line1 contains bold-red (1;31m)"+else+ nok "ctx@93%: expected bold-red in line1"+fi++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "3. Pace speedometer"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++# At quota >=90: expect "rotating" on line1+THOME3="$TMPDIR_BASE/home_pace_rot"+mkdir -p "$THOME3/.claude/.sysinfo"+out_rot=$(render "$FIXTURES/input-danger.json" 160 "$THOME3")+vis_rot=$(strip_ansi "$(printf '%s' "$out_rot" | head -1)")+if printf '%s' "$vis_rot" | grep -q 'rotating'; then+ ok "pace@91%: 'rotating' badge on line1"+else+ nok "pace@91%: expected 'rotating' in line1, got: $(printf '%s' "$vis_rot" | cut -c1-80)"+fi++# At quota 45% with no burn history: expect "idle" on line1+THOME4="$TMPDIR_BASE/home_pace_idle"+mkdir -p "$THOME4/.claude/.sysinfo"+out_idle=$(render "$FIXTURES/input-basic.json" 160 "$THOME4")+vis_idle=$(strip_ansi "$(printf '%s' "$out_idle" | head -1)")+if printf '%s' "$vis_idle" | grep -q 'idle'; then+ ok "pace@45%,no-history: 'idle' badge on line1"+else+ nok "pace@45%,no-history: expected 'idle' in line1, got: $(printf '%s' "$vis_idle" | cut -c1-80)"+fi++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "4. Config parsing"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++# Default config is valid JSON+assert_exit0 "default config: valid JSON (jq .)" \+ jq . "$(dirname "$SCRIPT")/statusline.config.default.json"++# Minimal input (all empty) → exit 0+THOME5="$TMPDIR_BASE/home_cfg_min"+mkdir -p "$THOME5/.claude/.sysinfo"+assert_exit0 "minimal input: exit 0" \+ sh -c "HOME='$THOME5' COLUMNS=120 sh '$SCRIPT' < '$FIXTURES/input-minimal.json' >/dev/null 2>&1"++# Full/danger input → exit 0+THOME6="$TMPDIR_BASE/home_cfg_full"+mkdir -p "$THOME6/.claude/.sysinfo"+assert_exit0 "danger input: exit 0" \+ sh -c "HOME='$THOME6' COLUMNS=160 sh '$SCRIPT' < '$FIXTURES/input-danger.json' >/dev/null 2>&1"++# Absent config file → exit 0 (built-in defaults)+THOME7="$TMPDIR_BASE/home_cfg_absent"+mkdir -p "$THOME7/.claude/.sysinfo"+assert_exit0 "absent config: exit 0" \+ sh -c "HOME='$THOME7' COLUMNS=120 sh '$SCRIPT' < '$FIXTURES/input-basic.json' >/dev/null 2>&1"++# Garbage config → exit 0 (graceful fallback, jq errors suppressed)+THOME8="$TMPDIR_BASE/home_cfg_garbage"+mkdir -p "$THOME8/.claude/.sysinfo"+printf 'not json at all\n' > "$THOME8/.claude/statusline.config.json"+assert_exit0 "garbage config: exit 0" \+ sh -c "HOME='$THOME8' COLUMNS=120 sh '$SCRIPT' < '$FIXTURES/input-basic.json' >/dev/null 2>&1"++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "5. Peer metrics"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++_lhost=$(hostname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')+_peer_name="ams"; [ "$_lhost" = "ams" ] && _peer_name="fra"++# 5a. Fresh peer file → peer badge on line2+THOME9="$TMPDIR_BASE/home_peer_fresh"+mkdir -p "$THOME9/.claude/.sysinfo"+cp "$FIXTURES/peer-fresh.json" "$THOME9/.claude/.sysinfo/${_peer_name}.json"+touch "$THOME9/.claude/.sysinfo/${_peer_name}.json" # ensure mtime = now+out_peer=$(render "$FIXTURES/input-basic.json" 160 "$THOME9")+vis_peer=$(strip_ansi "$(printf '%s' "$out_peer" | sed -n '2p')")+if printf '%s' "$vis_peer" | grep -q "$_peer_name"; then+ ok "peer-fresh: '${_peer_name}' badge appears on line2"+else+ nok "peer-fresh: expected '${_peer_name}' in line2, got: $(printf '%s' "$vis_peer" | cut -c1-80)"+fi++# 5b. Stale peer file (>5min old) → "stale" on line2+THOME10="$TMPDIR_BASE/home_peer_stale"+mkdir -p "$THOME10/.claude/.sysinfo"+cp "$FIXTURES/peer-fresh.json" "$THOME10/.claude/.sysinfo/${_peer_name}.json"+# Back-date by 400s (>5min)+_stale_ts=$(date -d "400 seconds ago" +"%Y%m%d%H%M.%S" 2>/dev/null \+ || date -v-400S +"%Y%m%d%H%M.%S" 2>/dev/null \+ || echo "202001010000.00")+touch -t "$_stale_ts" "$THOME10/.claude/.sysinfo/${_peer_name}.json" 2>/dev/null || \+ touch -d "1970-01-01" "$THOME10/.claude/.sysinfo/${_peer_name}.json" 2>/dev/null || true+out_stale=$(render "$FIXTURES/input-basic.json" 160 "$THOME10")+vis_stale=$(strip_ansi "$(printf '%s' "$out_stale" | sed -n '2p')")+if printf '%s' "$vis_stale" | grep -q 'stale'; then+ ok "peer-stale: 'stale' badge on line2 for >5min old file"+else+ nok "peer-stale: expected 'stale' in line2, got: $(printf '%s' "$vis_stale" | cut -c1-80)"+fi++# 5c. No peer file → local only, exit 0, no stale badge+THOME11="$TMPDIR_BASE/home_peer_none"+mkdir -p "$THOME11/.claude/.sysinfo"+assert_exit0 "peer-none: exit 0 with no peer file" \+ sh -c "HOME='$THOME11' COLUMNS=160 sh '$SCRIPT' < '$FIXTURES/input-basic.json' >/dev/null 2>&1"+out_none=$(render "$FIXTURES/input-basic.json" 160 "$THOME11")+vis_none=$(strip_ansi "$(printf '%s' "$out_none" | sed -n '2p')")+if ! printf '%s' "$vis_none" | grep -q 'stale'; then+ ok "peer-none: no 'stale' badge without peer file"+else+ nok "peer-none: unexpected 'stale' in line2 when no peer file"+fi++# 5d. Publish: sysinfo file for this host created after render+THOME12="$TMPDIR_BASE/home_peer_pub"+mkdir -p "$THOME12/.claude/.sysinfo"+HOME="$THOME12" COLUMNS=120 sh "$SCRIPT" < "$FIXTURES/input-basic.json" >/dev/null 2>&1 || true+sleep 1 # allow background write to complete+_pub_file="$THOME12/.claude/.sysinfo/${_lhost}.json"+if [ -s "$_pub_file" ]; then+ ok "peer-publish: .sysinfo/${_lhost}.json created"+ if jq . "$_pub_file" >/dev/null 2>&1; then+ ok "peer-publish: .sysinfo/${_lhost}.json is valid JSON"+ else+ nok "peer-publish: .sysinfo/${_lhost}.json is not valid JSON"+ fi+else+ nok "peer-publish: .sysinfo/${_lhost}.json not found (expected async write within 1s)"+fi++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "6. Dedup: no metric token on two lines"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++THOME13="$TMPDIR_BASE/home_dedup"+mkdir -p "$THOME13/.claude/.sysinfo"++for _inf in "$FIXTURES/input-basic.json" "$FIXTURES/input-danger.json"; do+ _fname=$(basename "$_inf" .json)+ out_dd=$(render "$_inf" 160 "$THOME13")+ v1=$(strip_ansi "$(printf '%s' "$out_dd" | head -1)")+ v2=$(strip_ansi "$(printf '%s' "$out_dd" | sed -n '2p')")+ dedup_ok=1++ # 'ctx' token (context gauge) should only appear on line1+ if printf '%s' "$v1" | grep -q 'ctx' && printf '%s' "$v2" | grep -q 'ctx'; then+ nok "dedup[$_fname]: 'ctx' token on both line1 and line2"+ dedup_ok=0+ fi++ # pace badge ('idle', 'rotating', '%/m') should only appear on line1+ if printf '%s' "$v1" | grep -qE '(idle|rotating|%/m)' && \+ printf '%s' "$v2" | grep -qE '(idle|rotating|%/m)'; then+ nok "dedup[$_fname]: pace badge duplicated on both line1 and line2"+ dedup_ok=0+ fi++ [ "$dedup_ok" = "1" ] && ok "dedup[$_fname]: no metric token duplicated across lines"+done++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "7. Project badge cycling (C1 guard)"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+# Guards C1: with projects configured, line-3 must be non-empty and contain a+# project label — proving SEP_PB is defined and proj_badges splits correctly.+# Isolate the renderer's caches into a per-test dir via CLAUDE_STATUSLINE_CACHE_DIR+# so this never races the live session's uid-keyed /tmp/claude-statusline-slow-<uid>+# (shared-cache contamination was making this test flaky).+_cycle_cache="$TMPDIR_BASE/cache_cycle"+mkdir -p "$_cycle_cache"+_cycle_slow="$_cycle_cache/claude-statusline-slow-$(id -u)"+rm -f "$_cycle_slow" 2>/dev/null++_OPS_CACHE="$TMPDIR_BASE/home_cycle/.claude/plugins/data/ops-ops-marketplace/cache"+mkdir -p "$_OPS_CACHE"+mkdir -p "$TMPDIR_BASE/home_cycle/.claude/.sysinfo"++# Create two project badge files+cat > "$_OPS_CACHE/project-alpha.json" <<'PJEOF'+{"label":"Alpha","badges":[{"icon":"O","value":"2/2","color":"ok"}]}+PJEOF+cat > "$_OPS_CACHE/project-beta.json" <<'PJEOF'+{"label":"Beta","badges":[{"icon":"O","value":"1/3","color":"warn"}]}+PJEOF++# Create a config with both projects and a very short carousel interval+cat > "$TMPDIR_BASE/home_cycle/.claude/statusline.config.json" <<'CFGEOF'+{+ "theme":"cockpit","gauge_width":{"ctx":8,"quota":6},"carousel_interval_sec":15,+ "fleet":{"show_bg_agents":false,"show_rotation":false,"show_sdk_fallback":false,"show_cache_ttl":false},+ "sys_metrics":{"show_cpu":false,"show_ram":false,"show_disk":false,"publish_peer":false,"show_peer":false},+ "projects":[+ {"key":"alpha","label":"Alpha","match":"no-match-a","badges":["ecs"]},+ {"key":"beta","label":"Beta","match":"no-match-b","badges":["errors"]}+ ]+}+CFGEOF++out_c=$(HOME="$TMPDIR_BASE/home_cycle" CLAUDE_STATUSLINE_CACHE_DIR="$_cycle_cache" COLUMNS=160 sh "$SCRIPT" \+ < "$FIXTURES/input-basic.json" 2>/dev/null)+# Note: $() strips trailing newlines; add \n so sed -n '3p' can match line 3+line3_c=$(printf '%s\n' "$out_c" | sed -n '3p')+vis3_c=$(strip_ansi "$line3_c")++# Wipe slow_cache again and render a second time — what we assert is: line3 is+# non-empty and has a project label (proves SEP_PB defined + proj_badges split works).+rm -f "$_cycle_slow" 2>/dev/null+out_d=$(HOME="$TMPDIR_BASE/home_cycle" CLAUDE_STATUSLINE_CACHE_DIR="$_cycle_cache" COLUMNS=160 sh "$SCRIPT" \+ < "$FIXTURES/input-basic.json" 2>/dev/null)+line3_d=$(printf '%s\n' "$out_d" | sed -n '3p')+vis3_d=$(strip_ansi "$line3_d")++if [ -n "$vis3_c" ]; then+ ok "cycle: line3 non-empty (SEP_PB defined, proj_badges split works)"+else+ nok "cycle: line3 empty — SEP_PB likely undefined or proj_badges never populated"+fi++if printf '%s' "$vis3_c $vis3_d" | grep -qE '(Alpha|Beta)'; then+ ok "cycle: project label (Alpha or Beta) appears in line3 render"+else+ nok "cycle: no project label in line3 (got: '$(printf '%s' "$vis3_c" | cut -c1-60)')"+fi++# Restore slow_cache state (remove test artifact)+rm -f "$_cycle_slow" 2>/dev/null++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "8. ESC byte in rendered badge output (C2 guard)"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+# Guards C2: rendered output must contain real ESC bytes (0x1b), not literal "[32m".+# We test the general render output (which always contains colored segments).++THOME_ESC="$TMPDIR_BASE/home_esc"+mkdir -p "$THOME_ESC/.claude/.sysinfo"+out_esc=$(HOME="$THOME_ESC" COLUMNS=160 sh "$SCRIPT" < "$FIXTURES/input-basic.json" 2>/dev/null)++# Check for real ESC byte (0x1b followed by '[')+ESC_BYTE=$(printf '\033')+if printf '%s' "$out_esc" | grep -q "${ESC_BYTE}\["; then+ ok "esc-bytes: rendered output contains real ESC[... sequences"+else+ nok "esc-bytes: no real ESC byte found — output may contain literal '[32m' strings"+fi++# Also verify vis_width correctly strips ANSI (real ESC sequences disappear)+_sample=$(printf '%s' "$out_esc" | head -1)+_stripped=$(printf '%s' "$_sample" | sed "s/${ESC_BYTE}\[[0-9;]*m//g")+if printf '%s' "$_stripped" | grep -q "${ESC_BYTE}"; then+ nok "esc-strip: residual ESC bytes after ANSI strip — strip regex may be wrong"+else+ ok "esc-strip: no residual ESC bytes after stripping (strip regex works)"+fi++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "9. Syntax check"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++assert_exit0 "sh -n: statusline-command.sh" sh -n "$SCRIPT"+assert_exit0 "sh -n: run-tests.sh" sh -n "$TESTS_DIR/run-tests.sh"+assert_exit0 "jq: themes.json" jq . "$(dirname "$SCRIPT")/themes.json"+assert_exit0 "jq: statusline.config.default.json" \+ jq . "$(dirname "$SCRIPT")/statusline.config.default.json"++# ═══════════════════════════════════════════════════════════════════════════+echo ""+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "SUMMARY"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+printf " Passed: %d\n" "$pass"+printf " Failed: %d\n" "$fail"+echo ""++if [ "$fail" -gt 0 ]; then+ echo "FAIL — ${fail} test(s) failed."+ exit 1+fi+echo "All tests passed."+exit 0diff --git a/claude-ops/templates/statusline/themes.json b/claude-ops/templates/statusline/themes.jsonnew file mode 100644index 00000000..ced47fe6--- /dev/null+++ b/claude-ops/templates/statusline/themes.json@@ -0,0 +1,79 @@+{+ "_comment": "Named color themes for the statusline cockpit. Values are ANSI SGR codes (the part between ESC[ and m). Semantic roles map to display purposes — renderers apply these via ESC[<code>m...ESC[0m.",+ "cockpit": {+ "_description": "Default: rich color, green/yellow/orange/red graded gauges, dim dividers.",+ "ok": "32",+ "warn": "33",+ "hot": "38;5;208",+ "danger": "1;31",+ "dim": "38;5;245",+ "accent": "36",+ "accent2": "35",+ "bold_ok": "1;32",+ "bold_acc": "1;36",+ "gauge_ok": "32",+ "gauge_warn": "33",+ "gauge_hot": "38;5;208",+ "gauge_crit": "1;31",+ "gauge_empty": "38;5;236",+ "loc_remote": "1;97;41",+ "loc_home": "1;97;44"+ },+ "minimal": {+ "_description": "Reduced: only two shades — normal and dim. No color grading on gauges.",+ "ok": "0",+ "warn": "0",+ "hot": "0",+ "danger": "1",+ "dim": "38;5;245",+ "accent": "0",+ "accent2": "0",+ "bold_ok": "1",+ "bold_acc": "1",+ "gauge_ok": "0",+ "gauge_warn": "0",+ "gauge_hot": "0",+ "gauge_crit": "1",+ "gauge_empty": "38;5;245",+ "loc_remote": "1",+ "loc_home": "1"+ },+ "mono": {+ "_description": "Monochrome: bold for emphasis only, no color at all. Usable on terminals with no color support.",+ "ok": "0",+ "warn": "1",+ "hot": "1",+ "danger": "1;4",+ "dim": "2",+ "accent": "1",+ "accent2": "1",+ "bold_ok": "1",+ "bold_acc": "1",+ "gauge_ok": "0",+ "gauge_warn": "1",+ "gauge_hot": "1",+ "gauge_crit": "1;4",+ "gauge_empty": "2",+ "loc_remote": "1;7",+ "loc_home": "1;7"+ },+ "nord": {+ "_description": "Nord palette — cool blues and muted tones.",+ "ok": "38;5;108",+ "warn": "38;5;179",+ "hot": "38;5;203",+ "danger": "1;38;5;203",+ "dim": "38;5;60",+ "accent": "38;5;110",+ "accent2": "38;5;146",+ "bold_ok": "1;38;5;108",+ "bold_acc": "1;38;5;110",+ "gauge_ok": "38;5;108",+ "gauge_warn": "38;5;179",+ "gauge_hot": "38;5;203",+ "gauge_crit": "1;38;5;203",+ "gauge_empty": "38;5;237",+ "loc_remote": "1;97;48;5;60",+ "loc_home": "1;97;48;5;24"+ }+}diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex f798b5ab..6196b6fd 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -49,6 +49,7 @@ run_suite "$TESTS_DIR/test-safety-hooks.sh"run_suite "$TESTS_DIR/test-deploy-fix-hooks.sh"run_suite "$TESTS_DIR/test-cloudflare-dns-lib.sh"run_suite "$TESTS_DIR/test-ops-dns-provision.sh"+run_suite "$TESTS_DIR/../templates/statusline/tests/run-tests.sh"echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"echo "SUMMARY"