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(competitor-intel): v2.3 full pipeline redesign — 5 signal sources + severity routing (v2.3.0) (#244)
Aurora Capital0ed73e4f12f8
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 73f3f890..e52843bc 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -11,7 +11,7 @@"name": "ops","description": "Business operations command center for Claude Code — 35 skills, 18 agents, smart background daemon. Manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (AWS), revenue (Stripe+RevenueCat), e-commerce, marketing, monitoring (Datadog/New Relic/OTEL), and voice. Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, and YOLO autonomous mode with 4 parallel C-suite agents.","source": "./claude-ops",- "version": "2.2.5",+ "version": "2.3.0","category": "productivity","keywords": ["ops",diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.jsonindex 0cc1a5a8..f5b43dba 100644--- a/claude-ops/.claude-plugin/plugin.json+++ b/claude-ops/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "ops",- "version": "2.2.5",+ "version": "2.3.0","description": "Business operations command center for Claude Code — 35 skills, 18 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, and YOLO mode for autonomous operation with 4 parallel C-suite agents.","author": {"name": "Lifecycle Innovations Limited",diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex 12a5b636..9e3167f2 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -2,6 +2,35 @@All notable changes to this project will be documented in this file.+## [2.3.0] — 2026-05-17+### Added+- **Competitor-intel v2.3 — full pipeline redesign with 5 signal sources, severity-tiered routing, and append-only event log.** Goes from "weekly Tavily dump + Sonnet synth" to a real CI system that rivals Crayon/Klue/Kompyte's signal breadth at $0 incremental cost.++ **New signal collectors** (`scripts/lib/competitor/`, all bash + jq + curl, no extra deps):+ - `reddit-search.sh` — Reddit JSON API (no auth), severity-classified by score + keyword heuristics (complaint, vs, alternative, switching from).+ - `hn-search.sh` — HN Algolia API (no auth), severity by points + comments + Show HN/Launch HN/is hiring detection.+ - `appstore-lookup.sh` — Apple iTunes Lookup API (no auth), version + rating + release-date snapshots for mobile competitors (opt-in via `preferences.json .competitor_intel.app_store: true`).+ - `jobs-feed.sh` — Greenhouse + Lever public job APIs (no auth), strategic-hire detection (VP / Head of / Director / Chief / Founding → high severity).+ - `page-diff.sh` — HTML pricing/features/careers/changelog page-diff engine. Fetches with curl, normalizes via Python (strip script/style/svg, decode entities, collapse whitespace), SHA-256, persists snapshots to `competitor_state/<brand>/<comp>/snapshots/<kind>.<sha8>.txt` with `<kind>.latest` symlink. Diffs emit lines-changed + extracted snippet. Severity: pricing-page change with money token (`$`, `€`, `/mo`, `/yr`) → high; other pricing/features/changelog → med; tiny copy tweaks → low. Last 12 snapshots retained per kind.++ **Severity-tiered routing** (`scripts/lib/competitor/event-router.sh` + 2 new crons):+ - All events append to `competitor_state/events.jsonl` (audit log).+ - `severity: high` → also writes to `queue/immediate.jsonl`, drained every 10min by `ops-competitor-alert.sh` (Telegram push if creds + always `alerts.log`).+ - `severity: med` → `queue/daily.jsonl`, drained at 17:00 by `ops-cron-competitor-daily.sh` (grouped-by-competitor roll-up, dated daily-YYYY-MM-DD.md + Telegram digest with 4000-char cap).+ - `severity: low` → state-only, surfaced in weekly strategic synthesis.++ **Weekly cron pipeline rewrite** (`ops-cron-competitor-intel.sh`, 432 lines):+ - Discovery cached 30d (skips Tavily when state has fresh `last_discovery`, saving ~60% Tavily spend).+ - Per-competitor signals collected in parallel background jobs with 30s timeout guards; page-diff URLs read per-competitor from `preferences.json .competitor_intel.urls.<competitor>`.+ - Reads 7d window of `events.jsonl` (jq epoch filter) and merges into Sonnet prompt (capped at 100k chars).+ - Raw synthesis always persisted to `reports/competitor-intel/YYYY-MM-DD_<brand>-synthesis.md` BEFORE extraction so partial LLM output is never lost.+ - State extended with `last_discovery` and `app_store_enabled` keys (backward compat with v2.2.5 `competitors` + `last_run` preserved).+ - Graceful degradation: missing `TAVILY_API_KEY` AND no cached state → SKIP cleanly; missing Tavily but cached state present → proceed with non-Tavily signals only.++ **Daemon services config** — `competitor-alert` (`*/10 * * * *`) and `competitor-daily` (`0 17 * * *`) added to `daemon-services.default.json` and `daemon-services.example.json` alongside existing weekly `competitor-intel` (`0 10 * * 1` Europe/Amsterdam).++ **Cost model at 10-brand scale**: ~13 Tavily calls/wk total (cached discovery), ~320k Sonnet tokens/mo on Max-OAuth — $0 incremental.+## [2.2.5] — 2026-05-17### Fixed- **`competitor-intel` LLM synth dropped to raw Tavily fallback when output didn't include `---REPORT---` marker.** Sonnet was producing valid strategic deltas but the strict marker check threw them away. Three-strategy JSON extraction now: (1) fenced ` ```json ` block, (2) bare `{"competitors":[...]}` regex anywhere in output, (3) bullet-list scrape from "NEW entrants" / "Competitor moves" sections. Report extraction now falls back to stripping JSON blocks from full synthesis instead of dropping to raw Tavily dump.diff --git a/claude-ops/package.json b/claude-ops/package.jsonindex 628905f5..c798dbee 100644--- a/claude-ops/package.json+++ b/claude-ops/package.json@@ -1,6 +1,6 @@{"name": "claude-ops-bin",- "version": "2.2.5",+ "version": "2.3.0","private": true,"description": "Runtime dependencies for claude-ops bin scripts (ops-telegram-autolink.mjs, ops-slack-autolink.mjs). Installed separately from telegram-server/ so the .mjs scripts resolve modules from claude-ops/node_modules regardless of invocation cwd.","type": "module",diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonindex 7ada8f0e..98e2450c 100644--- a/claude-ops/scripts/daemon-services.default.json+++ b/claude-ops/scripts/daemon-services.default.json@@ -55,6 +55,18 @@"cron": "0 10 * * 1","_note": "Weekly competitor intelligence report every Monday at 10am. Script not yet landed — re-enable when ops-cron-competitor-intel.sh is added."},+ "competitor-alert": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-competitor-alert.sh",+ "cron": "*/10 * * * *",+ "_note": "Drains queue/immediate.jsonl every 10 min. Pushes high-severity competitor signals to Telegram (if TELEGRAM_BOT_TOKEN+TELEGRAM_CHAT_ID set) and always persists to reports/competitor-intel/alerts.log."+ },+ "competitor-daily": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-daily.sh",+ "cron": "0 17 * * *",+ "_note": "Daily 17:00 roll-up of med-severity competitor signals. Groups by competitor, writes daily-YYYY-MM-DD.md, pushes Telegram digest if creds present."+ },"marketing-prewarm": {"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-prewarm.sh",diff --git a/claude-ops/scripts/daemon-services.example.json b/claude-ops/scripts/daemon-services.example.jsonindex af89225b..3895e1d0 100644--- a/claude-ops/scripts/daemon-services.example.json+++ b/claude-ops/scripts/daemon-services.example.json@@ -30,6 +30,18 @@"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-intel.sh","_note": "Requires: TELEGRAM_BOT_TOKEN. Optional: TAVILY_API_KEY for better search results."},+ "competitor-alert": {+ "enabled": true,+ "cron": "*/10 * * * *",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-competitor-alert.sh",+ "_note": "Requires: collector scripts writing to queue/immediate.jsonl. Optional: TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID for push alerts. Always persists to reports/competitor-intel/alerts.log."+ },+ "competitor-daily": {+ "enabled": true,+ "cron": "0 17 * * *",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-daily.sh",+ "_note": "Requires: collector scripts writing to queue/daily.jsonl. Optional: TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID for digest push."+ },"message-listener": {"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-message-listener.sh",diff --git a/claude-ops/scripts/lib/competitor/appstore-lookup.sh b/claude-ops/scripts/lib/competitor/appstore-lookup.shnew file mode 100755index 00000000..9f64f1f4--- /dev/null+++ b/claude-ops/scripts/lib/competitor/appstore-lookup.sh@@ -0,0 +1,101 @@+#!/usr/bin/env bash+set -euo pipefail++# App Store ranking + review signal collector — competitor intel v2.3+# Usage: appstore-lookup.sh <competitor-app-name> [--country US]++COMPETITOR_NAME="${1:-}"+COUNTRY="US"++if [[ -z "$COMPETITOR_NAME" ]]; then+ echo "Usage: appstore-lookup.sh <competitor-app-name> [--country US]" >&2+ exit 1+fi++shift+while [[ $# -gt 0 ]]; do+ case "$1" in+ --country) COUNTRY="${2:-US}"; shift 2 ;;+ *) shift ;;+ esac+done++LOG_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"+LOG_FILE="$LOG_DIR/competitor-appstore.log"+mkdir -p "$LOG_DIR"++log_err() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] appstore-lookup ERROR: $*" >> "$LOG_FILE"; }++# URL-encode the search term (jq @uri as fallback)+ENCODED_TERM="$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$COMPETITOR_NAME" 2>/dev/null \+ || jq -rn --arg t "$COMPETITOR_NAME" '$t | @uri')"++SEARCH_URL="https://itunes.apple.com/search?term=${ENCODED_TERM}&country=${COUNTRY}&entity=software&limit=5"++RESPONSE="$(curl -fsSL --max-time 10 "$SEARCH_URL" 2>/dev/null)" || {+ log_err "curl failed for '$COMPETITOR_NAME'"+ exit 0+}++RESULT_COUNT="$(printf '%s' "$RESPONSE" | jq -r '.resultCount // 0')"+if [[ "$RESULT_COUNT" -eq 0 ]]; then+ exit 0+fi++# Pick first result with kind == "software"+MATCH="$(printf '%s' "$RESPONSE" | jq -c '+ .results[]+ | select(.kind == "software")+ ' | head -1)"++if [[ -z "$MATCH" ]]; then+ exit 0+fi++NOW_ISO="$(date -u +%Y-%m-%dT%H:%M:%SZ)"++TRACK_ID="$(printf '%s' "$MATCH" | jq -r '.trackId')"+TRACK_NAME="$(printf '%s' "$MATCH" | jq -r '.trackName // ""')"+SELLER="$(printf '%s' "$MATCH" | jq -r '.sellerName // ""')"+VERSION="$(printf '%s' "$MATCH" | jq -r '.version // ""')"+RELEASE_DATE="$(printf '%s' "$MATCH" | jq -r '.currentVersionReleaseDate // ""')"+RATING="$(printf '%s' "$MATCH" | jq -r '.averageUserRating // 0')"+RATING_COUNT="$(printf '%s' "$MATCH" | jq -r '.userRatingCount // 0')"+PRICE="$(printf '%s' "$MATCH" | jq -r '.price // 0')"+CURRENCY="$(printf '%s' "$MATCH" | jq -r '.currency // "USD"')"++# Severity heuristic+SEVERITY="low"+if [[ -n "$RELEASE_DATE" ]]; then+ # Days since release+ # macOS: date -j -f; Linux: date -d+ RELEASE_EPOCH="$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$RELEASE_DATE" +%s 2>/dev/null \+ || date -d "$RELEASE_DATE" +%s 2>/dev/null || echo 0)"+ DAYS_AGO=$(( ($(date -u +%s) - RELEASE_EPOCH) / 86400 ))+ if [[ "$DAYS_AGO" -le 7 ]]; then+ SEVERITY="high"+ fi+fi+if [[ "$SEVERITY" != "high" && "$RATING_COUNT" -gt 10000 ]]; then+ SEVERITY="med"+fi++# Format release date as YYYY-MM-DD+RELEASE_SHORT="${RELEASE_DATE:0:10}"++SNIPPET="${SELLER} · v${VERSION} released ${RELEASE_SHORT}"++jq -cn \+ --arg source "appstore" \+ --arg timestamp "$NOW_ISO" \+ --arg competitor "$COMPETITOR_NAME" \+ --argjson trackId "$TRACK_ID" \+ --arg version "$VERSION" \+ --arg release_date "$RELEASE_DATE" \+ --argjson rating "$RATING" \+ --argjson rating_count "$RATING_COUNT" \+ --argjson price "$PRICE" \+ --arg currency "$CURRENCY" \+ --arg severity "$SEVERITY" \+ --arg snippet "$SNIPPET" \+ '{source:$source,timestamp:$timestamp,competitor:$competitor,trackId:$trackId,version:$version,release_date:$release_date,rating:$rating,rating_count:$rating_count,price:$price,currency:$currency,severity:$severity,snippet:$snippet}'diff --git a/claude-ops/scripts/lib/competitor/event-router.sh b/claude-ops/scripts/lib/competitor/event-router.shnew file mode 100644index 00000000..0c95923f--- /dev/null+++ b/claude-ops/scripts/lib/competitor/event-router.sh@@ -0,0 +1,64 @@+#!/usr/bin/env bash+# event-router.sh — Severity-tiered event routing for competitor intel v2.3+#+# Source this file to get the `route_event` function.+# Usage: echo "$jsonl_event" | route_event+#+# Routes:+# high → events.jsonl + queue/immediate.jsonl+# med → events.jsonl + queue/daily.jsonl+# low → events.jsonl only+#+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"++_router_log() {+ local log_file="$DATA_DIR/logs/competitor-router.log"+ mkdir -p "$DATA_DIR/logs" 2>/dev/null || true+ printf '%s [event-router] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$log_file" 2>/dev/null || true+}++route_event() {+ # Reads one JSONL event from stdin, routes by severity.+ local event+ event=$(cat)++ [[ -z "$event" ]] && return 0++ # Validate it's parseable JSON+ if ! printf '%s' "$event" | jq -e '.' >/dev/null 2>&1; then+ _router_log "WARN: skipping non-JSON input: ${event:0:120}"+ return 0+ fi++ local severity+ severity=$(printf '%s' "$event" | jq -r '.severity // "low"' 2>/dev/null || echo "low")++ # Ensure state dirs exist+ local state_dir="$DATA_DIR/competitor_state"+ local queue_dir="$state_dir/queue"+ mkdir -p "$queue_dir"++ # Always append to audit log+ printf '%s\n' "$event" >> "$state_dir/events.jsonl"++ case "$severity" in+ high)+ printf '%s\n' "$event" >> "$queue_dir/immediate.jsonl"+ _router_log "HIGH routed → queue/immediate.jsonl (competitor=$(printf '%s' "$event" | jq -r '.competitor // "?"' 2>/dev/null))"+ ;;+ med)+ printf '%s\n' "$event" >> "$queue_dir/daily.jsonl"+ _router_log "MED routed → queue/daily.jsonl (competitor=$(printf '%s' "$event" | jq -r '.competitor // "?"' 2>/dev/null))"+ ;;+ low)+ _router_log "LOW state-only (competitor=$(printf '%s' "$event" | jq -r '.competitor // "?"' 2>/dev/null))"+ ;;+ *)+ _router_log "WARN: unknown severity '$severity' — treating as low"+ ;;+ esac++ return 0+}diff --git a/claude-ops/scripts/lib/competitor/hn-search.sh b/claude-ops/scripts/lib/competitor/hn-search.shnew file mode 100755index 00000000..170744d3--- /dev/null+++ b/claude-ops/scripts/lib/competitor/hn-search.sh@@ -0,0 +1,85 @@+#!/usr/bin/env bash+# Hacker News signal collector for competitor intel v2.3+# Usage: hn-search.sh <brand-or-competitor-name> [--days N]+set -euo pipefail++LOG_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"+LOG_FILE="$LOG_DIR/competitor-hn.log"+mkdir -p "$LOG_DIR" 2>/dev/null || true++log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG_FILE" 2>/dev/null || true; }++if [[ $# -lt 1 ]]; then+ log "ERROR: missing competitor name arg"+ exit 0+fi++COMP="$1"; shift || true+DAYS=7+while [[ $# -gt 0 ]]; do+ case "$1" in+ --days) DAYS="${2:-7}"; shift 2 ;;+ *) shift ;;+ esac+done++# Compute UNIX timestamp N days ago (BSD + GNU date compatible)+if date -u -v-1d +%s >/dev/null 2>&1; then+ SINCE_TS=$(date -u -v-"${DAYS}"d +%s)+else+ SINCE_TS=$(date -u -d "${DAYS} days ago" +%s)+fi++UA="claude-ops-competitor-intel/2.3 (+https://github.com/Lifecycle-Innovations-Limited/claude-ops)"+QUERY=$(printf '%s' "$COMP" | jq -sRr @uri)+URL="https://hn.algolia.com/api/v1/search?query=${QUERY}&tags=story&numericFilters=created_at_i>${SINCE_TS}&hitsPerPage=20"++RESP=$(curl -sS --max-time 15 -A "$UA" -H "Accept: application/json" "$URL" 2>>"$LOG_FILE") || {+ log "ERROR: curl failed for query=$COMP"+ exit 0+}++if ! printf '%s' "$RESP" | jq -e '.hits' >/dev/null 2>&1; then+ log "ERROR: parse failed for query=$COMP (resp len=${#RESP})"+ exit 0+fi++NOW_ISO=$(date -u +%Y-%m-%dT%H:%M:%SZ)++printf '%s' "$RESP" | jq -c --arg comp "$COMP" --arg now "$NOW_ISO" '+ .hits[]?+ | {+ objectID: (.objectID // ""),+ title: (.title // ""),+ ext_url: (.url // ""),+ points: (.points // 0),+ num_comments: (.num_comments // 0),+ author: (.author // ""),+ story_text: (.story_text // "")+ }+ | . as $p+ | ($p.story_text | gsub("<[^>]+>"; "") | .[0:300]) as $snippet+ | (if ($p.points > 100 and $p.num_comments > 30) then "high"+ elif ($p.points > 30)+ or ($p.title | test("Show HN|Launch HN|is hiring"; "i")) then "med"+ else "low" end) as $sev+ | (if ($p.ext_url | length) > 0 then $p.ext_url+ else "https://news.ycombinator.com/item?id=" + $p.objectID end) as $url+ | {+ source: "hn",+ timestamp: $now,+ competitor: $comp,+ title: $p.title,+ url: $url,+ points: $p.points,+ num_comments: $p.num_comments,+ author: $p.author,+ severity: $sev,+ snippet: $snippet+ }+' 2>>"$LOG_FILE" || {+ log "ERROR: jq transform failed for query=$COMP"+ exit 0+}++exit 0diff --git a/claude-ops/scripts/lib/competitor/jobs-feed.sh b/claude-ops/scripts/lib/competitor/jobs-feed.shnew file mode 100755index 00000000..f7dbdcc7--- /dev/null+++ b/claude-ops/scripts/lib/competitor/jobs-feed.sh@@ -0,0 +1,123 @@+#!/usr/bin/env bash+# Public job-board signal collector for competitor intel v2.3+# Usage: jobs-feed.sh <competitor-company-slug> [--source greenhouse|lever|auto]+set -euo pipefail++LOG_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"+LOG_FILE="$LOG_DIR/competitor-jobs.log"+mkdir -p "$LOG_DIR" 2>/dev/null || true++log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG_FILE" 2>/dev/null || true; }++if [[ $# -lt 1 ]]; then+ log "ERROR: missing competitor slug arg"+ exit 0+fi++SLUG="$1"; shift || true+SOURCE="auto"+while [[ $# -gt 0 ]]; do+ case "$1" in+ --source) SOURCE="${2:-auto}"; shift 2 ;;+ *) shift ;;+ esac+done++UA="claude-ops-competitor-intel/2.3 (+https://github.com/Lifecycle-Innovations-Limited/claude-ops)"+NOW_ISO=$(date -u +%Y-%m-%dT%H:%M:%SZ)++fetch() {+ # $1 = url ; prints body, returns curl exit code; HTTP status appended on last line+ local url="$1" tmp status+ tmp=$(mktemp)+ status=$(curl -sS --max-time 15 -A "$UA" -H "Accept: application/json" -o "$tmp" -w '%{http_code}' "$url" 2>>"$LOG_FILE") || { rm -f "$tmp"; return 1; }+ cat "$tmp"; rm -f "$tmp"+ printf '\n%s' "$status"+}++emit_greenhouse() {+ local body="$1"+ printf '%s' "$body" | jq -c --arg comp "$SLUG" --arg now "$NOW_ISO" '+ .jobs[]?+ | {+ id: (.id | tostring),+ title: (.title // ""),+ location: ((.location.name // "") | tostring),+ department: ((.departments[0].name // "") | tostring),+ posted_at: (.updated_at // ""),+ url: (.absolute_url // ""),+ content: (.content // "")+ }+ | . as $j+ | ($j.content | gsub("<[^>]+>"; "") | gsub("&[a-z]+;"; " ") | gsub("\\s+"; " ") | .[0:200]) as $snip+ | (if ($j.title | test("VP|Head of|Director|Chief"; "i")) then "high"+ elif ($j.title | test("Founding"; "i")) then "med"+ else "low" end) as $sev+ | {source:"jobs", timestamp:$now, competitor:$comp, board:"greenhouse",+ posting_id:$j.id, title:$j.title, location:$j.location, department:$j.department,+ posted_at:$j.posted_at, url:$j.url, severity:$sev, snippet:$snip}+ ' 2>>"$LOG_FILE" || log "ERROR: greenhouse jq transform failed for slug=$SLUG"+}++emit_lever() {+ local body="$1"+ printf '%s' "$body" | jq -c --arg comp "$SLUG" --arg now "$NOW_ISO" '+ .[]?+ | {+ id: (.id // ""),+ title: (.text // ""),+ location: ((.categories.location // "") | tostring),+ department: ((.categories.team // "") | tostring),+ created_ms: (.createdAt // 0),+ url: (.hostedUrl // ""),+ desc: (.descriptionPlain // "")+ }+ | . as $j+ | ($j.desc | gsub("\\s+"; " ") | .[0:200]) as $snip+ | (if ($j.created_ms > 0) then ($j.created_ms / 1000 | strftime("%Y-%m-%dT%H:%M:%SZ")) else "" end) as $posted+ | (if ($j.title | test("VP|Head of|Director|Chief"; "i")) then "high"+ elif ($j.title | test("Founding"; "i")) then "med"+ else "low" end) as $sev+ | {source:"jobs", timestamp:$now, competitor:$comp, board:"lever",+ posting_id:$j.id, title:$j.title, location:$j.location, department:$j.department,+ posted_at:$posted, url:$j.url, severity:$sev, snippet:$snip}+ ' 2>>"$LOG_FILE" || log "ERROR: lever jq transform failed for slug=$SLUG"+}++try_greenhouse() {+ local url="https://boards-api.greenhouse.io/v1/boards/${SLUG}/jobs?content=true"+ local out status body+ out=$(fetch "$url") || { log "ERROR: curl failed greenhouse slug=$SLUG"; return 2; }+ status=$(printf '%s' "$out" | tail -n1)+ body=$(printf '%s' "$out" | sed '$d')+ case "$status" in+ 200) emit_greenhouse "$body"; return 0 ;;+ 404) return 1 ;;+ *) log "ERROR: greenhouse HTTP $status slug=$SLUG"; return 2 ;;+ esac+}++try_lever() {+ local url="https://api.lever.co/v0/postings/${SLUG}?mode=json"+ local out status body+ out=$(fetch "$url") || { log "ERROR: curl failed lever slug=$SLUG"; return 2; }+ status=$(printf '%s' "$out" | tail -n1)+ body=$(printf '%s' "$out" | sed '$d')+ case "$status" in+ 200) emit_lever "$body"; return 0 ;;+ 404) return 1 ;;+ *) log "ERROR: lever HTTP $status slug=$SLUG"; return 2 ;;+ esac+}++case "$SOURCE" in+ greenhouse) try_greenhouse || true ;;+ lever) try_lever || true ;;+ auto|*)+ if ! try_greenhouse; then+ try_lever || true+ fi+ ;;+esac++exit 0diff --git a/claude-ops/scripts/lib/competitor/page-diff.sh b/claude-ops/scripts/lib/competitor/page-diff.shnew file mode 100755index 00000000..c3aa4f96--- /dev/null+++ b/claude-ops/scripts/lib/competitor/page-diff.sh@@ -0,0 +1,173 @@+#!/usr/bin/env bash+# page-diff.sh — fetch a competitor URL, normalize, SHA, diff vs prior snapshot.+# Emits a JSONL event when the page has changed. Silent (exit 0, no output) when unchanged.+#+# Usage:+# page-diff.sh <brand> <competitor> <kind> <url>+# kind ∈ {pricing, features, careers, blog, changelog, other}+#+# State layout:+# $DATA_DIR/competitor_state/<brand>/<competitor>/snapshots/<kind>.<sha8>.txt+# $DATA_DIR/competitor_state/<brand>/<competitor>/snapshots/<kind>.latest # symlink+#+# Severity:+# high — pricing page changed AND diff touches a $€£ or /mo /yr token+# med — pricing/features/changelog changed (no money token), or careers added a role+# low — copy tweak, whitespace, or no signal worth alerting on+#+# Output (stdout, one line):+# {"source":"page-diff","timestamp":"…","competitor":"…","kind":"…","url":"…",+# "old_sha":"…","new_sha":"…","lines_changed":N,"severity":"…","snippet":"…"}++set -euo pipefail++BRAND="${1:?brand required}"+COMPETITOR="${2:?competitor required}"+KIND="${3:?kind required}"+URL="${4:?url required}"++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/competitor-page-diff.log"+mkdir -p "$LOG_DIR"+log() { printf '%s [page-diff] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"; }++# Slugify brand + competitor for filesystem safety+slug() { printf '%s' "$1" | tr '[:upper:] /' '[:lower:]--' | tr -cd 'a-z0-9-_.'; }+BRAND_SLUG=$(slug "$BRAND")+COMP_SLUG=$(slug "$COMPETITOR")+SNAP_DIR="$DATA_DIR/competitor_state/$BRAND_SLUG/$COMP_SLUG/snapshots"+mkdir -p "$SNAP_DIR"++# ── Fetch + normalize ────────────────────────────────────────────────────+# 30s timeout, follow redirects, modern UA so most sites don't 403.+HTML=$(curl -sSL \+ --max-time 30 \+ --retry 1 \+ --retry-delay 2 \+ -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605 (KHTML, like Gecko) Version/17 Safari/605 claude-ops-competitor-intel/2.3" \+ -H "Accept: text/html,application/xhtml+xml" \+ -H "Accept-Language: en-US,en;q=0.9" \+ "$URL" 2>>"$LOG" || true)++if [[ -z "$HTML" ]]; then+ log "FETCH_FAIL $BRAND/$COMPETITOR/$KIND $URL — empty body"+ exit 0+fi++# Normalize: strip <script>/<style>/<noscript> blocks, then strip all tags,+# collapse whitespace, drop blank lines. Keep money tokens intact.+NORMALIZER=$(mktemp)+cat > "$NORMALIZER" <<'PYEOF'+import sys, re+html = sys.stdin.read()+for tag in ("script", "style", "noscript", "svg"):+ html = re.sub(rf"<{tag}\b[^>]*>.*?</{tag}>", "", html, flags=re.DOTALL | re.IGNORECASE)+html = re.sub(r"<!--.*?-->", "", html, flags=re.DOTALL)+html = re.sub(r"</(p|div|section|article|li|h[1-6]|tr|br)>", "\n", html, flags=re.IGNORECASE)+html = re.sub(r"<br\s*/?>", "\n", html, flags=re.IGNORECASE)+html = re.sub(r"<[^>]+>", " ", html)+for old, new in ((" ", " "), ("&", "&"), ("<", "<"), (">", ">"), (""", '"'), ("'", "'")):+ html = html.replace(old, new)+out = []+for line in html.splitlines():+ s = re.sub(r"\s+", " ", line).strip()+ if len(s) >= 3:+ out.append(s)+print("\n".join(out))+PYEOF++NORMALIZED=$(printf '%s' "$HTML" | python3 "$NORMALIZER" 2>>"$LOG" || true)+rm -f "$NORMALIZER"++if [[ -z "$NORMALIZED" ]]; then+ log "NORMALIZE_FAIL $BRAND/$COMPETITOR/$KIND $URL"+ exit 0+fi++# ── SHA + diff ────────────────────────────────────────────────────────────+if command -v shasum >/dev/null 2>&1; then+ NEW_SHA=$(printf '%s' "$NORMALIZED" | shasum -a 256 | awk '{print $1}')+else+ NEW_SHA=$(printf '%s' "$NORMALIZED" | sha256sum | awk '{print $1}')+fi+NEW_SHA8="${NEW_SHA:0:8}"+NEW_FILE="$SNAP_DIR/$KIND.$NEW_SHA8.txt"+LATEST_LINK="$SNAP_DIR/$KIND.latest"++# First run for this URL — write baseline and exit (no event; nothing to compare)+if [[ ! -L "$LATEST_LINK" ]]; then+ printf '%s\n' "$NORMALIZED" > "$NEW_FILE"+ ln -sf "$NEW_FILE" "$LATEST_LINK"+ log "BASELINE $BRAND/$COMPETITOR/$KIND sha=$NEW_SHA8 (no event emitted on first run)"+ exit 0+fi++OLD_FILE=$(readlink "$LATEST_LINK")+[[ "$OLD_FILE" != /* ]] && OLD_FILE="$SNAP_DIR/$OLD_FILE"+OLD_SHA8=$(basename "$OLD_FILE" .txt | awk -F. '{print $NF}')++# No change → silent exit+if [[ "$NEW_SHA8" == "$OLD_SHA8" ]]; then+ exit 0+fi++# Compute diff stats + extract a snippet of changed lines+printf '%s\n' "$NORMALIZED" > "$NEW_FILE"+DIFF_OUT=$(diff -u "$OLD_FILE" "$NEW_FILE" 2>/dev/null || true)+LINES_CHANGED=$(printf '%s\n' "$DIFF_OUT" | grep -cE '^[+-][^+-]' || echo 0)+# Extract first 5 changed lines (skip diff header), cap to 400 chars total+CHANGED_SNIPPET=$(printf '%s\n' "$DIFF_OUT" | grep -E '^[+][^+]' | head -5 | sed 's/^+//' | tr '\n' ' ' | head -c 400)++# Detect money/pricing tokens in the changes (signal that pricing actually moved)+HAS_MONEY_TOKEN=0+if printf '%s' "$CHANGED_SNIPPET" | grep -qE '\$[0-9]+|€[0-9]+|£[0-9]+|[0-9]+\s*(USD|EUR|GBP)|\/(mo|month|yr|year)\b|free\s+trial|per\s+(seat|user)'; then+ HAS_MONEY_TOKEN=1+fi++# ── Severity classification ──────────────────────────────────────────────+SEVERITY=low+case "$KIND" in+ pricing)+ if (( HAS_MONEY_TOKEN == 1 )); then SEVERITY=high; else SEVERITY=med; fi+ ;;+ features|changelog)+ SEVERITY=med+ ;;+ careers)+ # Job postings count change → med if grew or any senior keyword in snippet+ if printf '%s' "$CHANGED_SNIPPET" | grep -qiE '\b(VP|head of|director|chief|founding|principal)\b'; then+ SEVERITY=high+ else+ SEVERITY=med+ fi+ ;;+esac++# Tiny diffs (< 3 lines changed) downgrade to low unless pricing+money+if (( LINES_CHANGED < 3 )) && [[ "$SEVERITY" != "high" ]]; then+ SEVERITY=low+fi++# Update latest pointer+ln -sf "$NEW_FILE" "$LATEST_LINK"++# Retention: keep last 12 snapshots per kind, drop older+find "$SNAP_DIR" -maxdepth 1 -name "$KIND.*.txt" -type f -print0 \+ | xargs -0 ls -t 2>/dev/null \+ | tail -n +13 \+ | while read -r old; do rm -f "$old"; done++# Emit event+jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \+ --arg comp "$COMPETITOR" \+ --arg kind "$KIND" \+ --arg url "$URL" \+ --arg old "$OLD_SHA8" \+ --arg new "$NEW_SHA8" \+ --argjson lc "${LINES_CHANGED:-0}" \+ --arg sev "$SEVERITY" \+ --arg snip "$CHANGED_SNIPPET" \+ '{source:"page-diff", timestamp:$ts, competitor:$comp, kind:$kind, url:$url, old_sha:$old, new_sha:$new, lines_changed:$lc, severity:$sev, snippet:$snip}'++log "DIFF $BRAND/$COMPETITOR/$KIND $OLD_SHA8 → $NEW_SHA8 lines=$LINES_CHANGED severity=$SEVERITY"diff --git a/claude-ops/scripts/lib/competitor/reddit-search.sh b/claude-ops/scripts/lib/competitor/reddit-search.shnew file mode 100755index 00000000..1f241b0b--- /dev/null+++ b/claude-ops/scripts/lib/competitor/reddit-search.sh@@ -0,0 +1,85 @@+#!/usr/bin/env bash+# Reddit signal collector for competitor intel v2.3+# Usage: reddit-search.sh <brand-or-competitor-name> [--days N]+set -euo pipefail++LOG_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"+LOG_FILE="$LOG_DIR/competitor-reddit.log"+mkdir -p "$LOG_DIR" 2>/dev/null || true++log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG_FILE" 2>/dev/null || true; }++if [[ $# -lt 1 ]]; then+ log "ERROR: missing competitor name arg"+ exit 0+fi++COMP="$1"; shift || true+DAYS=7+while [[ $# -gt 0 ]]; do+ case "$1" in+ --days) DAYS="${2:-7}"; shift 2 ;;+ *) shift ;;+ esac+done++# Map days to Reddit's t= window (week is the most useful default; clamp out-of-band values)+if [[ "$DAYS" -le 1 ]]; then T_WINDOW="day"+elif [[ "$DAYS" -le 7 ]]; then T_WINDOW="week"+elif [[ "$DAYS" -le 31 ]]; then T_WINDOW="month"+elif [[ "$DAYS" -le 365 ]]; then T_WINDOW="year"+else T_WINDOW="all"+fi++UA="claude-ops-competitor-intel/2.3 (+https://github.com/Lifecycle-Innovations-Limited/claude-ops)"+QUERY=$(printf '%s' "$COMP" | jq -sRr @uri)+URL="https://www.reddit.com/search.json?q=${QUERY}&t=${T_WINDOW}&limit=25&sort=new"++RESP=$(curl -sS --max-time 15 -A "$UA" -H "Accept: application/json" "$URL" 2>>"$LOG_FILE") || {+ log "ERROR: curl failed for query=$COMP"+ exit 0+}++if ! printf '%s' "$RESP" | jq -e '.data.children' >/dev/null 2>&1; then+ log "ERROR: parse failed for query=$COMP (resp len=${#RESP})"+ exit 0+fi++NOW_ISO=$(date -u +%Y-%m-%dT%H:%M:%SZ)++printf '%s' "$RESP" | jq -c --arg comp "$COMP" --arg now "$NOW_ISO" '+ .data.children[]?.data+ | {+ title: (.title // ""),+ permalink: (.permalink // ""),+ subreddit: (.subreddit // ""),+ score: (.score // 0),+ num_comments: (.num_comments // 0),+ selftext: (.selftext // ""),+ created_utc: (.created_utc // 0)+ }+ | . as $p+ | ($p.selftext | .[0:300]) as $snippet+ | ($p.title + " " + $p.selftext | ascii_downcase) as $hay+ | (if ($p.score > 100 and $p.num_comments > 20) then "high"+ elif ($p.score > 20)+ or ($hay | test("complaint|\\bvs\\b|alternative|switching from")) then "med"+ else "low" end) as $sev+ | {+ source: "reddit",+ timestamp: $now,+ competitor: $comp,+ title: $p.title,+ url: ("https://www.reddit.com" + $p.permalink),+ subreddit: $p.subreddit,+ score: $p.score,+ num_comments: $p.num_comments,+ severity: $sev,+ snippet: $snippet+ }+' 2>>"$LOG_FILE" || {+ log "ERROR: jq transform failed for query=$COMP"+ exit 0+}++exit 0diff --git a/claude-ops/scripts/ops-competitor-alert.sh b/claude-ops/scripts/ops-competitor-alert.shnew file mode 100644index 00000000..9b596356--- /dev/null+++ b/claude-ops/scripts/ops-competitor-alert.sh@@ -0,0 +1,90 @@+#!/usr/bin/env bash+# ops-competitor-alert.sh — Drain immediate.jsonl and dispatch high-severity alerts+#+# Runs every 10 minutes via daemon-services (competitor-alert entry).+# Telegram optional — always persists to disk as fallback.+#+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/competitor-alert.log"+QUEUE_DIR="$DATA_DIR/competitor_state/queue"+REPORT_DIR="$DATA_DIR/reports/competitor-intel"++mkdir -p "$LOG_DIR" "$QUEUE_DIR" "$REPORT_DIR"++log() { printf '%s [competitor-alert] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++# ── Credentials ───────────────────────────────────────────────────────────────+TELEGRAM_TOKEN="${TELEGRAM_BOT_TOKEN:-}"+TELEGRAM_CHAT="${TELEGRAM_CHAT_ID:-}"++if [[ -z "$TELEGRAM_TOKEN" ]]; then+ TELEGRAM_TOKEN=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)+fi+if [[ -z "$TELEGRAM_CHAT" ]]; then+ TELEGRAM_CHAT=$(doppler secrets get TELEGRAM_CHAT_ID --plain 2>/dev/null || true)+fi++# ── Queue state ───────────────────────────────────────────────────────────────+IMMEDIATE_QUEUE="$QUEUE_DIR/immediate.jsonl"+PROCESSED_QUEUE="$QUEUE_DIR/immediate.processed.jsonl"++if [[ ! -f "$IMMEDIATE_QUEUE" ]] || [[ ! -s "$IMMEDIATE_QUEUE" ]]; then+ log "HEARTBEAT_OK"+ exit 0+fi++# ── Alert log (dated rotating — one file per day) ─────────────────────────────+ALERT_LOG="$REPORT_DIR/alerts.log"+TODAY=$(date -u +%Y-%m-%d)+DATED_ALERT_LOG="$REPORT_DIR/alerts-${TODAY}.log"++# ── Process queue ─────────────────────────────────────────────────────────────+PROCESSED=0+FAILED=0++while IFS= read -r event; do+ [[ -z "$event" ]] && continue++ # Extract fields with jq, fallback to "?" on missing+ brand=$(printf '%s' "$event" | jq -r '.brand // .competitor // "?"' 2>/dev/null || echo "?")+ competitor=$(printf '%s' "$event" | jq -r '.competitor // "?"' 2>/dev/null || echo "?")+ source=$(printf '%s' "$event" | jq -r '.source // "?"' 2>/dev/null || echo "?")+ snippet=$(printf '%s' "$event" | jq -r '.snippet // ""' 2>/dev/null || echo "")+ ts=$(printf '%s' "$event" | jq -r '.timestamp // ""' 2>/dev/null || echo "")++ # Terse alert line+ alert_text="🔥 [HIGH] ${competitor} (${source}): ${snippet:0:200}"++ # Always write to disk alert logs+ printf '[%s] %s\n' "${ts:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}" "$alert_text" | tee -a "$ALERT_LOG" >> "$DATED_ALERT_LOG"++ # Telegram push if creds present+ if [[ -n "$TELEGRAM_TOKEN" && -n "$TELEGRAM_CHAT" ]]; then+ TG_RESP=$(curl -s --max-time 10 -X POST \+ "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \+ -H "Content-Type: application/json" \+ -d "$(jq -n --arg chat "$TELEGRAM_CHAT" --arg text "$alert_text" \+ '{chat_id: $chat, text: $text}')" 2>/dev/null || echo '{"ok":false}')+ if printf '%s' "$TG_RESP" | jq -e '.ok == true' >/dev/null 2>&1; then+ log "Telegram OK: $alert_text"+ else+ log "WARN: Telegram send failed — alert persisted to disk only"+ fi+ else+ log "INFO: Telegram not configured — alert saved to disk: $alert_text"+ fi++ # Append to processed archive+ printf '%s\n' "$event" >> "$PROCESSED_QUEUE"+ PROCESSED=$((PROCESSED + 1))++done < "$IMMEDIATE_QUEUE"++# Truncate the live queue after draining+: > "$IMMEDIATE_QUEUE"++log "Drained $PROCESSED event(s) from immediate queue"+log "HEARTBEAT_OK"diff --git a/claude-ops/scripts/ops-cron-competitor-daily.sh b/claude-ops/scripts/ops-cron-competitor-daily.shnew file mode 100644index 00000000..b7d10726--- /dev/null+++ b/claude-ops/scripts/ops-cron-competitor-daily.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# ops-cron-competitor-daily.sh — Daily 17:00 roll-up of med-severity competitor signals+#+# Drains queue/daily.jsonl, groups by competitor, writes a markdown roll-up,+# and pushes to Telegram if creds are present.+#+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/competitor-daily.log"+QUEUE_DIR="$DATA_DIR/competitor_state/queue"+REPORT_DIR="$DATA_DIR/reports/competitor-intel"+PREFS_PATH="$DATA_DIR/preferences.json"++mkdir -p "$LOG_DIR" "$QUEUE_DIR" "$REPORT_DIR"++log() { printf '%s [competitor-daily] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++# ── Credentials ───────────────────────────────────────────────────────────────+TELEGRAM_TOKEN="${TELEGRAM_BOT_TOKEN:-}"+TELEGRAM_CHAT="${TELEGRAM_CHAT_ID:-}"++if [[ -z "$TELEGRAM_TOKEN" ]]; then+ TELEGRAM_TOKEN=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)+fi+if [[ -z "$TELEGRAM_CHAT" ]]; then+ TELEGRAM_CHAT=$(doppler secrets get TELEGRAM_CHAT_ID --plain 2>/dev/null || true)+fi++# ── Config ────────────────────────────────────────────────────────────────────+pref_get() {+ local key="$1"+ [[ -f "$PREFS_PATH" ]] || { echo ""; return; }+ jq -r --arg k "$key" '.competitor_intel[$k] // ""' "$PREFS_PATH" 2>/dev/null || echo ""+}++BRAND_NAME="${BRAND_NAME:-$(pref_get brand_name)}"+BRAND_NAME="${BRAND_NAME:-Unknown Brand}"+REPORT_TIMEZONE="${REPORT_TIMEZONE:-$(pref_get report_timezone)}"+REPORT_TIMEZONE="${REPORT_TIMEZONE:-UTC}"++# ── Queue state ───────────────────────────────────────────────────────────────+DAILY_QUEUE="$QUEUE_DIR/daily.jsonl"++if [[ ! -f "$DAILY_QUEUE" ]] || [[ ! -s "$DAILY_QUEUE" ]]; then+ log "HEARTBEAT_OK"+ exit 0+fi++log "Draining daily queue for brand=$BRAND_NAME"++TODAY=$(TZ="$REPORT_TIMEZONE" date '+%Y-%m-%d')+REPORT_FILE="$REPORT_DIR/daily-${TODAY}.md"++# ── Build grouped report ──────────────────────────────────────────────────────+# Collect all events, group by competitor using jq slurp+ALL_EVENTS=$(cat "$DAILY_QUEUE")++EVENT_COUNT=$(printf '%s\n' "$ALL_EVENTS" | grep -c '^{' 2>/dev/null || echo 0)+log "Processing $EVENT_COUNT med-severity event(s)"++# Group by competitor → top 3–5 snippets per competitor+GROUPED=$(printf '%s\n' "$ALL_EVENTS" | jq -s '+ group_by(.competitor)+ | map({+ competitor: .[0].competitor,+ events: (+ sort_by(.timestamp) | reverse+ | .[0:5]+ | map("- [" + (.source // "?") + "] " + (.snippet // "")[0:180])+ )+ })+ | sort_by(.competitor)+' 2>/dev/null || echo "[]")++COMPETITOR_COUNT=$(printf '%s' "$GROUPED" | jq 'length' 2>/dev/null || echo 0)++# ── Write markdown report ─────────────────────────────────────────────────────+{+ printf '# %s Competitor Intel — Daily Roll-up\n' "$BRAND_NAME"+ printf '**Date:** %s \n' "$(TZ="$REPORT_TIMEZONE" date '+%a %d %b %Y %H:%M %Z')"+ printf '**Signals:** %s med-severity events across %s competitor(s)\n\n' "$EVENT_COUNT" "$COMPETITOR_COUNT"+ printf '---\n\n'++ if [[ "$COMPETITOR_COUNT" -eq 0 ]]; then+ printf '_No med-severity signals in queue._\n'+ else+ printf '%s' "$GROUPED" | jq -r '.[] | "## \(.competitor)\n\n" + (.events | join("\n")) + "\n"' 2>/dev/null || true+ fi++ printf '\n---\n_Generated by ops-cron-competitor-daily.sh at %s_\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+} > "$REPORT_FILE"++log "Report written to $REPORT_FILE"++# Update latest symlink+ln -sf "$REPORT_FILE" "$REPORT_DIR/latest-daily.md"++# ── Telegram push ─────────────────────────────────────────────────────────────+if [[ -n "$TELEGRAM_TOKEN" && -n "$TELEGRAM_CHAT" ]]; then+ # Compact Telegram summary (Telegram has 4096-char limit)+ TG_SUMMARY=$(printf '*%s Competitor Daily — %s*\n%s signals, %s competitor(s)\n\n' \+ "$BRAND_NAME" "$TODAY" "$EVENT_COUNT" "$COMPETITOR_COUNT")++ TOP_BULLETS=$(printf '%s' "$GROUPED" | jq -r '+ .[0:5]+ | .[]+ | "• *" + .competitor + "*: " + (.events[0] // "no detail")+ ' 2>/dev/null | head -5 || true)++ TG_TEXT="${TG_SUMMARY}${TOP_BULLETS}"+ TG_TEXT="${TG_TEXT:0:4000}"++ TG_RESP=$(curl -s --max-time 15 -X POST \+ "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \+ -H "Content-Type: application/json" \+ -d "$(jq -n --arg chat "$TELEGRAM_CHAT" --arg text "$TG_TEXT" \+ '{chat_id: $chat, text: $text, parse_mode: "Markdown"}')" 2>/dev/null || echo '{"ok":false}')++ if printf '%s' "$TG_RESP" | jq -e '.ok == true' >/dev/null 2>&1; then+ log "Telegram digest sent to chat=$TELEGRAM_CHAT"+ else+ log "WARN: Telegram send failed — report saved to disk only ($REPORT_FILE)"+ fi+else+ log "INFO: Telegram not configured — report saved to disk only ($REPORT_FILE)"+fi++# ── Truncate queue after processing ──────────────────────────────────────────+: > "$DAILY_QUEUE"+log "Daily queue truncated"+log "HEARTBEAT_OK"diff --git a/claude-ops/scripts/ops-cron-competitor-intel.sh b/claude-ops/scripts/ops-cron-competitor-intel.shindex cbcd5a8b..d035f3c9 100755--- a/claude-ops/scripts/ops-cron-competitor-intel.sh+++ b/claude-ops/scripts/ops-cron-competitor-intel.sh@@ -1,19 +1,22 @@#!/usr/bin/env bash-# ops-cron-competitor-intel.sh — Weekly self-discovering competitor intel+# ops-cron-competitor-intel.sh v2.3 — Weekly Monday 10:00 Europe/Amsterdam+# strategic synthesis cron.## Pipeline (per brand seed):-# 1. Tavily discovery → top competitors to {brand} in {category}-# 2. State merge → diff vs competitor_state.json, flag NEW entrants-# 3. Tavily news pass → recent moves per top-5 competitor (last 7d)-# 4. Tavily brand pass → own-brand reviews / mentions-# 5. LLM synthesis → claude_invoke (Sonnet) one-page strategic delta-# 6. Telegram digest + persist new state for next week's delta+# 1. Discovery (cached 30d) — Tavily landscape search+# 2. Per-competitor signal collect — reddit/hn/appstore/jobs/page-diff (parallel)+# 3. Brand mentions — Tavily news (last 7d) + route+# 4. Event log read — last 7d from events.jsonl+# 5. LLM synthesis — Sonnet, fenced-JSON extraction+# 6. State persist + disk report — symlink + optional Telegram## Config (preferences.json → .competitor_intel):-# brand_name — e.g. "My-Project" (REQUIRED)+# brand_name — e.g. "My-Project" (REQUIRED)# category — e.g. "AI health coaching apps" (REQUIRED)# max_competitors — int, default 5# report_timezone — IANA TZ, default UTC+# app_store — bool, enable appstore-lookup collectors+# urls — object: {<CompetitorName>: {pricing:"...",features:"...",careers:"..."}}## Env overrides: BRAND_NAME, BRAND_CATEGORY, MAX_COMPETITORS, REPORT_TIMEZONE#@@ -25,8 +28,10 @@ LOG_DIR="$DATA_DIR/logs"LOG="$LOG_DIR/competitor-intel.log"PREFS_PATH="$DATA_DIR/preferences.json"STATE_PATH="$DATA_DIR/competitor_state.json"+EVENTS_PATH="$DATA_DIR/competitor_state/events.jsonl"+LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/lib/competitor" 2>/dev/null && pwd || echo "$HOME/.claude/plugins/cache/ops-marketplace/ops/scripts/lib/competitor")"-mkdir -p "$LOG_DIR"+mkdir -p "$LOG_DIR" "$DATA_DIR/competitor_state" "$DATA_DIR/reports/competitor-intel"log() { printf '%s [competitor-intel] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }# ── Resolve config ────────────────────────────────────────────────────────@@ -43,6 +48,13 @@ REPORT_TIMEZONE="${REPORT_TIMEZONE:-$(pref_get report_timezone)}"MAX_COMPETITORS="${MAX_COMPETITORS:-5}"REPORT_TIMEZONE="${REPORT_TIMEZONE:-UTC}"+# App Store enabled flag+APP_STORE_ENABLED=false+if [[ -f "$PREFS_PATH" ]]; then+ _as=$(jq -r '.competitor_intel.app_store // false' "$PREFS_PATH" 2>/dev/null || echo "false")+ [[ "$_as" == "true" ]] && APP_STORE_ENABLED=true+fi+if [[ -z "$BRAND_NAME" || -z "$BRAND_CATEGORY" ]]; thenlog "SKIP: brand_name + category not configured in preferences.json. Run /ops:setup."log "HEARTBEAT_OK"@@ -54,103 +66,228 @@ TELEGRAM_TOKEN="${TELEGRAM_BOT_TOKEN:-}"TELEGRAM_CHAT="${TELEGRAM_CHAT_ID:-}"TAVILY_KEY="${TAVILY_API_KEY:-}"-if [[ -z "$TELEGRAM_TOKEN" ]]; then- TELEGRAM_TOKEN=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)-fi-if [[ -z "$TAVILY_KEY" ]]; then- TAVILY_KEY=$(doppler secrets get TAVILY_API_KEY --plain 2>/dev/null || true)-fi+[[ -z "$TELEGRAM_TOKEN" ]] && TELEGRAM_TOKEN=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)+[[ -z "$TAVILY_KEY" ]] && TAVILY_KEY=$(doppler secrets get TAVILY_API_KEY --plain 2>/dev/null || true)-if [[ -z "$TAVILY_KEY" ]]; then- log "SKIP: TAVILY_API_KEY not available — can't run intelligent search."- log "HEARTBEAT_OK"- exit 0+# Load event router if available+ROUTER_SH="$LIB_DIR/event-router.sh"+HAS_ROUTER=false+if [[ -f "$ROUTER_SH" ]]; then+ # shellcheck disable=SC1090+ . "$ROUTER_SH" && HAS_ROUTER=true || truefi+route_event() {+ # Pipe stdin JSONL through router if loaded; else append directly to events.jsonl+ if $HAS_ROUTER; then+ route_event_fn # function from event-router.sh; reads stdin+ else+ tee -a "$EVENTS_PATH"+ fi+}+YEAR=$(date +%Y)+NOW_EPOCH=$(date -u +%s)# ── Tavily helpers ────────────────────────────────────────────────────────tavily_search() {- # $1=query, $2=depth(basic|advanced), $3=topic(general|news), $4=dayslocal query="$1" depth="${2:-basic}" topic="${3:-general}" days="${4:-30}"local payloadpayload=$(jq -n --arg q "$query" --arg d "$depth" --arg t "$topic" --argjson days "$days" \'{query:$q, search_depth:$d, topic:$t, max_results:5, days:$days}')-curl -s -X POST "https://api.tavily.com/search" \-H "Content-Type: application/json" \-H "Authorization: Bearer ${TAVILY_KEY}" \-d "$payload" 2>/dev/null || echo '{"results":[]}'}-# ── Stage 1: Discovery — surface current competitor landscape ─────────────-log "Stage 1: discovering competitors to '$BRAND_NAME' in category '$BRAND_CATEGORY'"-DISCOVERY_QUERY="Top competitors to $BRAND_NAME in $BRAND_CATEGORY market $YEAR — list company names"-DISCOVERY_JSON=$(tavily_search "$DISCOVERY_QUERY" "advanced" "general" 90)-DISCOVERY_TEXT=$(echo "$DISCOVERY_JSON" | jq -r '.results[]? | "[\(.title // "?")] \((.content // "")[:400])"' 2>/dev/null | head -c 6000)--# ── Stage 2: Load prior state ─────────────────────────────────────────────+# ── Stage 1: Discovery (cached 30d) ──────────────────────────────────────KNOWN_COMPETITORS="[]"+LAST_DISCOVERY=""if [[ -f "$STATE_PATH" ]]; thenKNOWN_COMPETITORS=$(jq -r --arg b "$BRAND_NAME" '.[$b].competitors // []' "$STATE_PATH" 2>/dev/null || echo "[]")+ LAST_DISCOVERY=$(jq -r --arg b "$BRAND_NAME" '.[$b].last_discovery // ""' "$STATE_PATH" 2>/dev/null || echo "")+fi++DISCOVERY_TEXT=""+NEED_DISCOVERY=true++# Check if 30d cache is still valid+if [[ -n "$LAST_DISCOVERY" ]]; then+ # BSD date -j; fallback to GNU date -d+ DISC_EPOCH=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$LAST_DISCOVERY" +%s 2>/dev/null \+ || date -d "$LAST_DISCOVERY" +%s 2>/dev/null || echo 0)+ AGE_DAYS=$(( (NOW_EPOCH - DISC_EPOCH) / 86400 ))+ if (( AGE_DAYS < 30 )) && [[ "$KNOWN_COMPETITORS" != "[]" ]]; then+ NEED_DISCOVERY=false+ log "Stage 1: discovery cache valid (${AGE_DAYS}d old, next refresh in $((30 - AGE_DAYS))d)"+ fi+fi++if $NEED_DISCOVERY; then+ if [[ -z "$TAVILY_KEY" ]]; then+ if [[ "$KNOWN_COMPETITORS" == "[]" ]]; then+ log "SKIP: TAVILY_API_KEY missing and no cached competitors — nothing to process."+ log "HEARTBEAT_OK"+ exit 0+ fi+ log "Stage 1: TAVILY_API_KEY missing — skipping discovery, using cached competitors"+ NEED_DISCOVERY=false+ else+ log "Stage 1: running Tavily discovery for '$BRAND_NAME' in '$BRAND_CATEGORY'"+ DISC_JSON=$(tavily_search \+ "Top competitors to $BRAND_NAME in $BRAND_CATEGORY market $YEAR — list company names" \+ "advanced" "general" 90)+ DISCOVERY_TEXT=$(printf '%s' "$DISC_JSON" \+ | jq -r '.results[]? | "[\(.title // "?")] \((.content // "")[:400])"' 2>/dev/null \+ | head -c 6000)+ fifi-log "Stage 2: $(echo "$KNOWN_COMPETITORS" | jq 'length // 0' 2>/dev/null || echo 0) competitors in prior state"--# ── Stage 3: Brand mentions (own reviews/news) ────────────────────────────-log "Stage 3: scanning brand mentions for '$BRAND_NAME'"-BRAND_NEWS_JSON=$(tavily_search "$BRAND_NAME reviews OR mentions OR launch OR funding" "basic" "news" 7)-BRAND_TEXT=$(echo "$BRAND_NEWS_JSON" | jq -r '.results[]? | "[\(.title // "?")] \((.content // "")[:300])"' 2>/dev/null | head -c 4000)--# ── Stage 4: Recent moves per known competitor (cap at MAX_COMPETITORS) ───-COMPETITOR_MOVES=""-if [[ "$KNOWN_COMPETITORS" != "[]" && "$KNOWN_COMPETITORS" != "" ]]; then- log "Stage 4: scanning recent moves for known competitors"- while IFS= read -r comp; do- [[ -z "$comp" ]] && continue- NEWS_JSON=$(tavily_search "$comp pricing OR launch OR funding OR product $YEAR" "basic" "news" 7)- SNIP=$(echo "$NEWS_JSON" | jq -r '.results[]? | " • \(.title // "?"): \((.content // "")[:200])"' 2>/dev/null | head -3)- [[ -n "$SNIP" ]] && COMPETITOR_MOVES+=$'\n## '"$comp"$'\n'"$SNIP"$'\n'- done < <(echo "$KNOWN_COMPETITORS" | jq -r '.[]?' 2>/dev/null | head -n "$MAX_COMPETITORS")++log "Stage 1: $(printf '%s' "$KNOWN_COMPETITORS" | jq 'length // 0' 2>/dev/null || echo 0) competitors in prior state"++# ── Stage 2: Per-competitor parallel signal collection ────────────────────+log "Stage 2: parallel signal collection begins"+TMP_EVENTS_DIR=$(mktemp -d)++collect_competitor() {+ local comp="$1"+ local out_file="$TMP_EVENTS_DIR/$(printf '%s' "$comp" | tr -cd 'a-zA-Z0-9_-' | head -c 40).jsonl"++ # reddit + hn always+ timeout 30 bash "$LIB_DIR/reddit-search.sh" "$comp" --days 7 >> "$out_file" 2>/dev/null || true+ timeout 30 bash "$LIB_DIR/hn-search.sh" "$comp" --days 7 >> "$out_file" 2>/dev/null || true++ # appstore only if enabled in prefs+ if $APP_STORE_ENABLED; then+ timeout 30 bash "$LIB_DIR/appstore-lookup.sh" "$comp" >> "$out_file" 2>/dev/null || true+ fi++ # jobs-feed — derive slug: lowercase + hyphenate spaces/slashes+ local slug+ slug=$(printf '%s' "$comp" | tr '[:upper:] /' '[:lower:]--' | tr -cd 'a-z0-9-')+ timeout 30 bash "$LIB_DIR/jobs-feed.sh" "$slug" >> "$out_file" 2>/dev/null || true++ # page-diff for each URL kind defined in prefs under .competitor_intel.urls.<comp>+ if [[ -f "$PREFS_PATH" ]]; then+ local url_kinds=("pricing" "features" "careers")+ for kind in "${url_kinds[@]}"; do+ local url+ url=$(jq -r --arg c "$comp" --arg k "$kind" \+ '.competitor_intel.urls[$c][$k] // ""' "$PREFS_PATH" 2>/dev/null || echo "")+ if [[ -n "$url" ]]; then+ timeout 30 bash "$LIB_DIR/page-diff.sh" "$BRAND_NAME" "$comp" "$kind" "$url" \+ >> "$out_file" 2>/dev/null || true+ fi+ done+ fi+}++PIDS=()+while IFS= read -r comp; do+ [[ -z "$comp" ]] && continue+ collect_competitor "$comp" &+ PIDS+=($!)+done < <(printf '%s' "$KNOWN_COMPETITORS" | jq -r '.[]?' 2>/dev/null | head -n "$MAX_COMPETITORS")++# Wait for all background collectors+for pid in "${PIDS[@]:-}"; do+ wait "$pid" 2>/dev/null || true+done++# Route all collected events through the event router + accumulate for prompt+EVENTS_JSONL=""+for f in "$TMP_EVENTS_DIR"/*.jsonl; do+ [[ -f "$f" ]] || continue+ while IFS= read -r line; do+ [[ -z "$line" ]] && continue+ printf '%s\n' "$line" | route_event || true+ EVENTS_JSONL+="$line"$'\n'+ done < "$f"+done+rm -rf "$TMP_EVENTS_DIR"++log "Stage 2: signal collection complete ($(printf '%s' "$EVENTS_JSONL" | grep -c . || echo 0) events collected)"++# ── Stage 3: Brand mentions ───────────────────────────────────────────────+BRAND_TEXT=""+if [[ -n "$TAVILY_KEY" ]]; then+ log "Stage 3: scanning brand mentions for '$BRAND_NAME'"+ BRAND_NEWS_JSON=$(tavily_search \+ "$BRAND_NAME reviews OR mentions OR launch OR funding" "basic" "news" 7)+ BRAND_TEXT=$(printf '%s' "$BRAND_NEWS_JSON" \+ | jq -r '.results[]? | "[\(.title // "?")] \((.content // "")[:300])"' 2>/dev/null \+ | head -c 4000)++ # Route brand mention events+ if $HAS_ROUTER; then+ printf '%s' "$BRAND_NEWS_JSON" | jq -c --arg b "$BRAND_NAME" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \+ '.results[]? | {source:"tavily-brand",timestamp:$ts,competitor:$b,title:.title,url:.url,severity:"low",snippet:(.content // "" | .[0:200])}' \+ 2>/dev/null | route_event || true+ fi+else+ log "Stage 3: SKIP brand mentions (no TAVILY_KEY)"fi-# ── Stage 5: LLM synthesis — strategic delta report ───────────────────────+# ── Stage 4: Read past 7d of events from events.jsonl ────────────────────+log "Stage 4: reading 7d event log"+CUTOFF_EPOCH=$((NOW_EPOCH - 7 * 86400))+AUDIT_EVENTS=""+if [[ -f "$EVENTS_PATH" ]]; then+ AUDIT_EVENTS=$(jq -rc --argjson cut "$CUTOFF_EPOCH" '+ select(.timestamp? != null)+ | select(+ (.timestamp | strptime("%Y-%m-%dT%H:%M:%SZ") | mktime) >= $cut+ )+ ' "$EVENTS_PATH" 2>/dev/null | head -c 100000 || true)+fi+EVENT_COUNT=$(printf '%s' "$AUDIT_EVENTS" | grep -c . || echo 0)+log "Stage 4: $EVENT_COUNT events in 7d window"++# Merge collector events into audit log view (they may not be flushed yet)+if [[ -n "$EVENTS_JSONL" ]]; then+ AUDIT_EVENTS="${AUDIT_EVENTS}"$'\n'"${EVENTS_JSONL}"+fi+# Cap total prompt input+AUDIT_EVENTS=$(printf '%s' "$AUDIT_EVENTS" | head -c 100000)++# ── Stage 5: LLM synthesis ───────────────────────────────────────────────log "Stage 5: LLM synthesis (Sonnet)"NEW_STATE_COMPETITORS="$KNOWN_COMPETITORS"REPORT=""+SYNTHESIS=""# shellcheck disable=SC1091if [[ -f "$PLUGIN_ROOT/scripts/lib/claude-invoke.sh" ]]; then. "$PLUGIN_ROOT/scripts/lib/claude-invoke.sh"PROMPT_FILE=$(mktemp)- cat > "$PROMPT_FILE" <<EOF-You are a strategic competitor intelligence analyst.+ SYSTEM_PROMPT="You are a senior strategic competitor intelligence analyst. Be concise, specific, and action-oriented. Avoid generic summaries."+ cat > "$PROMPT_FILE" <<EOFBrand: $BRAND_NAMECategory: $BRAND_CATEGORY-Date: $(TZ="$REPORT_TIMEZONE" date '+%Y-%m-%d')-Previously known competitors: $(echo "$KNOWN_COMPETITORS" | jq -c '.' 2>/dev/null || echo "[]")+Report date: $(TZ="$REPORT_TIMEZONE" date '+%Y-%m-%d')+Previously known competitors: $(printf '%s' "$KNOWN_COMPETITORS" | jq -c '.' 2>/dev/null || echo "[]")-## Raw Tavily research+## Discovery research (Tavily, current landscape):+${DISCOVERY_TEXT:-[skipped — cached competitor list used]}-### Discovery pass (current landscape):-$DISCOVERY_TEXT+## Brand mentions (last 7d):+${BRAND_TEXT:-[skipped — no Tavily key]}-### Brand mentions (last 7 days, $BRAND_NAME):-$BRAND_TEXT--### Recent competitor moves (last 7 days):-$COMPETITOR_MOVES+## Signal event log (last 7d, JSONL):+${AUDIT_EVENTS:-[no events]}## Your tasks-1. Extract the canonical competitor list from the Discovery pass — return ONLY actual product/company names, not generic categories. Cap at $MAX_COMPETITORS.-2. Identify NEW entrants (in current list but not in "Previously known competitors").-3. Identify DROPPED competitors (in prior list but absent from current landscape).-4. Synthesize a one-page strategic delta. Skip filler. Strategic, not generic.+1. Extract the canonical competitor list from Discovery + events — real product/company names only, no categories. Cap at $MAX_COMPETITORS.+2. Identify NEW entrants vs "Previously known competitors".+3. Identify DROPPED competitors (in prior list, absent now).+4. Synthesize a one-page strategic delta — skip filler, be strategic.-Output format (STRICT — must be parseable):+Output format (STRICT):\`\`\`json{"competitors": ["name1","name2"]}@@ -172,37 +309,61 @@ Output format (STRICT — must be parseable):...EOF- SYNTHESIS=$(claude_invoke --model claude-sonnet-4-6 --no-session-persistence -p < "$PROMPT_FILE" 2>>"$LOG" || echo "")+ SYNTHESIS=$(claude_invoke --model claude-sonnet-4-6 --no-session-persistence \+ --system "$SYSTEM_PROMPT" -p < "$PROMPT_FILE" 2>>"$LOG" || echo "")rm -f "$PROMPT_FILE"+else+ log "WARN: claude-invoke.sh not found at $PLUGIN_ROOT — using Tavily-only fallback"+fi- if [[ -n "$SYNTHESIS" ]]; then- # Try three JSON-extraction strategies in order of strictness- EXTRACTED=""- # 1. Fenced ```json block- CAND=$(echo "$SYNTHESIS" | sed -n '/```json/,/```/p' | sed '1d;$d' | jq -r '.competitors // empty' 2>/dev/null || true)+# Persist raw synthesis immediately so partial output is never lost+REPORT_DIR="$DATA_DIR/reports/competitor-intel"+BRAND_SLUG=$(printf '%s' "$BRAND_NAME" | tr '[:upper:] ' '[:lower:]-')+SYNTHESIS_FILE="$REPORT_DIR/$(date +%Y-%m-%d)_${BRAND_SLUG}-synthesis.md"+if [[ -n "$SYNTHESIS" ]]; then+ printf '%s\n' "$SYNTHESIS" > "$SYNTHESIS_FILE"+ log "Raw synthesis persisted to $SYNTHESIS_FILE"+fi++# ── JSON + report extraction ──────────────────────────────────────────────+if [[ -n "$SYNTHESIS" ]]; then+ EXTRACTED=""+ # 1. Fenced ```json block+ CAND=$(printf '%s' "$SYNTHESIS" | sed -n '/```json/,/```/p' | sed '1d;$d' \+ | jq -r '.competitors // empty' 2>/dev/null || true)+ [[ -n "$CAND" && "$CAND" != "null" && "$CAND" != "[]" ]] && EXTRACTED="$CAND"++ # 2. Bare {"competitors":[...]} anywhere in output+ if [[ -z "$EXTRACTED" ]]; then+ CAND=$(printf '%s' "$SYNTHESIS" \+ | grep -oE '\{"competitors":\s*\[[^]]*\][^}]*\}' | head -1 \+ | jq -r '.competitors // empty' 2>/dev/null || true)[[ -n "$CAND" && "$CAND" != "null" && "$CAND" != "[]" ]] && EXTRACTED="$CAND"- # 2. Bare {"competitors":[...]} anywhere in output (no fence)- if [[ -z "$EXTRACTED" ]]; then- CAND=$(echo "$SYNTHESIS" | grep -oE '\{"competitors":\s*\[[^]]*\][^}]*\}' | head -1 | jq -r '.competitors // empty' 2>/dev/null || true)- [[ -n "$CAND" && "$CAND" != "null" && "$CAND" != "[]" ]] && EXTRACTED="$CAND"- fi- # 3. Greedy bullet-list scrape from "NEW entrants" or "Competitor moves" sections- if [[ -z "$EXTRACTED" ]]; then- CAND=$(echo "$SYNTHESIS" | awk '/[Cc]ompetitor|[Ee]ntrant/{flag=1} flag && /^\s*[-•*]\s*\*?\*?[A-Z][A-Za-z0-9 .&-]+/' | grep -oE '\*?\*?[A-Z][A-Za-z0-9 .&-]{2,30}\*?\*?' | sed 's/\*//g; s/^[[:space:]]*//; s/[[:space:]]*$//' | sort -u | head -10 | jq -R . | jq -s . 2>/dev/null || true)- [[ -n "$CAND" && "$CAND" != "null" && "$CAND" != "[]" ]] && EXTRACTED="$CAND"- fi- [[ -n "$EXTRACTED" ]] && NEW_STATE_COMPETITORS="$EXTRACTED"-- # Report extraction: prefer ---REPORT--- marker; otherwise strip JSON block- # and use whatever LLM produced — do NOT silently fall back to raw Tavily.- REPORT=$(echo "$SYNTHESIS" | awk '/---REPORT---/{flag=1; next} flag' | sed '/^```/,/^```$/d')- if [[ -z "$REPORT" ]]; then- REPORT=$(echo "$SYNTHESIS" | sed -E '/^```(json)?$/,/^```$/d')- log "WARN: ---REPORT--- marker missing in LLM output — using full synthesis as report"- fifi-else- log "WARN: claude-invoke.sh not found at $PLUGIN_ROOT — using Tavily-only fallback"++ # 3. Greedy bullet-list scrape from competitor/entrant sections+ if [[ -z "$EXTRACTED" ]]; then+ CAND=$(printf '%s' "$SYNTHESIS" \+ | awk '/[Cc]ompetitor|[Ee]ntrant/{flag=1} flag && /^\s*[-•*]\s*\*?\*?[A-Z][A-Za-z0-9 .&-]+/' \+ | grep -oE '\*?\*?[A-Z][A-Za-z0-9 .&-]{2,30}\*?\*?' \+ | sed 's/\*//g; s/^[[:space:]]*//; s/[[:space:]]*$//' \+ | sort -u | head -10 | jq -R . | jq -s . 2>/dev/null || true)+ [[ -n "$CAND" && "$CAND" != "null" && "$CAND" != "[]" ]] && EXTRACTED="$CAND"+ fi++ [[ -n "$EXTRACTED" ]] && NEW_STATE_COMPETITORS="$EXTRACTED"++ # Dedup + cap competitor list+ NEW_STATE_COMPETITORS=$(printf '%s' "$NEW_STATE_COMPETITORS" \+ | jq -c --argjson max "$MAX_COMPETITORS" 'unique | .[0:$max]' 2>/dev/null \+ || echo "$NEW_STATE_COMPETITORS")++ # Extract report section+ REPORT=$(printf '%s' "$SYNTHESIS" | awk '/---REPORT---/{flag=1; next} flag' | sed '/^```/,/^```$/d')+ if [[ -z "$REPORT" ]]; then+ REPORT=$(printf '%s' "$SYNTHESIS" | sed -E '/^```(json)?$/,/^```$/d')+ log "WARN: ---REPORT--- marker missing — using full synthesis as report"+ fifi# Fallback report if LLM unavailable or returned empty@@ -213,39 +374,55 @@ if [[ -z "$REPORT" ]]; then${DISCOVERY_TEXT:0:1200}*Brand mentions (raw):*-${BRAND_TEXT:0:1200}"+${BRAND_TEXT:0:1200}++*Signal events (raw, $EVENT_COUNT in 7d):*+$(printf '%s' "$AUDIT_EVENTS" | head -c 800)"fi-# ── Persist state ─────────────────────────────────────────────────────────+# ── Stage 6: Persist state ────────────────────────────────────────────────+LAST_DISC_TS="$LAST_DISCOVERY"+$NEED_DISCOVERY && LAST_DISC_TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+NOW_TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+TMP_STATE=$(mktemp)if [[ -f "$STATE_PATH" ]]; then- jq --arg b "$BRAND_NAME" --argjson c "$NEW_STATE_COMPETITORS" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \- '.[$b] = {competitors: $c, last_run: $ts}' "$STATE_PATH" > "$TMP_STATE" 2>/dev/null \- || jq -n --arg b "$BRAND_NAME" --argjson c "$NEW_STATE_COMPETITORS" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \- '{($b): {competitors: $c, last_run: $ts}}' > "$TMP_STATE"+ jq --arg b "$BRAND_NAME" \+ --argjson c "$NEW_STATE_COMPETITORS" \+ --arg ts "$NOW_TS" \+ --arg ld "$LAST_DISC_TS" \+ --argjson as "$APP_STORE_ENABLED" \+ '.[$b] = (.[$b] // {}) + {competitors:$c, last_run:$ts, last_discovery:$ld, app_store_enabled:$as}' \+ "$STATE_PATH" > "$TMP_STATE" 2>/dev/null \+ || jq -n --arg b "$BRAND_NAME" \+ --argjson c "$NEW_STATE_COMPETITORS" \+ --arg ts "$NOW_TS" \+ --arg ld "$LAST_DISC_TS" \+ --argjson as "$APP_STORE_ENABLED" \+ '{($b): {competitors:$c, last_run:$ts, last_discovery:$ld, app_store_enabled:$as}}' > "$TMP_STATE"else- jq -n --arg b "$BRAND_NAME" --argjson c "$NEW_STATE_COMPETITORS" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \- '{($b): {competitors: $c, last_run: $ts}}' > "$TMP_STATE"+ jq -n --arg b "$BRAND_NAME" \+ --argjson c "$NEW_STATE_COMPETITORS" \+ --arg ts "$NOW_TS" \+ --arg ld "$LAST_DISC_TS" \+ --argjson as "$APP_STORE_ENABLED" \+ '{($b): {competitors:$c, last_run:$ts, last_discovery:$ld, app_store_enabled:$as}}' > "$TMP_STATE"fimv "$TMP_STATE" "$STATE_PATH"-log "State persisted: $(echo "$NEW_STATE_COMPETITORS" | jq 'length // 0' 2>/dev/null || echo 0) competitors tracked for $BRAND_NAME"+log "State persisted: $(printf '%s' "$NEW_STATE_COMPETITORS" | jq 'length // 0' 2>/dev/null || echo 0) competitors tracked for $BRAND_NAME"-# ── Stage 6: Persist report to disk (always) + push to Telegram (if creds) ─-REPORT_DIR="$DATA_DIR/reports/competitor-intel"-mkdir -p "$REPORT_DIR"-REPORT_FILE="$REPORT_DIR/$(date +%Y-%m-%d)_$(echo "$BRAND_NAME" | tr '[:upper:] ' '[:lower:]-').md"+# ── Disk report (always) + symlink ───────────────────────────────────────+REPORT_FILE="$REPORT_DIR/$(date +%Y-%m-%d)_${BRAND_SLUG}.md"printf '%s\n' "$REPORT" > "$REPORT_FILE"+ln -sf "$REPORT_FILE" "$REPORT_DIR/latest-${BRAND_SLUG}.md"log "Report written to $REPORT_FILE"-# Update latest pointer for easy access-ln -sf "$REPORT_FILE" "$REPORT_DIR/latest-$(echo "$BRAND_NAME" | tr '[:upper:] ' '[:lower:]-').md"--log "Stage 6: dispatching Telegram digest"+# ── Telegram (additive) ───────────────────────────────────────────────────if [[ -n "$TELEGRAM_TOKEN" && -n "$TELEGRAM_CHAT" ]]; thencurl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \-H "Content-Type: application/json" \-d "$(jq -n --arg chat "$TELEGRAM_CHAT" --arg text "$REPORT" \- '{chat_id: $chat, text: $text, parse_mode: "Markdown"}')" \+ '{chat_id:$chat, text:$text, parse_mode:"Markdown"}')" \>> "$LOG" 2>&1log "Competitor intel sent to Telegram chat=$TELEGRAM_CHAT"else