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: claude-ops v0.8.0 — business operations command center for Claude Code
Lifecycle Innovations0e29706e6d16
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 00000000..d0da5491--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,18 @@+{+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",+ "name": "ops-marketplace",+ "description": "Local marketplace for claude-ops plugin",+ "owner": {+ "name": "Lifecycle Innovations Limited",+ "email": "[email protected]"+ },+ "plugins": [+ {+ "name": "ops",+ "description": "Business operations command center for Claude Code",+ "source": "./claude-ops",+ "version": "0.8.0",+ "category": "productivity"+ }+ ]+}\ No newline at end of filediff --git a/.githooks/pre-commit b/.githooks/pre-commitnew file mode 100755index 00000000..62e6d0da--- /dev/null+++ b/.githooks/pre-commit@@ -0,0 +1,86 @@+#!/usr/bin/env bash+# Pre-commit hook: block commits containing personal data or secrets+# This is a PUBLIC open-source plugin — no user-specific data allowed+set -euo pipefail++RED='\033[0;31m'+GREEN='\033[0;32m'+NC='\033[0m'+FAILED=0++echo "Running pre-commit security checks..."++# Only check added/modified lines in the staged diff (not removals)+DIFF_ADDED=$(git diff --cached -U0 | grep '^+' | grep -v '^+++' || true)++if [[ -z "$DIFF_ADDED" ]]; then+ exit 0+fi++check() {+ local desc="$1" pattern="$2"+ local hits+ hits=$(echo "$DIFF_ADDED" | grep -iE "$pattern" 2>/dev/null | head -3 || true)+ if [[ -n "$hits" ]]; then+ echo -e "${RED}BLOCKED: $desc${NC}"+ echo "$hits" | head -3+ FAILED=1+ fi+}++# === Secrets & tokens (pattern-based, no hardcoded values) ===+check "Shopify admin/app tokens" 'shp(at|ss|pa|ca)_[a-f0-9]{10,}'+check "Slack tokens" 'xox[bpca]-[a-zA-Z0-9]+'+check "GitHub tokens" 'gh[pso]_[A-Za-z0-9]{20,}'+check "AWS access keys" 'AKIA[A-Z0-9]{16}'+check "Generic sk_ secret keys" '\bsk_[a-zA-Z0-9]{20,}'+check "Generic gsk_ keys" '\bgsk_[A-Za-z0-9]{20,}'+check "Stripe live keys" '(sk_live_|pk_live_|rk_live_)[a-zA-Z0-9]+'+check "Google API keys" 'AIza[A-Za-z0-9_-]{35}'+check "Org-prefixed keys (40+ hex)" '\borg_[a-f0-9]{40,}'+check "Bearer tokens in strings" 'Bearer [a-zA-Z0-9_-]{20,}'+check "Base64 JWT-like tokens" 'eyJ[a-zA-Z0-9_-]{50,}'++# === Personal email patterns ===+check "Personal email (webmail)" '[a-zA-Z0-9._%+-]+@(gmail|yahoo|hotmail|outlook|icloud|proton|hey)\.(com|net|org)'+check "Non-example work emails" '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|io|ai|dev|co|ltd|limited)'++# Allow @example.com, @test.com, @localhost — filter those out+if [[ $FAILED -eq 1 ]]; then+ # Re-check: if ALL email hits are example/test domains, clear the flag+ real_emails=$(echo "$DIFF_ADDED" | grep -iE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|io|ai|dev|co|ltd|limited)' | grep -ivE '@(example|test|localhost|noreply|anthropic)\.' || true)+ if [[ -z "$real_emails" ]]; then+ FAILED=0+ fi+fi++# === Hardcoded paths ===+check "macOS home directory" '/Users/[a-z][a-zA-Z0-9_-]+'+check "Linux home directory" '/home/[a-z][a-zA-Z0-9_-]+/'++# === Phone numbers (international format) ===+check "Phone numbers" '\+[0-9]{1,3}[- ]?[0-9]{6,14}'++# === IP addresses (non-localhost, non-example) ===+check "Private/real IP addresses" '\b(10\.[0-9]+\.[0-9]+\.[0-9]+|172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+|192\.168\.[0-9]+\.[0-9]+)\b'++# === Generic sensitive patterns ===+check "password= or secret= values" '(password|secret|api_key|access_token)\s*[=:]\s*["\x27][^"\x27]{8,}'++if [[ $FAILED -eq 1 ]]; then+ echo ""+ echo -e "${RED}Commit blocked — personal or sensitive data detected in a PUBLIC repo.${NC}"+ echo "Use generic placeholders: [email protected], yourstore.myshopify.com, <YOUR_TOKEN>"+ echo "Bypass with --no-verify (emergency only)."+ exit 1+fi++# Run test suite secrets scanner if available+if [[ -f "claude-ops/tests/test-no-secrets.sh" ]]; then+ (cd claude-ops && bash tests/test-no-secrets.sh > /dev/null 2>&1) || {+ echo -e "${RED}BLOCKED: test-no-secrets.sh failed${NC}"+ exit 1+ }+fi++echo -e "${GREEN}Pre-commit security checks passed${NC}"diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdnew file mode 100644index 00000000..d8e9e9a7--- /dev/null+++ b/.github/CONTRIBUTING.md@@ -0,0 +1,54 @@+# Contributing to Claude Ops Marketplace++Thanks for your interest in contributing!++## Getting Started++1. Fork the repository+2. Clone your fork: `git clone https://github.com/<your-username>/claude-ops.git`+3. Create a feature branch (see branch naming below)+4. Make your changes, commit, and push+5. Open a pull request against `dev`++## Branch Naming++| Prefix | Use |+|--------|-----|+| `feat/` | New features or integrations |+| `fix/` | Bug fixes |+| `docs/` | Documentation only changes |++Examples: `feat/stripe-integration`, `fix/auth-token-refresh`, `docs/setup-guide`++## Pull Request Process++1. Target the `dev` branch (never `main` directly)+2. Fill out the PR template completely+3. Ensure all CI checks pass+4. Request a review from a maintainer+5. Address feedback promptly — stale PRs may be closed++## Code Style++- TypeScript: follow existing ESLint/Prettier config (`npm run lint`)+- Shell scripts: `shellcheck`-clean+- Python: `ruff` for linting, `black` for formatting+- No placeholder comments or TODOs — ship complete code only+- Keep changes surgical; avoid scope creep++## Testing++- Add or update unit tests for any logic you change+- Run the test suite before opening a PR:+ ```bash+ npm run type-check && npm run lint && npm run test+ ```+- Integration tests must not mock external services++## Reporting Issues++Use the issue templates in `.github/ISSUE_TEMPLATE/`. Include as much context as possible — vague reports are hard to act on.++## License++By contributing, you agree your contributions will be licensed under the project's existing license.diff --git a/.github/FUNDING.yml b/.github/FUNDING.ymlnew file mode 100644index 00000000..d5db1056--- /dev/null+++ b/.github/FUNDING.yml@@ -0,0 +1 @@+github: Lifecycle-Innovations-Limiteddiff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdnew file mode 100644index 00000000..9a528c3f--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -0,0 +1,37 @@+---+name: Bug Report+about: Report a reproducible bug+labels: bug+---++## Description++<!-- A clear and concise description of the bug -->++## Steps to Reproduce++1.+2.+3.++## Expected Behavior++<!-- What should have happened -->++## Actual Behavior++<!-- What actually happened — include error messages, stack traces, or screenshots -->++## Environment++- **Claude Code version**: <!-- e.g. 1.2.3 — run `claude --version` -->+- **OS**: <!-- e.g. macOS 15.2, Ubuntu 24.04 -->+- **Node version** (if applicable): <!-- e.g. 20.11.0 -->++## Integrations Configured++<!-- List any MCP servers, tools, or third-party integrations active when the bug occurred -->++## Additional Context++<!-- Anything else that might help: config snippets, logs, related issues -->diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.mdnew file mode 100644index 00000000..c508a824--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.md@@ -0,0 +1,25 @@+---+name: Feature Request+about: Suggest a new feature or improvement+labels: enhancement+---++## Description++<!-- A clear and concise description of the feature you'd like -->++## Use Case++<!-- Describe the problem this solves or the workflow it enables. Who benefits and how? -->++## Proposed Solution++<!-- How would you like this to work? Include API shapes, UI sketches, or command examples if helpful -->++## Alternatives Considered++<!-- What workarounds or alternative approaches have you tried? Why do they fall short? -->++## Additional Context++<!-- Links, prior art, related issues, or anything else worth knowing -->diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 00000000..043c67b9--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,23 @@+## Summary++<!-- What does this PR do and why? 1-3 sentences max -->++## Changes++<!-- Bullet list of meaningful changes — skip obvious ones like "added file X" -->++-+-++## Test Plan++<!-- How did you verify this works? Include commands run or steps taken -->++-++## Checklist++- [ ] Tests pass (`npm run type-check && npm run lint && npm run test`)+- [ ] Documentation updated (if applicable)+- [ ] No secrets, tokens, or credentials in the diff+- [ ] Targets `dev` (not `main`)diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 00000000..f897be73--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,46 @@+name: CI+on:+ pull_request:+ branches: [dev, main]+ push:+ branches: [dev]++jobs:+ lint-and-check:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'++ - name: Install dependencies+ run: cd claude-ops && npm ci++ - name: Syntax check (Node scripts)+ run: |+ node --check claude-ops/bin/ops-slack-autolink.mjs+ node --check claude-ops/bin/ops-telegram-autolink.mjs+ node --check claude-ops/telegram-server/index.js++ - name: Syntax check (Shell scripts)+ run: |+ bash -n claude-ops/bin/ops-merge-scan+ bash -n claude-ops/bin/ops-prs+ bash -n claude-ops/bin/ops-ci+ bash -n claude-ops/bin/ops-git+ bash -n claude-ops/bin/ops-infra+ bash -n claude-ops/bin/ops-unread+ bash -n claude-ops/bin/ops-gather+ bash -n claude-ops/bin/ops-setup-detect+ bash -n claude-ops/bin/ops-setup-install++ - name: Prettier check+ run: cd claude-ops && npx prettier --check "**/*.{js,mjs,json}" --ignore-path .gitignore++ - name: Install gitleaks+ run: |+ curl -sSfL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar xz+ chmod +x gitleaks+ - name: Run gitleaks+ run: ./gitleaks detect --source . --config claude-ops/.gitleaks.toml --verbosediff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..1fd89f93--- /dev/null+++ b/.gitignore@@ -0,0 +1,6 @@+# Root-level gitignore for the marketplace wrapper repo+.claude/+.planning/+.DS_Store+node_modules/+*.logdiff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..9483c070--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Lifecycle Innovations Limited++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 00000000..2aed09f1--- /dev/null+++ b/README.md@@ -0,0 +1,231 @@+```+ ██████╗██╗ █████╗ ██╗ ██╗██████╗ ███████╗ ██████╗ ██████╗ ███████╗+██╔════╝██║ ██╔══██╗██║ ██║██╔══██╗██╔════╝ ██╔═══██╗██╔══██╗██╔════╝+██║ ██║ ███████║██║ ██║██║ ██║█████╗ █████╗██║ ██║██████╔╝███████╗+██║ ██║ ██╔══██║██║ ██║██║ ██║██╔══╝ ╚════╝██║ ██║██╔═══╝ ╚════██║+╚██████╗███████╗██║ ██║╚██████╔╝██████╔╝███████╗ ╚██████╔╝██║ ███████║+ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚══════╝+```++<div align="center">++**Business Operating System for Claude Code**++[](./claude-ops/LICENSE)+[](https://github.com/Lifecycle-Innovations-Limited/claude-ops/releases)+[](https://claude.ai/settings/plugins)++</div>++```+╭──────────────────────────────────────────────────────────────────────────────╮+│ /ops:go ► MORNING BRIEFING 2026-04-12 09:03 │+├─────────────────────────────────┬────────────────────────────────────────────┤+│ INFRA ████████████████ ok │ ECS: 4/4 healthy RDS: ok Redis: ok │+│ CI/CD ████████████░░░░ 75% │ 3 passing 1 failing (my-api #847) │+│ INBOX ░░░░░░░░░░░░░░░░ 14 │ Slack: 9 Telegram: 3 Gmail: 2 unread │+│ PRs ████████████████ 3 │ 3 ready to merge 1 needs review │+│ SPRINT ████████████░░░░ 67% │ Sprint 24 — 8 of 12 issues complete │+│ REVENUE ████████████████ $ │ $2,847 MTD ↑12% vs last month │+├─────────────────────────────────┴────────────────────────────────────────────┤+│ Next action: merge feat/user-profile · fix my-api CI · reply @alice │+╰──────────────────────────────────────────────────────────────────────────────╯+```++One command. Sixty seconds. Your entire business, at a glance.++Turn Claude Code into a complete business operating system — infrastructure health, CI/CD status, unified inbox, open PRs, sprint state, revenue snapshot, and autonomous agents that act on your behalf.++```+╔══════════════════════════════╗+║ QUICK START ║+╚══════════════════════════════╝+```++```bash+# 1. Add the marketplace+/plugin marketplace add Lifecycle-Innovations-Limited/claude-ops++# 2. Install the plugin+/plugin install ops@lifecycle-innovations-limited-claude-ops++# 3. Configure your integrations (guided wizard)+/ops:setup+```++> The setup wizard walks through each integration interactively — install CLIs, connect channels, build your project registry. All credentials stored locally, never transmitted.++**Local development:**++```bash+git clone https://github.com/Lifecycle-Innovations-Limited/claude-ops.git+claude --plugin-dir ./claude-ops+```++```+╔══════════════════════════════╗+║ COMMAND SET ║+╚══════════════════════════════╝+```++```+┌────────────────┬─────────────────────────────────────────────┬──────────────────────────────────┐+│ COMMAND │ WHAT IT DOES │ INTEGRATIONS │+├────────────────┼─────────────────────────────────────────────┼──────────────────────────────────┤+│ /ops:go │ Full morning briefing — one cmd, 60s │ GitHub, Linear, Sentry, AWS │+│ /ops:inbox │ Unified inbox — read + triage all channels │ Slack, Telegram, WhatsApp, Gmail│+│ /ops:merge │ Autonomous PR review + merge pipeline │ GitHub Actions, GitHub CLI │+│ /ops:comms │ Send/read messages across any channel │ Slack, Telegram, WhatsApp, Gmail│+│ /ops:fires │ Production incidents + ECS health │ AWS ECS, Sentry │+│ /ops:revenue │ AWS spend, credits, runway estimate │ AWS Cost Explorer │+│ /ops:projects │ Portfolio dashboard — all projects │ GitHub, Linear │+│ /ops:linear │ Sprint board + issue management │ Linear │+│ /ops:deploy │ Deploy status across all projects │ AWS ECS, Vercel, GitHub Actions │+│ /ops:triage │ Cross-platform issue triage │ Sentry, Linear, GitHub Issues │+│ /ops:next │ Priority-ranked "what should I do next" │ Everything │+│ /ops:yolo │ 4 parallel C-suite AI agents — autonomous │ Everything │+└────────────────┴─────────────────────────────────────────────┴──────────────────────────────────┘+```++```+╔══════════════════════════════╗+║ BEFORE / AFTER ║+╚══════════════════════════════╝+```++```+┌────────────────────────────────────────────┬──────────────────────────────────────────────┐+│ WITHOUT claude-ops │ WITH claude-ops │+├────────────────────────────────────────────┼──────────────────────────────────────────────┤+│ Open 6+ tabs every morning │ /ops:go —— one command, done │+│ Context-switch between Slack/Telegram/ │ /ops:inbox —— unified view, all channels │+│ email │ │+│ Manually review and merge PRs one by one │ /ops:merge —— autonomous pipeline │+│ SSH into servers to check health │ /ops:fires —— terminal dashboard │+│ Forget to track AWS spend │ /ops:revenue —— automatic cost snapshot │+│ Switch between Linear and GitHub │ /ops:linear + /ops:projects —— unified │+└────────────────────────────────────────────┴──────────────────────────────────────────────┘+```++```+╔══════════════════════════════╗+║ REQUIREMENTS ║+╚══════════════════════════════╝+```++Just [Claude Code](https://claude.ai/code) 1.0+. Everything else is installed automatically.++The setup wizard (`/ops:setup`) walks you through each integration interactively — "Do you want AWS CLI? [Yes/No]", "Connect Slack? [OAuth/Skip]", etc. Missing CLIs are auto-installed via Homebrew. MCP servers connect via OAuth. No config files to edit manually.++```+╔══════════════════════════════════════════╗+║ INTEGRATIONS: MCP vs CLI ║+╚══════════════════════════════════════════╝+```++Most integrations offer two paths. The setup wizard lets you choose per-integration.++```+┌─────────────┬──────────────────────────────────┬────────────────────┬───────────────────────────────────────────────────────────────────┐+│ SERVICE │ MCP (zero-config OAuth) │ + CLI tool │ WHAT YOU LOSE WITHOUT THE CLI │+├─────────────┼──────────────────────────────────┼────────────────────┼───────────────────────────────────────────────────────────────────┤+│ GitHub │ — │ gh (auto) │ EVERYTHING — CI logs, PR merge, issue triage all require gh │+│ AWS │ — │ aws (auto) │ EVERYTHING — ECS health, cost tracking, revenue are CLI-only │+│ Linear │ OAuth via Claude.ai (12 tools) │ — │ Nothing — fully covered. 12 tools across 6 skills │+│ Vercel │ OAuth via Claude.ai │ — │ Nothing — deploy status, build logs, runtime logs via MCP │+│ Slack │ OAuth via Claude.ai │ local bot token │ MCP covers most users. Token adds: unlimited search, private ch │+│ Gmail │ OAuth via Claude.ai (read) │ gog (send+archive│ MCP = read-only. CLI enables autonomous send + archive │+│ Calendar │ OAuth via Claude.ai (full) │ gog (read-only) │ MCP has MORE features. Either works for briefings │+│ Sentry │ OAuth via Claude.ai │ sentry-cli │ MCP covers triage. CLI adds: source maps, release tracking │+│ WhatsApp │ — │ wacli │ EVERYTHING — no MCP exists. wacli is the only path │+│ Telegram │ — │ bundled MCP server│ EVERYTHING — plugin ships its own MTProto server. Fully automated │+│ GSD │ — │ auto-detected │ Optional — roadmap state in dashboards. Skills degrade gracefully │+└─────────────┴──────────────────────────────────┴────────────────────┴───────────────────────────────────────────────────────────────────┘+```++> **TL;DR** — Linear and Vercel are MCP-only (and that's fine). GitHub and AWS are CLI-only (auto-installed). Gmail is where the choice matters most: MCP gives you read-only, CLI gives you full autonomous inbox management.++```+╔══════════════════════════════╗+║ ARCHITECTURE ║+╚══════════════════════════════╝+```++**Token Efficiency**++All skills use pre-execution shell blocks (`!` fences) that gather data *before* the model context loads — zero extra latency, minimal token overhead.++**Plugin Structure**++```+claude-ops/+├── .claude-plugin/+│ └── plugin.json # Plugin manifest + userConfig schema+│+├── skills/ # 14 slash command skills+│ ├── ops/ # Router — dispatches to sub-skills+│ ├── ops-go/ # Morning briefing+│ ├── ops-inbox/ # Unified inbox+│ ├── ops-comms/ # Cross-channel messaging+│ ├── ops-merge/ # Autonomous PR pipeline+│ ├── ops-fires/ # Production incidents+│ ├── ops-deploy/ # Deploy status+│ ├── ops-revenue/ # Cost tracking+│ ├── ops-projects/ # Portfolio dashboard+│ ├── ops-linear/ # Sprint management+│ ├── ops-triage/ # Issue triage+│ ├── ops-next/ # Next action advisor+│ ├── ops-yolo/ # YOLO autonomous mode+│ └── setup/ # Interactive setup wizard+│+├── agents/ # 9 autonomous agents+│ ├── yolo-ceo.md # CEO synthesizer (Opus)+│ ├── yolo-cto.md # CTO technical analysis+│ ├── yolo-cfo.md # CFO financial analysis+│ ├── yolo-coo.md # COO operations analysis+│ ├── triage-agent.md # Issue investigation + fix+│ ├── comms-scanner.md # Inbox state scanner+│ ├── infra-monitor.md # Infrastructure health+│ ├── project-scanner.md # Project portfolio scanner+│ └── revenue-tracker.md # Revenue/cost monitor+│+├── bin/ # Shell scripts + ops-shopify-create+├── hooks/ # SessionStart health check+├── telegram-server/ # Bundled MCP server (gram.js)+├── templates/ # App scaffolding templates+│ └── shopify-admin-app/ # Shopify Admin Remix template+├── tests/ # Bash-based validation suite+├── scripts/ # Setup scripts + project registry+├── CLAUDE.md # Plugin-root rules (AskUserQuestion <=4, no delegation)+└── .mcp.json # MCP server declarations+```++```+╔══════════════════════════════╗+║ CONTRIBUTING ║+╚══════════════════════════════╝+```++PRs welcome. See [`claude-ops/README.md`](./claude-ops/README.md) for detailed documentation on each skill, agent, and integration.++```bash+# Development mode — load plugin from local directory+claude --plugin-dir ./claude-ops++# Reload after changes+/reload-plugins+```++```+╔══════════════════════════════╗+║ LICENSE ║+╚══════════════════════════════╝+```++[MIT](./claude-ops/LICENSE) — built by [Lifecycle Innovations Limited](https://github.com/Lifecycle-Innovations-Limited)++```+─────────────────────────────────────────────────────────────────────────────+ claude-ops v0.8.0 · MIT · github.com/Lifecycle-Innovations-Limited+─────────────────────────────────────────────────────────────────────────────+```diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 00000000..5dc21c1c--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,25 @@+# Security Policy++## Reporting a Vulnerability++If you discover a security vulnerability, please report it responsibly:++1. **Do NOT** open a public issue+2. Email: [email protected] (replace with your contact)+3. Include: description, reproduction steps, impact assessment++We'll respond within 48 hours and work with you on a fix before public disclosure.++## Supported Versions++| Version | Supported |+|---------|-----------|+| 0.3.x | ✅ |+| < 0.3 | ❌ |++## Security Features++- **Secret scanning**: `.gitleaks.toml` + GitHub secret scanning + push protection enabled+- **No secrets in code**: All tokens stored in macOS keychain, never in dotfiles or config+- **Encrypted cookie handling**: Browser cookie decryption uses the app's own keychain key+- **File permissions**: All temp files created with `umask 077` (mode 0600)diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..79c93086--- /dev/null+++ b/claude-ops/.claude-plugin/plugin.json@@ -0,0 +1,154 @@+{+ "name": "ops",+ "version": "0.6.0",+ "description": "Business operations command center for Claude Code. Manage communications, projects, infrastructure, and revenue from your terminal. Includes YOLO mode for autonomous business operation.",+ "author": {+ "name": "Lifecycle Innovations Limited",+ "url": "https://github.com/Lifecycle-Innovations-Limited"+ },+ "homepage": "https://github.com/Lifecycle-Innovations-Limited/claude-ops",+ "repository": "https://github.com/Lifecycle-Innovations-Limited/claude-ops",+ "license": "MIT",+ "keywords": [+ "business",+ "operations",+ "communications",+ "whatsapp",+ "email",+ "slack",+ "telegram",+ "linear",+ "sentry",+ "infrastructure",+ "revenue",+ "yolo"+ ],+ "userConfig": {+ "telegram_api_id": {+ "title": "Telegram API ID",+ "description": "Numeric API ID from https://my.telegram.org/apps. Optional — run /ops:setup telegram to auto-configure.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "telegram_api_hash": {+ "title": "Telegram API Hash",+ "description": "API hash from https://my.telegram.org/apps. Optional — run /ops:setup telegram to auto-configure.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "telegram_phone": {+ "title": "Telegram Phone Number",+ "description": "Your phone number in E.164 format. Optional — run /ops:setup telegram to auto-configure.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "telegram_session": {+ "title": "Telegram Session String",+ "description": "gram.js StringSession. Optional — run /ops:setup telegram to auto-configure.",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "sentry_org": {+ "title": "Sentry Organization",+ "description": "Sentry organization slug e.g. 'my-org' (optional)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "linear_team": {+ "title": "Linear Team Key",+ "description": "Default Linear team key e.g. 'HEA' (optional)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "aws_region": {+ "title": "AWS Region",+ "description": "Default AWS region for infra checks e.g. 'us-east-1' (optional)",+ "type": "string",+ "sensitive": false,+ "default": "us-east-1"+ },+ "klaviyo_private_key": {+ "title": "Klaviyo Private API Key",+ "description": "Private API key from Klaviyo Settings > API Keys (starts with pk_ or ck_)",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "meta_ads_token": {+ "title": "Meta Ads Access Token",+ "description": "Meta Marketing API access token from Facebook Business",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "meta_ad_account_id": {+ "title": "Meta Ad Account ID",+ "description": "Ad account ID (format: act_XXXXXXXXX)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "ga4_property_id": {+ "title": "Google Analytics 4 Property ID",+ "description": "GA4 property ID (numeric, from Admin > Property Settings)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "google_search_console_site": {+ "title": "Google Search Console Site URL",+ "description": "Site URL as registered in Search Console (e.g., https://example.com)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "shopify_store_url": {+ "title": "Shopify Store URL",+ "description": "Your Shopify store URL (e.g., mystore.myshopify.com)",+ "type": "string",+ "sensitive": false,+ "default": ""+ },+ "shopify_admin_token": {+ "title": "Shopify Admin API Token",+ "description": "Admin API access token from Shopify Partners or custom app",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "shipbob_access_token": {+ "title": "ShipBob Access Token",+ "description": "ShipBob Personal Access Token for fulfillment tracking (optional)",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "bland_ai_api_key": {+ "title": "Bland AI API Key",+ "description": "API key from https://app.bland.ai — used for /ops:ops-voice call",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "elevenlabs_api_key": {+ "title": "ElevenLabs API Key",+ "description": "API key from https://elevenlabs.io — used for /ops:ops-voice tts",+ "type": "string",+ "sensitive": true,+ "default": ""+ },+ "groq_api_key": {+ "title": "Groq API Key",+ "description": "API key from https://console.groq.com — used for /ops:ops-voice transcribe (Whisper)",+ "type": "string",+ "sensitive": true,+ "default": ""+ }+ }+}diff --git a/claude-ops/.gitignore b/claude-ops/.gitignorenew file mode 100644index 00000000..12853f8d--- /dev/null+++ b/claude-ops/.gitignore@@ -0,0 +1,33 @@+node_modules/+.env+.env.*+.DS_Store+*.swp+*.swo+*~+.vscode/+.idea/+telegram-server/node_modules/+.planning/+.claude/worktrees/+*.log++# Per-user config — never commit. Copy registry.example.json to registry.json+# and fill in your own project list. preferences.json holds secrets (tokens,+# owner identity) and is managed by /ops:setup.+scripts/registry.json+scripts/preferences.json++# Temp files from autolink scripts+/tmp/+ops-*.out+ops-*.log+telegram-code.txt+telegram-password.txt+slack-login-done++# Playwright+.claude-ops/++# Package locks from sub-dirs (root only committed)+telegram-server/package-lock.jsondiff --git a/claude-ops/.gitleaks.toml b/claude-ops/.gitleaks.tomlnew file mode 100644index 00000000..133e27e6--- /dev/null+++ b/claude-ops/.gitleaks.toml@@ -0,0 +1,84 @@+# gitleaks configuration for claude-ops (public repo)+# Run: gitleaks detect --source . --config .gitleaks.toml++title = "claude-ops secret scanning"++[extend]+useDefault = true++[[rules]]+id = "telegram-bot-token"+description = "Telegram Bot Token"+regex = '''\d{8,10}:[A-Za-z0-9_-]{35}'''+keywords = ["telegram"]++[[rules]]+id = "telegram-api-hash"+description = "Telegram API Hash"+regex = '''[a-f0-9]{32}'''+keywords = ["api_hash", "apiHash", "TELEGRAM_API_HASH"]++[[rules]]+id = "telegram-session-string"+description = "Telegram Session String (gram.js)"+regex = '''[A-Za-z0-9+/=]{100,}'''+keywords = ["session", "StringSession", "TELEGRAM_SESSION"]++[[rules]]+id = "slack-xoxc-token"+description = "Slack XOXC Token"+regex = '''xoxc-[0-9]+-[0-9]+-[0-9]+-[a-f0-9]+'''++[[rules]]+id = "slack-xoxd-token"+description = "Slack XOXD Token"+regex = '''xoxd-[A-Za-z0-9%+/=]+'''++[[rules]]+id = "slack-xoxb-token"+description = "Slack Bot Token"+regex = '''xoxb-[0-9]+-[0-9]+-[A-Za-z0-9]+'''++[[rules]]+id = "slack-xoxp-token"+description = "Slack User Token"+regex = '''xoxp-[0-9]+-[0-9]+-[0-9]+-[a-f0-9]+'''++[[rules]]+id = "phone-number-international"+description = "International Phone Number"+regex = '''\+\d{10,15}'''+allowlist.paths = [+ '''SKILL\.md$''',+ '''CHANNELS\.md$''',+ '''README\.md$''',+ '''\.example\.''',+ '''test''',+ '''plugin\.json$''',+ '''CHANGELOG\.md$''',+]+allowlist.regexes = [+ '''\+15551234567''',+]++[[rules]]+id = "email-address-personal"+description = "Personal Email Address"+regex = '''[a-zA-Z0-9._%+-]+@(gmail|outlook|hotmail|yahoo|protonmail|icloud)\.[a-z]{2,}'''+allowlist.paths = [+ '''SKILL\.md$''',+ '''README\.md$''',+ '''\.example\.''',+ '''CHANGELOG\.md$''',+]++[allowlist]+paths = [+ '''node_modules''',+ '''package-lock\.json''',+ '''\.gitleaks\.toml$''',+]+stopwords = [+ "XOXC_TOKEN",+ "XOXD_TOKEN",+]diff --git a/claude-ops/.mcp.json b/claude-ops/.mcp.jsonnew file mode 100644index 00000000..1ea076a3--- /dev/null+++ b/claude-ops/.mcp.json@@ -0,0 +1,14 @@+{+ "mcpServers": {+ "telegram": {+ "command": "node",+ "args": ["${CLAUDE_PLUGIN_ROOT}/telegram-server/index.js"],+ "env": {+ "TELEGRAM_API_ID": "${user_config.telegram_api_id}",+ "TELEGRAM_API_HASH": "${user_config.telegram_api_hash}",+ "TELEGRAM_PHONE": "${user_config.telegram_phone}",+ "TELEGRAM_SESSION": "${user_config.telegram_session}"+ }+ }+ }+}diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdnew file mode 100644index 00000000..1579b131--- /dev/null+++ b/claude-ops/CHANGELOG.md@@ -0,0 +1,195 @@+# Changelog++All notable changes to this project will be documented in this file.++## [0.8.0] — 2026-04-13++### Added++- **CLAUDE.md plugin rules** — Plugin-root `CLAUDE.md` with two hard rules enforced across all skills: (1) max 4 options per `AskUserQuestion` call (schema limit), (2) never delegate CLI commands to the user — run via Bash tool instead (exception: `wacli auth` QR code).+- **Shopify admin app template** — `templates/shopify-admin-app/` — full Shopify Admin Remix template with all admin scopes, forked from Shopify/shopify-app-template-remix.+- **`bin/ops-shopify-create`** — Non-interactive Shopify app scaffolding script. Automates device-code OAuth (auto-opens browser via `expect`), fetches org ID from Shopify Partners API cache, runs `shopify app init` with all flags, and injects client ID into `shopify.app.toml`.+- **`expect` as required CLI** — Added to `bin/ops-setup-preflight` detection and `bin/ops-setup-install` for browser-automation flows.+- **Test suite** — New `tests/` directory with bash-based validation covering skills, bin scripts, hooks, templates, and secrets.++### Changed++- **AskUserQuestion <=4 enforcement** — All 15 skills audited and fixed. setup section picker (11→batched 4+4+3), setup channel picker (7→4+3), ops-comms / deploy / fires / go / inbox / linear / projects / revenue / speedup / triage / yolo all batch >4 menus with `[More options...]` bridges. ops-dash hotkey menu refactored.++## [0.6.0] — 2026-04-13++### Added++- **`/ops:ecom`** — E-commerce operations command center (Shopify, Klaviyo, ShipBob, Meta Ads)+- **`/ops:marketing`** — Marketing analytics (email campaigns, ads, SEO, social, competitors)+- **`/ops:voice`** — Voice channel management+- **Daemon cron jobs** — Competitor intel, inbox digest, store health monitoring scripts+- **Message listener** — Real-time message event processing via wacli+- **Universal credential auto-scan** — Setup wizard auto-discovers API keys from env, Doppler, password managers, and browser sessions+- **Dynamic partner discovery** — Ecom/marketing setup detects installed platforms automatically+- **docs/** — Full reference documentation (skills, agents, daemon, memories)++### Fixed++- MCP namespace corrections across 8 skills and 3 agents (Linear, Gmail, Sentry)+- Broken YAML frontmatter in ops-comms, ops-triage, ops-yolo+- All 19 audit gaps resolved (100/100 score)++### Changed++- README updated with v0.6.0 features, architecture diagram, new skills table+- Plugin userConfig expanded: Klaviyo, Meta Ads, GA4, Search Console, Shopify, ShipBob keys++## [0.5.0] — 2026-04-13++### Added++- **ops-daemon** — Unified background process manager (launchd). Manages wacli sync, memory extraction, and future services with auto-heal, bootstrap sync, and auto-backfill for @lid chats.+- **ops-memories** — Daemon-spawned haiku agent extracts contact profiles, user preferences, communication patterns, and conversation context from chat history every 30 min. Writes structured markdown to `memories/`.+- **wacli-keepalive** — Persistent WhatsApp connection with bootstrap sync, auto-detection of empty @lid chats, health file contract (`~/.wacli/.health`), and launchd integration.+- **Doppler integration** — Setup wizard detects and configures Doppler CLI for secrets management. All skills can query secrets via `doppler secrets get`.+- **Password manager integration** — Setup wizard detects 1Password (`op`), Dashlane (`dcli`), Bitwarden (`bw`), and macOS Keychain. Configures query commands for agent use.+- **CLI/API reference tables** — All 14 operational skills now include complete command reference tables with exact syntax, flags, and output formats for wacli, gog, gh, aws, sentry-cli, and Linear GraphQL.+- **Deep context inbox** — ops-inbox and ops-comms now read full conversation threads (20+ messages), build contact profiles across channels, search for topic context, and draft replies matching user's language and style. Safety rail: NEVER send without full thread understanding.+- **PreToolUse hooks** — Automatic wacli health check before any WhatsApp command. Daemon health surfaced to user when action needed.+- **Stop hooks** — Session cleanup removes stale worktrees and temp files.+- **Runtime Context** — Every skill loads preferences, daemon health, ops-memories, and secrets at execution time.++### Changed++- **Plugin feature adoption ~35% → ~85%** — All 19 skills annotated with `effort`, `maxTurns`, and `disallowedTools`. 3 heavy skills use `claude-opus-4-6`. 4 read-only skills block Edit/Write. All 10 spawnable agents have `memory` (project/user scope). 4 scanner agents have `initialPrompt` for auto-start. Triage agent has `isolation: worktree`.+- **Setup wizard** — New steps for Doppler (3f), password manager (3g), and background daemon (5b). Daemon replaces standalone wacli launchd agent.+- **ops-inbox** — Full thread reads (20 msgs not 5), contact profile cards, topic search, cross-channel history, language/style matching in drafts.+- **ops-comms** — Full conversation context required before any send. Health pre-flight for WhatsApp.++## [0.4.2] — 2026-04-13++### Added++- **`bin/ops-autofix`** — Silent auto-repair script for common ops issues. Fixes wacli FTS5 (rebuilds with `sqlite_fts5` Go build tag), registers Slack MCP (from keychain tokens), and registers Vercel MCP. Runs non-interactively with `--json` output. Supports `--fix=all|wacli-fts|slack-mcp|vercel-mcp` targeting.++### Changed++- **`bin/ops-doctor`** — Now runs `ops-autofix` after diagnostics and reports any auto-applied fixes.+- **`bin/ops-setup-preflight`** — Now runs `ops-autofix` as a background job during preflight, so `/ops:setup` auto-repairs issues before the wizard even starts.++## [0.4.0] — 2026-04-13++### Added++- **`/ops:dash`** — Interactive pixel-art command center dashboard. Visual HQ with instant hotkey navigation (1-9, 0, a-h), live status indicators (fires, unread, PRs, GSD phases), C-suite report viewer, interactive settings editor, share-your-setup social flow, and FAQ/wiki section with links. `/ops` with no args now launches the dashboard instead of a text menu.+- **`/ops:speedup`** — Cross-platform system optimizer. Auto-detects macOS/Linux/WSL, scans for reclaimable disk space (brew, npm, Xcode, Docker, trash, logs, tmp, app caches), reports memory pressure, runaway processes, startup bloat, network latency. Health score (0-100). Tiered cleanup options: quick/full/deep/custom/memory/startup/network. On macOS, leverages the existing comprehensive `speedup.sh` for deep optimization.+- **`bin/ops-dash`** — Shell script that renders the pixel-art dashboard with parallel background data probes (projects, PRs, CI, unread, GSD, YOLO reports).+- **`bin/ops-speedup`** — Shell script for cross-platform system diagnostics (OS detection, hardware fingerprint, disk/memory/process/network metrics). Supports `--json` flag for machine-readable output.++### Changed++- **`/ops` router** — Empty args now launch `/ops:dash` instead of showing a static text menu. Added routing for `speedup`, `clean`, `optimize`, `cleanup` to `/ops:speedup`.+- **Telegram setup** — After authenticating via `ops-telegram-autolink.mjs`, credentials are now auto-written to the MCP config. No more manual paste into `/plugin settings`.+- **GSD companion install** — Now installs automatically with a single "Yes" instead of telling users to run slash commands manually.++## [Unreleased]++### Added — autolink wizards for Telegram and Slack++- **`bin/ops-telegram-autolink.mjs`** — zero-browser Telegram user-auth wizard. Takes a phone number, uses plain HTTP against `my.telegram.org` (pattern borrowed from [esfelurm/Apis-Telegram](https://github.com/esfelurm/Apis-Telegram) — `my.telegram.org` is fully server-rendered so no Playwright/Selenium is needed for api_id extraction). Scouts existing credentials in macOS keychain and `~/.claude.json` first. If none found, posts phone to `/auth/send_password`, waits for the user's code via `/tmp/telegram-code.txt` bridge file, POSTs `/auth/login`, GETs `/apps`, regex-extracts `api_id` + `api_hash`, creates an app if none exists, then runs gram.js `client.start()` to generate a session string (handling a second code via the same bridge). Final result: JSON line to stdout with `{api_id, api_hash, phone, session}`.+- **`bin/ops-slack-autolink.mjs`** — Slack token wizard with scout-first, Playwright fallback. Scouts `~/.claude.json mcpServers.slack`, process env, macOS keychain (`slack-xoxc`/`slack-xoxd`), shell profile files, and Doppler. If nothing is found, launches Playwright with a persistent Chromium profile dir at `~/.claude-ops/slack-profile`, navigates to `app.slack.com/client/`, waits for the user to log in via a bridge file (`/tmp/slack-login-done`), then extracts the `xoxc-...` token from `localStorage.localConfig_v2.teams[teamId].token` and the `d` cookie (`xoxd-...`) from the cookie jar. Ported from [maorfr/slack-token-extractor](https://github.com/maorfr/slack-token-extractor) (Python → Node).+- **`skills/setup/SKILL.md` Step 3a + 3d rewritten** to invoke these binaries as background processes via the file-bridge pattern, and to display instructions for wiring extracted values into `/plugin settings` (we do not auto-write to `~/.claude.json` — that's Claude Code's internal file and the plugin must not touch it).+- **New deps**: `playwright` (~200MB Chromium browser on first install) added to `telegram-server/package.json`. Only required if the user chooses to run the Playwright fallback path for Slack — scout-only mode has no dependency on Playwright.+- **Bumped to v0.2.2** — `plugin.json` + `marketplace.json`. Earlier user-auth-only fixes were v0.2.1.++### Fixed — public-repo hygiene pass++- **Scrubbed `scripts/registry.json` from all git history** via `git filter-repo` + force-push. The file contained real project data (paths, repo slugs, revenue stages, infra topology) and was tracked in the repo since day one. Now gitignored, with `scripts/registry.example.json` as a starter template.+- **Removed `.planning/` from tracked files** (`git rm -r --cached`). Previously leaked internal phase docs, ROADMAP.md, STATE.md, PROJECT.md. Gitignored going forward.+- **Refactored hardcoded project references to registry-driven iteration** in 7 files: `agents/yolo-cto.md`, `agents/yolo-coo.md`, `agents/infra-monitor.md`, `agents/triage-agent.md`, `agents/comms-scanner.md`, `skills/ops-deploy/SKILL.md`, `skills/ops-triage/SKILL.md`, `skills/ops-next/SKILL.md`, `skills/ops-projects/SKILL.md`. All loops now read `.projects[].repos[]` / `.paths[]` / `.infra.ecs_clusters[]` / `.infra.health_endpoints[]` from `scripts/registry.json` (with `registry.example.json` fallback). Sensible defaults shown in example tables use `example-app` / `example-api` instead of real project names.+- **Removed hardcoded personal data**: hardcoded email in `agents/comms-scanner.md` replaced with preferences-driven `channels.email.account`. Hardcoded home-dir fallback removed from `skills/setup/SKILL.md` detector invocation.+- **Rewrote README installation section** to reflect marketplace-plugin install flow (`/plugin marketplace add` + `/plugin`), not manual `git clone` + `settings.json` editing.+- **Rewrote README Telegram section** to match the v0.2.0 user-auth rewrite (gram.js MTProto) with API ID / API hash / phone / session flow instead of obsolete Bot API token flow.+- **Bumped `marketplace.json` to 0.2.1** to match `plugin.json`.+- Registered `.gitignore` superset: `node_modules/`, `.env*`, editor swap files, `.planning/`, `.claude/worktrees/`, `.DS_Store`, `*.log`, `scripts/preferences.json`, `scripts/registry.json`.++### Added++#### Interactive setup wizard (`/ops:setup`)++- `skills/setup/SKILL.md` — end-to-end config wizard with `AskUserQuestion` selectors+- `bin/ops-setup-detect` — JSON state probe (tools, env vars, MCPs, registry, prefs)+- `bin/ops-setup-install` — idempotent Homebrew/apt installer for CLI dependencies+- `~/.claude/plugins/data/ops-ops-marketplace/preferences.json` — owner, timezone, verbosity, default channels, channel secrets. Lives in Claude Code's per-plugin data dir so it survives reinstalls and version bumps; never stored in the plugin source tree.+- Routes `setup|configure|init|install` in the `/ops` command router++#### WhatsApp auto-heal (Step 3b of wizard)++- Detects stuck `wacli sync` processes via stale store lock + age check+- Detects app-state key desync via `wacli sync` stderr probe (the `didn't find app state key` error class)+- Offers to kill stale sync / logout + re-pair interactively+- Automatic historical backfill via `wacli history backfill` on top 10 most-recent chats after a successful heal++#### Email + Calendar with MCP fallback++- **Email**: primary `gog` CLI (full read + send); fallback Claude Gmail MCP connector (read-only until user grants send perms in Claude Desktop → Connectors)+- **Calendar**: primary `gog cal` (shared gog OAuth token); fallback Google Calendar MCP connector (read-only until user grants write perms in Claude Desktop)+- Both record the chosen backend in the plugin-data `preferences.json` (`channels.email`, `channels.calendar`) so downstream skills (`/ops-go`, `/ops-next`, `/ops-fires`) can cross-correlate with today's schedule++## [0.1.0] — 2026-04-11++### Added++#### Phase 1: Plugin Scaffold + Registry++- `scripts/registry.example.json` — template for the per-user project registry (aliases, paths, repos, infra, revenue stage, GSD flag). Real `scripts/registry.json` is gitignored.+- `bin/ops-unread` — parallel unread counts for WhatsApp, Email, Slack, Telegram+- `bin/ops-git` — git status across all registry projects+- `bin/ops-prs` — open PRs across all registered GitHub repos+- `bin/ops-ci` — CI failures (last 24h) from GitHub Actions+- `bin/ops-infra` — ECS cluster and service health from AWS+- `bin/ops-gather` — meta-runner for all gather scripts++#### Phase 2: Morning Briefing++- `skills/ops-go/SKILL.md` — token-efficient morning briefing using `!` shell injection+- Pre-gathers all data in <10 seconds before model reads context+- Unified business dashboard with prioritized actions++#### Phase 3: Communications Hub++- `skills/ops-inbox/SKILL.md` — inbox zero across WhatsApp, Email, Slack, Telegram+- `skills/ops-comms/SKILL.md` — send/read routing with natural language parsing+- Telegram MCP integration (mcp**claude_ops_telegram**\*)++#### Phase 4: Project Management++- `skills/ops-projects/SKILL.md` — portfolio dashboard with GSD state, CI, PRs+- `skills/ops-linear/SKILL.md` — Linear sprint board, issue management, GSD sync+- `skills/ops-triage/SKILL.md` — cross-platform triage (Sentry + Linear + GitHub)+- `skills/ops-fires/SKILL.md` — production incidents dashboard with agent dispatch+- `skills/ops-deploy/SKILL.md` — ECS + Vercel + GitHub Actions deploy status++#### Phase 5: Business Intelligence++- `skills/ops-revenue/SKILL.md` — AWS costs, credits, revenue pipeline, runway+- `skills/ops-next/SKILL.md` — priority-ordered next action (fires > comms > PRs > sprint > GSD)++#### Phase 6: YOLO Mode++- `skills/ops-yolo/SKILL.md` — 4-agent C-suite analysis + autonomous mode+- `agents/yolo-ceo.md` — Strategic analysis agent (claude-opus-4-5)+- `agents/yolo-cto.md` — Technical health agent (claude-sonnet-4-5)+- `agents/yolo-cfo.md` — Financial analysis agent (claude-sonnet-4-5)+- `agents/yolo-coo.md` — Operations execution agent (claude-sonnet-4-5)++#### Phase 7: Telegram MCP Server++- `telegram-server/index.js` — minimal MCP server using Telegram Bot API+- Tools: `send_message`, `get_updates`, `list_chats`+- `telegram-server/package.json` — @modelcontextprotocol/sdk dependency+- `.mcp.json` — Claude Code MCP server registration++#### Supporting Agents++- `agents/comms-scanner.md` — background comms monitoring agent+- `agents/infra-monitor.md` — infrastructure health monitoring agent+- `agents/project-scanner.md` — project state analysis agent+- `agents/revenue-tracker.md` — revenue and cost monitoring agent+- `agents/triage-agent.md` — issue triage and fix dispatch agentdiff --git a/claude-ops/CLAUDE.md b/claude-ops/CLAUDE.mdnew file mode 100644index 00000000..7c1b9280--- /dev/null+++ b/claude-ops/CLAUDE.md@@ -0,0 +1,42 @@+# claude-ops Plugin Rules++These rules apply to ALL skills in this plugin. They are non-negotiable and override any conflicting instruction in individual SKILL.md files.++## Rule 0 — PUBLIC REPO: No personal data ever++**This is a public open-source plugin.** Every file in this repo is visible to anyone on the internet.++**NEVER commit:**+- Real names, emails, phone numbers, or usernames (use "owner", "[email protected]", "+1234567890")+- Real store URLs, project names, or org names (use "yourstore.myshopify.com", "my-project")+- API keys, tokens, secrets, session strings, or chat IDs (use `<YOUR_TOKEN>`, `$ENV_VAR`)+- Real GitHub org names or repo slugs in examples (use "your-org/your-repo")+- Hardcoded paths like `/Users/username/...` (use `~` or `$HOME`)++**All user-specific data belongs in:**+- `$PREFS_PATH` (preferences.json in plugin data dir — never committed)+- `scripts/registry.json` (gitignored)+- Environment variables or Doppler secrets++Run `tests/test-no-secrets.sh` before every commit to verify.++## Rule 1 — Max 4 options per AskUserQuestion++The `AskUserQuestion` tool enforces a hard schema limit of `<=4` items in the `options` array. Passing more than 4 options causes an `InputValidationError` and the skill crashes.++**Requirements:**+- Never pass more than 4 options in a single `AskUserQuestion` call.+- When a step lists >4 choices, apply this strategy:+ 1. **Filter first** — remove items that are already configured, completed, or irrelevant to the current context. This alone often brings the count to <=4.+ 2. **Batch the rest** — group remaining items logically and present them across multiple sequential `AskUserQuestion` calls of <=4 options each.+ 3. **Use "More..." as a bridge** — when batching, the last option in each batch (except the final one) should be `[More options...]` to advance to the next batch.+- Dynamic lists (projects, configs, vaults) that may grow beyond 4 items at runtime MUST be paginated at 4 per page.+- Multi-select lists follow the same limit — max 4 checkboxes per call.++## Rule 2 — Never delegate commands to the user++When a skill says "tell the user to run X in a separate terminal" or "Run `command` in your terminal":+- **Run it via the Bash tool instead** (backgrounded with `run_in_background: true` if it is long-running or interactive).+- **OAuth flows** (`gog auth login`, `doppler login`, `op signin`): run via Bash with `run_in_background: true` — the browser will open automatically.+- **Password manager unlock** (`bw unlock`, `dcli configure`): run via Bash tool directly.+- **Exception — QR-based auth** (`wacli auth`): this genuinely requires the user's phone camera pointed at the terminal. This is the ONLY case where you should tell the user to act in a separate terminal.diff --git a/claude-ops/LICENSE b/claude-ops/LICENSEnew file mode 100644index 00000000..9483c070--- /dev/null+++ b/claude-ops/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Lifecycle Innovations Limited++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/claude-ops/README.md b/claude-ops/README.mdnew file mode 100644index 00000000..45434d25--- /dev/null+++ b/claude-ops/README.md@@ -0,0 +1,338 @@+# claude-ops++> **v0.6.0** — Smart Daemon · Deep Context Inbox · 21 Skills · 12 Agents · Full Plugin Feature Integration++A Claude Code plugin that turns Claude into a business operating system. Run `/ops` to launch the interactive command center — a pixel-art dashboard with instant hotkey access to morning briefings, inbox management, fire alerts, deploy status, revenue tracking, and autonomous YOLO mode.++## Features++| Skill | Description |+| ----------------- | ------------------------------------------------------------------------------ |+| `/ops` | Interactive command center dashboard (visual HQ) |+| `/ops:dash` | Same as `/ops` — pixel-art dashboard with hotkey navigation |+| `/ops:setup` | Interactive setup wizard — installs CLIs, configures channels, builds registry |+| `/ops:go` | Morning briefing — all systems in one dashboard |+| `/ops:next` | Priority-ordered next action (fires > comms > PRs > sprint > GSD) |+| `/ops:inbox` | Inbox zero across WhatsApp, Email, Slack, Telegram |+| `/ops:comms` | Send/read messages across all channels |+| `/ops:projects` | Portfolio dashboard — GSD phase, CI, PRs, dirty files |+| `/ops:linear` | Linear sprint board, issue management, GSD sync |+| `/ops:triage` | Cross-platform issue triage (Sentry + Linear + GitHub) |+| `/ops:fires` | Production incidents dashboard with agent dispatch |+| `/ops:deploy` | ECS + Vercel + GitHub Actions deploy status |+| `/ops:revenue` | AWS costs, credits, revenue pipeline, runway |+| `/ops:merge` | Auto-fix CI + merge all ready PRs |+| `/ops:speedup` | Cross-platform system optimizer (macOS/Linux/WSL) |+| `/ops:yolo` | 4-agent C-suite analysis + autonomous mode |+| `/ops:ecom` | E-commerce operations — Shopify orders, inventory, fulfillment, analytics |+| `/ops:marketing` | Marketing analytics — email campaigns, ads (Meta/Google), SEO, social |+| `/ops:voice` | Voice channel management — Bland AI calls, ElevenLabs TTS, Whisper transcribe |+| `/ops:orchestrate`| Autonomous multi-project work engine with parallel agents |++### Dashboard hotkeys++The `/ops:dash` command center provides instant navigation:++```+ QUICK ACTIONS INTEL+ 1 Morning briefing 6 Revenue & costs+ 2 Inbox zero 7 Linear sprint+ 3 Fire check 8 Deploy status+ 4 Project dashboard 9 Triage issues+ 5 What's next? 0 System speedup++ POWER COMMS+ a YOLO mode d Send message+ b Auto-merge PRs e C-suite reports+ c Setup wizard++ META+ f Settings & config h Help / FAQ / Wiki+ g Share your setup q Exit+```++## What's New in v0.6.0++### Smart Background Daemon+The ops-daemon runs persistently via launchd, keeping WhatsApp connected, pre-fetching briefing data every 5 minutes, detecting urgent messages, and triggering memory extraction on new conversations. Your `/ops:go` morning briefing loads instantly from cache.++### Deep Context Inbox+`/ops:inbox` now reads full conversation threads (20+ messages), builds contact profile cards from cross-channel search, and drafts replies matching your language and style. It never sends without understanding the full conversation.++### Memories System+A background haiku agent extracts contact profiles, communication preferences, and conversation context from your chat history every 30 minutes. All skills use these memories for personalized, context-aware responses.++### Doppler + Password Manager Integration+`/ops:setup` detects and configures Doppler for secrets management and 1Password/Dashlane/Bitwarden for credential vaults. All skills resolve secrets through the configured chain automatically.++### Full Plugin Feature Adoption+- All 21 skills: `effort`, `maxTurns`, `disallowedTools`, `model` annotations+- All 12 agents: `memory` (cross-session learning), `initialPrompt`, `isolation`+- PreToolUse hooks for WhatsApp health checks+- Runtime Context loading in every skill (preferences, daemon health, memories, secrets)+- CLI/API reference tables in all operational skills++## Requirements++- [Claude Code](https://claude.ai/code) 1.0++- GitHub CLI (`gh`) — for PRs and CI status++Everything else is optional. The setup wizard (`/ops:setup`) auto-detects what's installed and configures accordingly.++### Integrations++The setup wizard (`/ops:setup`) walks through each one interactively. You choose per-integration whether to install the CLI, connect the MCP, or skip.++#### CLI-only (no MCP alternative)++| Tool | Auto-installed | What it does |+|------|---------------|--------------|+| `gh` (GitHub CLI) | Yes (Homebrew) | PRs, CI logs, issue triage, merge pipeline — used by 8+ skills |+| `aws` (AWS CLI) | Yes (Homebrew) | ECS health, Cost Explorer, CloudWatch — used by ops-fires, ops-revenue, ops-deploy |+| `wacli` (WhatsApp) | Manual ([source](https://github.com/Lifecycle-Innovations-Limited/wacli)) | WhatsApp inbox, send/read, contact lookup — no MCP equivalent exists |+| Node.js 18+ | Yes (Homebrew) | Runs the bundled Telegram MCP server |++#### MCP-only (no CLI needed)++| MCP | Connected via | What it does |+|-----|--------------|--------------|+| Linear | OAuth (Claude.ai) | Sprint cycles, issues, projects — 12 tools across 6 skills. Fully covers all Linear functionality |+| Vercel | OAuth (Claude.ai) | Deploy status, build logs, runtime logs. Read-only (deploys triggered via CI) |++#### Choose: MCP, CLI, or both++| Integration | MCP path | CLI path | What you lose with MCP only |+|-------------|----------|----------|----------------------------|+| **Gmail** | Claude.ai OAuth — read threads, create drafts | `gog` CLI — full send, archive, label management | MCP **cannot send emails** (drafts only) and **cannot archive**. `/ops:inbox` autonomous mode requires `gog` |+| **Google Calendar** | Claude.ai OAuth — list, create, RSVP, find free time | `gog cal` — read today's events | MCP has *more* features. `gog` is simpler for read-only briefing context. Either works |+| **Slack** | Claude.ai OAuth — read, send, search | Local bot token via `ops-slack-autolink` | MCP has **quota limits**. Local token gives unlimited search + private channel access without bot membership |+| **Sentry** | Claude.ai OAuth — issue search, triage, resolve | `sentry-cli` — releases, source maps, deploy tracking | Current skills only use search/triage (MCP is fine). CLI adds release management (not used yet) |++#### Plugin-bundled++| Integration | What it is | Setup |+|-------------|-----------|-------|+| Telegram MCP server | gram.js MTProto user-auth — reads your DMs (not a bot) | `/ops:setup telegram` — enter phone number + 2 verification codes, everything else is fully automated (app creation, session generation, keychain storage) |+| [GSD](https://github.com/Lifecycle-Innovations-Limited/get-shit-done) | Project roadmap state in dashboards | Auto-detected. Skills degrade gracefully without it |++## Installation++`claude-ops` is distributed as a Claude Code marketplace plugin. Install it directly from inside Claude Code — you don't need to clone anything manually or edit any settings files.++```bash+# 1. Add the marketplace (one-time)+/plugin marketplace add Lifecycle-Innovations-Limited/claude-ops++# 2. Install the plugin+/plugin install ops@lifecycle-innovations-limited-claude-ops++# 3. Configure integrations (Telegram, Slack, AWS, etc.)+/ops:setup+```++The plugin's Telegram MCP server auto-installs its Node dependencies on first run via `npm install` inside the installed cache dir. You don't need to run it yourself.++If you prefer a local directory marketplace (useful for plugin development), clone the repo anywhere and register it:++```bash+git clone https://github.com/Lifecycle-Innovations-Limited/claude-ops ~/Projects/claude-ops-marketplace+# then inside Claude Code:+/plugin marketplace add ~/Projects/claude-ops-marketplace+```++## Setup++### Interactive wizard (recommended)++```+/ops:setup+```++Walks you through every configuration step inside Claude Code with structured selectors:++- Installs missing CLIs (`jq`, `gh`, `aws`, `doppler`, `sentry-cli`…) via Homebrew+- Collects tokens for each channel you enable (Telegram, WhatsApp, Email, Slack)+- Configures calendar (gog calendar → Google Calendar MCP fallback)+- Builds `scripts/registry.json` project-by-project+- Saves preferences (owner name, timezone, briefing verbosity, default channels, channel secrets) to `~/.claude/plugins/data/ops-ops-marketplace/preferences.json` — outside the plugin source tree so they survive plugin reinstalls and version bumps+- Exports `CLAUDE_PLUGIN_ROOT` in your shell profile++Jump straight to a section with e.g. `/ops:setup telegram`, `/ops:setup calendar`, `/ops:setup registry`, `/ops:setup cli`.++### Project Registry++Copy `scripts/registry.example.json` to `scripts/registry.json` (which is gitignored) and fill in your projects:++```json+{+ "version": "1.0",+ "owner": "Your Name",+ "projects": [+ {+ "alias": "myapp",+ "paths": ["~/Projects/myapp"],+ "repos": ["github-org/myapp"],+ "org": "github-org",+ "type": "monorepo",+ "infra": { "ecs_clusters": ["myapp-production"], "platform": "aws" },+ "revenue": { "model": "saas", "stage": "growth", "mrr": 5000 },+ "gsd": true,+ "priority": 1+ }+ ]+}+```++### Telegram (optional — user-auth, not bot)++The plugin uses **your personal Telegram account** via gram.js MTProto — not a bot — because bots can't read user DMs, which is the main use case for `/ops:inbox telegram`.++**Recommended path — let the wizard do it:**++```+/ops:setup telegram+```++This invokes `bin/ops-telegram-autolink.mjs`, which takes your phone number, performs the `my.telegram.org` HTTP login flow, extracts `api_id` + `api_hash` (creating a Telegram app for you if none exists), runs the gram.js auth flow to generate a session string, and stores everything in macOS keychain. Zero browser automation — `my.telegram.org` is server-rendered HTML, so the wizard uses plain HTTP requests. You just enter the two codes Telegram sends to your Telegram app.++After the wizard finishes, it automatically writes the credentials to the MCP config — no manual pasting required. Just restart Claude Code to activate the Telegram MCP server.++**Manual path (if you already have an app):**++1. Get your `api_id` + `api_hash` from [my.telegram.org/apps](https://my.telegram.org/apps). Create a personal app (NOT a bot).+2. Open `/plugin` in Claude Code → `ops@ops-marketplace` → Settings. Fill in `telegram_api_id`, `telegram_api_hash`, `telegram_phone` (E.164).+3. Generate a session string: `node ~/.claude/plugins/cache/ops-marketplace/ops/<latest>/telegram-server/index.js --auth`. Prompts for code + 2FA, prints a `TELEGRAM_SESSION` string.+4. Paste into `telegram_session` in plugin settings. Restart Claude Code.++After that, `/ops:inbox telegram`, `/ops:comms send "..." to John Smith`, and the YOLO autonomous loop can read and reply to your DMs directly.++## Usage++### Morning Briefing++```+/ops:go+```++Pre-gathers all data in parallel via shell scripts, then presents a unified dashboard in <10 seconds.++### Next Action++```+/ops:next+/ops:next focus on <project-alias>+```++Applies the priority stack: fires > urgent comms > ready-to-merge PRs > Linear sprint > GSD work.++### Inbox Zero++```+/ops:inbox # all channels+/ops:inbox email # email only+/ops:inbox slack # slack only+```++### Send a Message++```+/ops:comms send "hey, can we chat?" to John Smith+/ops:comms read whatsapp+```++### Fires Dashboard++```+/ops:fires+/ops:fires <project-alias>+```++Shows production incidents, ECS health, Sentry errors. Dispatches fix agents.++### YOLO Mode++```+/ops:yolo+```++Spawns 4 C-suite agents (CEO, CTO, CFO, COO) in parallel. Each analyzes the business from their perspective with full data access. Produces an unfiltered Hard Truths report.++After the report, type `YOLO` to hand over the controls — Claude will autonomously process inbox, merge ready PRs, fix fires, advance GSD phases, and deploy.++## Architecture++```+┌─────────────────────────────────────────────────┐+│ Claude Code │+│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │+│ │ Skills │ │ Agents │ │ Hooks │ │+│ │ (21) │ │ (12) │ │ PreToolUse │ │+│ │ /ops:* │ │ yolo-* │ │ SessionStart │ │+│ └────┬──────┘ └────┬─────┘ │ Stop │ │+│ │ │ └──────────────────┘ │+│ ▼ ▼ │+│ ┌─────────────────────────────────────────────┐ │+│ │ Runtime Context Layer │ │+│ │ preferences.json · daemon-health.json │ │+│ │ memories/ · secrets (Doppler/vault) │ │+│ └──────────────────────┬──────────────────────┘ │+└─────────────────────────┼────────────────────────┘+ │+┌─────────────────────────┼────────────────────────┐+│ ops-daemon (launchd) │+│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │+│ │ wacli │ │ memory │ │ brain layer │ │+│ │ sync │ │ extractor│ │ briefing cache │ │+│ │ (follow) │ │ (cron) │ │ urgent detect │ │+│ └──────────┘ └──────────┘ └──────────────────┘ │+└──────────────────────────────────────────────────┘+```++### Token Efficiency++All `ops-*` skills use the `!` shell injection pattern:++````markdown+```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || echo '{}'+```+````++This runs shell scripts *before* the model context is loaded, so data is pre-gathered with zero extra latency.++### Agent Files++| Agent | Purpose |+|-------|---------|+| `agents/comms-scanner.md` | Background comms monitoring |+| `agents/infra-monitor.md` | Infrastructure health monitoring |+| `agents/project-scanner.md` | Project state analysis |+| `agents/revenue-tracker.md` | Revenue and cost monitoring |+| `agents/triage-agent.md` | Issue triage and fix dispatch (worktree-isolated) |+| `agents/daemon-agent.md` | Daemon start/stop/health management |+| `agents/doctor-agent.md` | Plugin config diagnosis and auto-repair |+| `agents/memory-extractor.md` | Contact profile and context extraction (Haiku) |+| `agents/yolo-ceo.md` | CEO perspective (Opus, high effort) |+| `agents/yolo-cto.md` | CTO perspective |+| `agents/yolo-cfo.md` | CFO perspective |+| `agents/yolo-coo.md` | COO perspective |++### Telegram MCP Server++The `telegram-server/` directory contains an MCP server built on [gram.js](https://gram.js.org) (MTProto) that authenticates as your personal Telegram account — **not** as a bot. This is a hard requirement for `/ops:inbox telegram` because the Bot API cannot read user DMs.++Tools:+- `list_dialogs` — list recent conversations (DMs, groups, channels)+- `get_messages` — fetch messages from a specific chat+- `send_message` — send a message to a chat+- `search_messages` — full-text search across all your chats++See [telegram-server/README.md](telegram-server/README.md) for first-run auth flow and troubleshooting. The plugin's `.mcp.json` wires all four env vars (`TELEGRAM_API_ID`, `TELEGRAM_API_HASH`, `TELEGRAM_PHONE`, `TELEGRAM_SESSION`) from your `user_config` in Claude Code plugin settings — you never paste tokens into files directly.++## Contributing++PRs welcome. See [`docs/`](docs/) for detailed reference documentation on skills, agents, the daemon, and the memories system.++## License++MIT — see [LICENSE](LICENSE)diff --git a/claude-ops/agents/comms-scanner.md b/claude-ops/agents/comms-scanner.mdnew file mode 100644index 00000000..4a2116d7--- /dev/null+++ b/claude-ops/agents/comms-scanner.md@@ -0,0 +1,130 @@+---+name: comms-scanner+description: Scans all communication channels for FULL inbox state (not just unread). Classifies each conversation as NEEDS_REPLY, WAITING, or HANDLED. Returns structured JSON. Used by ops-inbox and ops-go.+model: claude-sonnet-4-5+effort: low+maxTurns: 10+tools:+ - Bash+ - Read+disallowedTools:+ - Write+ - Edit+ - Agent+memory: user+initialPrompt: "Scan all configured channels and classify conversations. Return structured JSON."+---++# COMMS SCANNER AGENT++Scan all channels for FULL inbox state — not just unread, but all recent conversations classified by action needed.++## Task++Run all channel scans in parallel:++```bash+# WhatsApp — ALL non-archived chats (not just unread)+wacli chats list --json 2>/dev/null || echo '{"error": "wacli not available"}'+# Then for each chat with recent activity (last 7 days):+# wacli messages list --chat "<JID>" --limit 5 --json+# Check FromMe on last message to classify NEEDS_REPLY vs WAITING+```++```bash+# Email — FULL inbox (not just unread)+# Read account from preferences.json (channels.email.account) or use gog's default+EMAIL_ACCOUNT=$(jq -r '.channels.email.account // empty' "${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json" 2>/dev/null)+if [ -n "$EMAIL_ACCOUNT" ]; then+ gog gmail search -a "$EMAIL_ACCOUNT" -j --results-only --no-input --max 30 "in:inbox" 2>/dev/null || echo '{"error": "gog not available"}'+else+ gog gmail search -j --results-only --no-input --max 30 "in:inbox" 2>/dev/null || echo '{"error": "gog not available or no default account"}'+fi+# For each thread, read last message to check if sender is you (WAITING) or them (NEEDS_REPLY)+```++```bash+# Telegram — user-auth API (NOT bot), list recent dialogs+# Use telegram user-auth MCP or tg-cli if available+echo '{"error": "telegram user-auth not configured"}'+```++Combine results into:++```json+{+ "timestamp": "[ISO8601]",+ "whatsapp": {+ "needs_reply": [+ {+ "contact": "[name]",+ "preview": "[text]",+ "timestamp": "[ISO8601]",+ "jid": "[JID]",+ "urgency": "high|medium|low"+ }+ ],+ "waiting": [+ {+ "contact": "[name]",+ "preview": "[your last msg]",+ "timestamp": "[ISO8601]"+ }+ ],+ "handled": []+ },+ "email": {+ "needs_reply": [+ {+ "from": "[sender]",+ "subject": "[subject]",+ "preview": "[text]",+ "timestamp": "[ISO8601]",+ "urgency": "high|medium|low"+ }+ ],+ "waiting": [+ {+ "from": "[recipient]",+ "subject": "[subject]",+ "timestamp": "[ISO8601]"+ }+ ],+ "fyi": [+ {+ "from": "[sender]",+ "subject": "[subject]",+ "type": "newsletter|notification|receipt"+ }+ ]+ },+ "slack": {+ "needs_reply": [],+ "waiting": [],+ "note": "fetch live via Slack MCP"+ },+ "telegram": {+ "needs_reply": [],+ "waiting": [],+ "note": "user-auth not configured"+ },+ "summary": {+ "total_needs_reply": 0,+ "total_waiting": 0,+ "total_fyi": 0,+ "urgent": []+ }+}+```++## Urgency scoring++Mark a message `high` if:++- Sender is in contacts list with `vip: true`+- Message contains: "urgent", "ASAP", "down", "broken", "help", "emergency", "critical"+- Email subject starts with "Re: Re: Re:" (long chain needing response)++## Output++Print only the JSON to stdout. No preamble. No summary.diff --git a/claude-ops/agents/daemon-agent.md b/claude-ops/agents/daemon-agent.mdnew file mode 100644index 00000000..7f27be7f--- /dev/null+++ b/claude-ops/agents/daemon-agent.md@@ -0,0 +1,116 @@+---+name: ops-daemon-manager+description: Manages the ops background daemon — start, stop, restart services, check health+model: claude-sonnet-4-6+effort: low+maxTurns: 10+memory: project+---++## Overview++The ops-daemon is a unified background process manager (`scripts/ops-daemon.sh`) that supervises+all claude-ops background services. It replaces per-service launchd agents with a single+`com.claude-ops.daemon` launchd unit.++Services are configured in `~/.claude/plugins/data/ops-ops-marketplace/daemon-services.json`.+Health is aggregated to `~/.claude/plugins/data/ops-ops-marketplace/daemon-health.json`.++## Commands++### Start daemon+```bash+launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.claude-ops.daemon.plist+```++### Stop daemon+```bash+launchctl bootout gui/$(id -u)/com.claude-ops.daemon+```++### Restart daemon+```bash+launchctl kickstart -k gui/$(id -u)/com.claude-ops.daemon+```++### Check overall health+```bash+cat ~/.claude/plugins/data/ops-ops-marketplace/daemon-health.json+```++### Check service statuses+```bash+cat ~/.claude/plugins/data/ops-ops-marketplace/daemon-health.json | jq '.services'+```++### Check for pending actions (e.g. reauth needed)+```bash+cat ~/.claude/plugins/data/ops-ops-marketplace/daemon-health.json | jq '.action_needed'+```++### Tail daemon log+```bash+tail -f ~/.claude/plugins/data/ops-ops-marketplace/logs/ops-daemon.log+```++### Tail a specific service log+```bash+tail -f ~/.claude/plugins/data/ops-ops-marketplace/logs/<service-name>.log+```++## Action Needed++When a service requires user intervention (e.g. wacli reauth), `action_needed` is set:++```json+{+ "action_needed": {"service": "wacli-sync", "action": "reauth"}+}+```++Any ops skill that reads `daemon-health.json` should surface this to the user immediately.++## Health Output Format++```json+{+ "timestamp": "2026-04-13T15:00:00Z",+ "pid": 12345,+ "uptime_seconds": 3600,+ "services": {+ "wacli-sync": {"status": "running", "pid": 67890, "last_health": "connected", "restarts": 0},+ "memory-extractor": {"status": "scheduled", "next_run": "2026-04-13T15:30:00Z", "last_run": "2026-04-13T15:00:00Z"}+ },+ "action_needed": null+}+```++## Service Statuses++| Status | Meaning |+|--------|---------|+| `running` | Process alive and healthy |+| `starting` | Just launched, awaiting health confirmation |+| `scheduled` | Cron service, waiting for next run |+| `dead` | Process exited unexpectedly |+| `needs_reauth` | Service requires user re-authentication |+| `stopped` | Gracefully stopped |+| `max_restarts_exceeded` | Hit restart cap — manual intervention needed |++## Install / Uninstall++The `ops:setup` wizard installs the daemon plist automatically. Manual install:++```bash+# Copy and configure plist+SCRIPTS_DIR=~/Projects/claude-ops/claude-ops/scripts+LOG_DIR=~/.claude/plugins/data/ops-ops-marketplace/logs+sed \+ -e "s|__DAEMON_SCRIPT_PATH__|$SCRIPTS_DIR/ops-daemon.sh|g" \+ -e "s|__LOG_DIR__|$LOG_DIR|g" \+ -e "s|__HOME__|$HOME|g" \+ "$SCRIPTS_DIR/com.claude-ops.daemon.plist" \+ > ~/Library/LaunchAgents/com.claude-ops.daemon.plist++launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.claude-ops.daemon.plist+```diff --git a/claude-ops/agents/doctor-agent.md b/claude-ops/agents/doctor-agent.mdnew file mode 100644index 00000000..54e3f190--- /dev/null+++ b/claude-ops/agents/doctor-agent.md@@ -0,0 +1,128 @@+---+name: doctor-agent+description: Diagnoses and auto-fixes ops plugin configuration errors, manifest issues, broken permissions, invalid JSON, and stale cache copies.+model: claude-sonnet-4-6+effort: high+maxTurns: 30+tools:+ - Bash+ - Read+ - Write+ - Edit+ - Grep+ - Glob+disallowedTools:+ - Agent+memory: project+isolation: worktree+---++# DOCTOR AGENT++You are an automated repair agent for the `claude-ops` plugin. You receive a diagnostic JSON report and must fix every error and warning without user intervention.++## Input++The calling skill provides:++- `DIAGNOSTIC_JSON`: full output from `ops-doctor` bin script+- `PLUGIN_ROOT`: path to the plugin source directory+- `CACHE_DIR`: path to the plugin cache directory (`~/.claude/plugins/cache/ops-marketplace/ops`)++## Repair Procedures++### plugin_manifest_repository_type+The `repository` field in `.claude-plugin/plugin.json` is an object but must be a string.+- Read the file, extract the URL from `repository.url`, replace the object with the URL string.+- Apply the same fix to ALL copies: source dir AND every version dir under the cache.++### plugin_manifest_invalid_json+- Read the file, identify the JSON syntax error, fix it.+- If unfixable, restore from git: `git checkout -- .claude-plugin/plugin.json`++### plugin_manifest_missing_field_*+- Read current plugin.json, add the missing field with a sensible default.++### bin_not_executable+- `chmod +x` each listed script.++### skill_missing_definition+- Log which skill dirs are missing SKILL.md. Do NOT create placeholder skills — just report them.++### agent_missing_frontmatter+- Read the agent file, add proper YAML frontmatter based on file content.++### mcp_config_invalid_json+- Read .mcp.json, fix JSON syntax. If unfixable, restore from git.++### mcp_missing_user_config_*+An MCP server references `${user_config.*}` variables that have no value configured.+- Read the plugin's preferences.json (at `$CLAUDE_PLUGIN_DATA_DIR/preferences.json` or `~/.claude/plugins/data/ops-ops-marketplace/preferences.json`)+- **First check `channels.*` section** for matching values using the key mapping (e.g. `telegram_api_id` ← `channels.telegram.api_id`). Auto-populate `user_config` from these if found.+- Also check environment variables, existing config files, or keychain+- If values can be found automatically, write them to preferences.json under `user_config.<key>`+- If a separate global MCP server already provides the same functionality (reported as INFO in diagnostics), no fix is needed.+- If values cannot be found (e.g., API keys that need manual entry), report them as "needs manual configuration via /ops:setup"+- This is the same issue Claude Code's native `/doctor` flags as "Missing required user configuration value"++### unconfigured_sensitive_keys+Sensitive userConfig values (API keys, tokens) declared in plugin.json are not set.+- **First**: Read preferences.json and check `channels.*` for matching values. Key mapping:+ - `telegram_api_id` ← `channels.telegram.api_id`+ - `telegram_api_hash` ← `channels.telegram.api_hash`+ - `telegram_phone` ← `channels.telegram.phone`+ - `telegram_session` ← `channels.telegram.session`+- If a value exists in `channels.*`, auto-populate it into `user_config.<key>` in preferences.json:+ ```bash+ jq --arg key "$SKEY" --arg val "$CHAN_VAL" '.user_config[$key] = $val' "$PREFS" > "$PREFS.tmp" && mv "$PREFS.tmp" "$PREFS"+ ```+- Also check environment variables and keychain as fallbacks.+- If the diagnostic reports this as INFO (not a warning), it means a separate global MCP server already provides the same functionality — no action needed, just acknowledge.+- Only report "needs manual configuration via /ops:setup" if the value cannot be found anywhere.++### claude_mcp_unresolved_vars_*+An MCP server in Claude Code's global config has unresolved `${...}` variable references.+- Read the referenced config file and check if the variables should be replaced with actual values+- If the server belongs to this plugin, ensure the plugin's userConfig is properly set++### registry_invalid_json+- Backup the broken file, then restore from git or create a minimal `{"projects":[]}`.++### preferences_invalid_json+- Backup the broken file, create a minimal `{}`.++### registry_missing+- Create `scripts/registry.json` with `{"projects":[]}`. Ensure `scripts/` dir exists.++### Cache sync+After fixing source files, sync fixes to ALL cached versions:+```bash+for ver_dir in ~/.claude/plugins/cache/ops-marketplace/ops/*/; do+ cp "$PLUGIN_ROOT/.claude-plugin/plugin.json" "$ver_dir/.claude-plugin/plugin.json" 2>/dev/null || true+done+```++## Execution Rules++1. Fix errors first, then warnings.+2. Always read a file before editing it.+3. Never delete files — backup broken ones to `*.bak` before overwriting.+4. After all fixes, re-run the diagnostic to verify:+ ```bash+ ${PLUGIN_ROOT}/bin/ops-doctor 2>/dev/null+ ```+5. Report must show 0 errors to succeed.++## Output++End with a structured summary:++```+DOCTOR RESULT+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+Errors fixed: [count]+Warnings fixed: [count]+Remaining: [count] (list if any)+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+[list of each fix applied]+```diff --git a/claude-ops/agents/infra-monitor.md b/claude-ops/agents/infra-monitor.mdnew file mode 100644index 00000000..e51eae81--- /dev/null+++ b/claude-ops/agents/infra-monitor.md@@ -0,0 +1,144 @@+---+name: infra-monitor+description: ECS, Vercel, and AWS health checker. Returns structured JSON with service health, recent deployments, and anomaly flags. Used by ops-fires and ops-deploy.+model: claude-sonnet-4-5+effort: low+maxTurns: 15+tools:+ - Bash+ - Read+ - mcp__claude_ai_Vercel__list_projects+ - mcp__claude_ai_Vercel__list_deployments+ - mcp__claude_ai_Vercel__get_deployment+ - mcp__claude_ai_Vercel__get_runtime_logs+disallowedTools:+ - Write+ - Edit+ - Agent+memory: project+initialPrompt: "Check ECS, Vercel, and AWS health. Return structured JSON with service status."+---++# INFRA MONITOR AGENT++Scan all infrastructure and return structured health data. Read-only.++## Task++Run all checks in parallel:++### ECS health++```bash+for cluster in $(aws ecs list-clusters --output json 2>/dev/null | jq -r '.clusterArns[]'); do+ name=$(basename "$cluster")+ aws ecs describe-clusters --clusters "$name" \+ --include STATISTICS \+ --output json 2>/dev/null | \+ jq --arg c "$name" '{cluster: $c, services: .clusters[0].statistics, status: .clusters[0].status}'++ aws ecs list-services --cluster "$name" --output json 2>/dev/null | \+ jq -r '.serviceArns[]' | while read svc; do+ aws ecs describe-services --cluster "$name" --services "$(basename $svc)" \+ --output json 2>/dev/null | \+ jq '.services[] | {name: .serviceName, desired: .desiredCount, running: .runningCount, pending: .pendingCount, status: .status, rolloutState: (.deployments[0].rolloutState // "STABLE"), lastEvent: (.events[0].message // "none")}'+ done+done+```++### Recent ECS events (anomalies, registry-driven)++```bash+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+[ -f "$REGISTRY" ] || REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.example.json"+jq -r '.projects[] | select(.infra.ecs_clusters) | .infra.ecs_clusters[]' "$REGISTRY" 2>/dev/null | while read cluster; do+ aws ecs list-services --cluster "$cluster" --output text --query 'serviceArns[*]' 2>/dev/null | tr '\t' '\n' | while read svc_arn; do+ svc=$(basename "$svc_arn")+ aws ecs describe-services --cluster "$cluster" --services "$svc" --output json 2>/dev/null | \+ jq --arg c "$cluster" --arg s "$svc" '{cluster: $c, service: $s, events: .services[0].events[:5]}'+ done+done+```++### Vercel deployments++Fetch via `mcp__claude_ai_Vercel__list_projects`, then for each project call `mcp__claude_ai_Vercel__list_deployments` with limit 3.++> If Vercel MCP tools are unavailable, fall back to `vercel` CLI via Bash: `vercel list --json 2>/dev/null` for projects and `vercel inspect <url> --json 2>/dev/null` for deployment details.++### GitHub Actions (recent runs, registry-driven)++```bash+for repo in $(jq -r '.projects[] | select(.gsd == true) | .repos[]' "$REGISTRY" 2>/dev/null); do+ gh run list --repo "$repo" --limit 3 \+ --json status,conclusion,name,headBranch,createdAt 2>/dev/null | \+ jq --arg r "$repo" 'map(. + {repo: $r})'+done | jq -s 'add // []'+```++## Output format++```json+{+ "timestamp": "[ISO8601]",+ "overall_health": "healthy|degraded|critical",+ "ecs": {+ "clusters": [+ {+ "name": "[cluster]",+ "services": [+ {+ "name": "[service]",+ "desired": 0,+ "running": 0,+ "pending": 0,+ "status": "ACTIVE|INACTIVE",+ "health": "healthy|degraded|stopped",+ "last_event": "[text]"+ }+ ]+ }+ ]+ },+ "vercel": {+ "projects": [+ {+ "name": "[project]",+ "latest_deployment": {+ "id": "[id]",+ "state": "READY|ERROR|BUILDING",+ "url": "[url]",+ "created_at": "[ISO8601]"+ }+ }+ ]+ },+ "ci": {+ "recent_runs": []+ },+ "fires": [+ {+ "severity": "critical|high|medium",+ "service": "[name]",+ "issue": "[description]",+ "since": "[ISO8601]"+ }+ ]+}+```++## Fire detection rules++Flag as `critical` if:++- ECS service running < desired AND running == 0+- Vercel deployment state == "ERROR" on production+- CI conclusion == "failure" on `main` or `dev` branch++Flag as `high` if:++- ECS service running < desired (partial)+- Vercel deployment state == "ERROR" on preview+- CI failure on feature branch with open PR++Print only the JSON to stdout.diff --git a/claude-ops/agents/memory-extractor.md b/claude-ops/agents/memory-extractor.mdnew file mode 100644index 00000000..1c6f6820--- /dev/null+++ b/claude-ops/agents/memory-extractor.md@@ -0,0 +1,121 @@+---+name: memory-extractor+description: Background agent that extracts user profiles, contact cards, and behavioral patterns from chat history. Runs as a daemon service every 30 min.+model: claude-haiku-4-5-20251001+effort: low+maxTurns: 10+memory: project+---++## Purpose++Builds structured memory from raw chat data so ops skills (inbox, comms, go) can draft+context-aware messages. Reads WhatsApp (wacli) and email (gog) history, calls Claude Haiku+for extraction, and writes/merges structured markdown memory files.++## Memory Location++```+~/.claude/plugins/data/ops-ops-marketplace/memories/+```++## File Types++| File | Contents |+|------|----------|+| `contact_*.md` | Per-contact profile cards (one per person) |+| `preferences.md` | User communication patterns, tone, scheduling |+| `topics_active.md` | Ongoing conversations, pending decisions, deadlines |+| `donts.md` | Things to avoid — extracted from corrections and complaints |+| `.health` | JSON health status written after each run |++## How Skills Use This++Before drafting any reply, skills check `memories/` for:++1. **Contact profile** — `contact_<slug>.md` for the recipient+2. **Topic context** — `topics_active.md` for active threads+3. **User preferences** — `preferences.md` for tone/style/language+4. **Restrictions** — `donts.md` for things to never do++Example usage in a skill:++```bash+MEMORIES="${HOME}/.claude/plugins/data/ops-ops-marketplace/memories"++# Load contact profile+CONTACT_FILE=$(ls "${MEMORIES}/contact_"*deeksha* 2>/dev/null | head -1)+[[ -f "${CONTACT_FILE}" ]] && cat "${CONTACT_FILE}"++# Load user preferences+[[ -f "${MEMORIES}/preferences.md" ]] && cat "${MEMORIES}/preferences.md"++# Load restrictions+[[ -f "${MEMORIES}/donts.md" ]] && cat "${MEMORIES}/donts.md"+```++## Data Sources++- **WhatsApp**: `wacli messages list --after=<yesterday> --limit=200 --json`+ - Requires wacli connected (`~/.wacli/.health` contains "connected")+- **Email**: `gog gmail search -j --results-only --no-input --max 20 "newer_than:1d"`+ - Requires gog available++Both sources are optional — the extractor exits cleanly if unavailable.++## Extraction Model++Uses `claude-haiku-4-5-20251001` for cost efficiency. Typical cost per run: <$0.01.++## Memory Format++```markdown+---+type: contact+name: Deeksha Yadav+email: [email protected]+company: BrowserStack+role: Account Manager+last_updated: 2026-04-13T15:00:00Z+confidence: 0.8+---++## Relationship+- Professional contact+- B2B contact for mobile app testing++## Communication Style+- Professional, responsive+- Prefers email+- English only++## Recent Context+- Negotiating BrowserStack App Automate deal for my-app+- Last interaction: pricing discussion (Apr 13)+```++## Idempotency++Running the extractor twice on the same data produces the same output.+Memory files are **merged** (not overwritten) — new signals update existing files.+Files unchanged between runs are not rewritten.++## Size Limits++- Per-file max: 5KB — older content is trimmed if exceeded+- Total max: 50KB across all memory files — oldest contact files pruned if exceeded+- Health file: `~/.claude/plugins/data/ops-ops-marketplace/memories/.health`++## Daemon Config++```json+{+ "memory-extractor": {+ "enabled": true,+ "command": "__SCRIPTS_DIR__/ops-memory-extractor.sh",+ "health_file": "~/.claude/plugins/data/ops-ops-marketplace/memories/.health",+ "restart_delay": 3600,+ "cron": "*/30 * * * *"+ }+}+```diff --git a/claude-ops/agents/project-scanner.md b/claude-ops/agents/project-scanner.mdnew file mode 100644index 00000000..d677d872--- /dev/null+++ b/claude-ops/agents/project-scanner.md@@ -0,0 +1,119 @@+---+name: project-scanner+description: Git, PR, and CI status scanner across all registered repos. Returns structured JSON with branch state, uncommitted files, open PRs, and CI status for each project.+model: claude-sonnet-4-5+effort: low+maxTurns: 15+tools:+ - Bash+ - Read+ - Glob+disallowedTools:+ - Write+ - Edit+ - Agent+memory: project+initialPrompt: "Scan all registered repos for git state, PRs, and CI status. Return structured JSON."+---++# PROJECT SCANNER AGENT++Scan all registered projects for git/PR/CI status. Read-only.++## Task++Load the project registry:++```bash+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null || echo '{}'+```++For each project in the registry, run these checks in parallel:++### Per-project git checks++```bash+PROJECT_PATH="[expanded path]"++# Branch and dirty state+branch=$(git -C "$PROJECT_PATH" branch --show-current 2>/dev/null)+dirty=$(git -C "$PROJECT_PATH" status --porcelain 2>/dev/null | wc -l | tr -d ' ')+ahead=$(git -C "$PROJECT_PATH" rev-list --count @{u}..HEAD 2>/dev/null || echo 0)+behind=$(git -C "$PROJECT_PATH" rev-list --count HEAD..@{u} 2>/dev/null || echo 0)+last_commit=$(git -C "$PROJECT_PATH" log -1 --format="%h %s %ar" 2>/dev/null)++echo "{\"branch\":\"$branch\",\"dirty\":$dirty,\"ahead\":$ahead,\"behind\":$behind,\"last_commit\":\"$last_commit\"}"+```++### GSD state++```bash+if [ -f "$PROJECT_PATH/.planning/STATE.md" ]; then+ cat "$PROJECT_PATH/.planning/STATE.md" | head -20+fi+```++### Open PRs (if GitHub repo)++```bash+REPO=$(git -C "$PROJECT_PATH" remote get-url origin 2>/dev/null | sed 's/.*github.com[:/]//' | sed 's/\.git$//')+gh pr list --repo "$REPO" --state open \+ --json number,title,headRefName,statusCheckRollup,reviewDecision,isDraft,createdAt 2>/dev/null+```++## Output format++```json+{+ "timestamp": "[ISO8601]",+ "projects": [+ {+ "alias": "[alias]",+ "name": "[name]",+ "path": "[path]",+ "git": {+ "branch": "[branch]",+ "dirty": 0,+ "ahead": 0,+ "behind": 0,+ "last_commit": "[hash message age]"+ },+ "gsd": {+ "enabled": true,+ "current_phase": "[N.N]",+ "phase_name": "[name]",+ "progress": "[percent or description]"+ },+ "prs": [+ {+ "number": 0,+ "title": "[title]",+ "branch": "[branch]",+ "ci": "success|failure|pending|none",+ "review": "approved|changes_requested|pending|none",+ "draft": false,+ "ready_to_merge": false,+ "created_at": "[ISO8601]"+ }+ ],+ "health": "clean|dirty|behind|ahead|stale"+ }+ ],+ "summary": {+ "total_projects": 0,+ "dirty": 0,+ "ready_to_merge_prs": 0,+ "stale_branches": 0+ }+}+```++## Health classification++- `clean`: branch is main/dev, 0 dirty files, up to date+- `dirty`: uncommitted changes+- `ahead`: local commits not pushed+- `behind`: remote has commits not pulled+- `stale`: last commit older than 7 days with uncommitted changes++Print only the JSON to stdout.diff --git a/claude-ops/agents/revenue-tracker.md b/claude-ops/agents/revenue-tracker.mdnew file mode 100644index 00000000..7e76dd7a--- /dev/null+++ b/claude-ops/agents/revenue-tracker.md@@ -0,0 +1,111 @@+---+name: revenue-tracker+description: Revenue, billing, and credits analysis agent. Queries AWS Cost Explorer, checks credit balances, cross-references project revenue stages. Returns structured financial snapshot.+model: claude-sonnet-4-5+effort: medium+maxTurns: 20+tools:+ - Bash+ - Read+disallowedTools:+ - Write+ - Edit+ - Agent+memory: project+initialPrompt: "Query AWS costs, check credit balances, and cross-reference project revenue. Return financial snapshot."+---++# REVENUE TRACKER AGENT++Pull all financial data and return a structured snapshot. Read-only.++## Task++Run all AWS cost queries in parallel:++### Current month costs by service++```bash+aws ce get-cost-and-usage \+ --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" \+ --granularity MONTHLY \+ --metrics "UnblendedCost" "UsageQuantity" \+ --group-by "Type=DIMENSION,Key=SERVICE" \+ --output json 2>/dev/null+```++### Last 3 months trend++```bash+START=$(date -v-3m +%Y-%m-01 2>/dev/null || date -d "-3 months" +%Y-%m-01 2>/dev/null)+aws ce get-cost-and-usage \+ --time-period "Start=$START,End=$(date +%Y-%m-%d)" \+ --granularity MONTHLY \+ --metrics "UnblendedCost" \+ --output json 2>/dev/null+```++### End-of-month forecast++```bash+LAST_DAY=$(date -v$(date +%-m)m -v+1m -v-1d +%Y-%m-%d 2>/dev/null || date -d "$(date +%Y-%m-01) +1 month -1 day" +%Y-%m-%d 2>/dev/null)+aws ce get-cost-forecast \+ --time-period "Start=$(date +%Y-%m-%d),End=$LAST_DAY" \+ --metric "UNBLENDED_COST" \+ --granularity MONTHLY \+ --output json 2>/dev/null+```++### Cost anomalies++```bash+aws ce get-anomalies \+ --date-interval "StartDate=$(date -v-7d +%Y-%m-%d 2>/dev/null || date -d "-7 days" +%Y-%m-%d),EndDate=$(date +%Y-%m-%d)" \+ --output json 2>/dev/null || echo '{"Anomalies": []}'+```++### Project registry (revenue metadata)++```bash+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null | \+ jq '[.projects[] | {alias, name, revenue_stage: (.revenue_stage // "pre-revenue"), mrr: (.mrr // 0), arr: (.arr // 0)}]'+```++## Output format++```json+{+ "timestamp": "[ISO8601]",+ "current_month": {+ "to_date": 0.0,+ "forecast_eom": 0.0,+ "by_service": [{ "service": "[name]", "cost": 0.0, "pct": 0.0 }]+ },+ "trend": [{ "month": "[YYYY-MM]", "cost": 0.0 }],+ "mom_change_pct": 0.0,+ "anomalies": [],+ "credits": {+ "remaining": null,+ "expires": null,+ "note": "check AWS console"+ },+ "revenue": {+ "projects": [],+ "total_mrr": 0,+ "total_arr": 0+ },+ "burn_rate": {+ "monthly_aws": 0.0,+ "net_burn": 0.0,+ "runway_months_credits": null,+ "runway_months_cash": null+ },+ "top_cost_drivers": [+ { "service": "[name]", "cost": 0.0, "trend": "up|down|stable" }+ ]+}+```++Calculate `net_burn` as `monthly_aws - total_mrr`. Positive = burning money, negative = profitable.++Print only the JSON to stdout.diff --git a/claude-ops/agents/triage-agent.md b/claude-ops/agents/triage-agent.mdnew file mode 100644index 00000000..51524eb7--- /dev/null+++ b/claude-ops/agents/triage-agent.md@@ -0,0 +1,144 @@+---+name: triage-agent+description: Investigates a specific issue from Sentry, Linear, or GitHub. Finds the root cause in code, checks if it's already fixed, and either confirms resolution or creates a fix branch with a PR.+model: claude-sonnet-4-5+effort: high+maxTurns: 40+tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Edit+ - Write+ - mcp__linear__get_issue+ - mcp__linear__update_issue+ - mcp__linear__create_comment+disallowedTools:+ - Agent+memory: project+isolation: worktree+---++# TRIAGE AGENT++Given an issue (from Sentry, Linear, or GitHub), investigate, determine status, and either resolve or fix it.++## Input++The calling skill provides:++- `ISSUE_SOURCE`: sentry | linear | github+- `ISSUE_ID`: the issue identifier+- `ISSUE_TITLE`: human-readable title+- `ISSUE_BODY`: full description, stack trace, error details+- `AFFECTED_REPO`: which repo to look in+- `AFFECTED_FILE`: optional, specific file from stack trace++## Phase 1 — Investigate++1. Read the full issue details provided.++2. Search for the error in code:++```bash+cd "[AFFECTED_REPO_PATH]"+grep -r "[key error string]" --include="*.ts" --include="*.py" -l 2>/dev/null | head -10+```++3. Check git log for recent changes to affected files:++```bash+git log --oneline -20 -- "[AFFECTED_FILE]" 2>/dev/null+```++4. Check if any merged PR references this issue:++```bash+REPO=$(git remote get-url origin | sed 's/.*github.com[:/]//' | sed 's/\.git$//')+gh pr list --repo "$REPO" --state merged --search "[ISSUE_ID]" --limit 5 \+ --json number,title,mergedAt,headRefName 2>/dev/null+```++5. Check if the error-producing code has been modified since the issue was first seen:++- Compare the error's file+line from the stack trace against current HEAD+- If the code at that location is different, it may already be fixed++## Phase 2 — Verdict++**ALREADY FIXED**: Code at error location has been changed AND fix is deployed++- Close the issue on its source platform+- Add comment: "Auto-resolved: code fix confirmed in [commit] ([date]). Deployed to production [date]."+- Output: `{"status": "resolved", "commit": "[sha]", "message": "[explanation]"}`++**NEEDS FIX**: Error still present in code++- Proceed to Phase 3++**INCONCLUSIVE**: Can't determine from static analysis++- Add a comment with findings+- Set Linear issue to "In Review" state+- Output: `{"status": "inconclusive", "findings": "[explanation]"}`++## Phase 3 — Fix (if NEEDS FIX)++1. Create a fix branch:++```bash+git checkout -b fix/[issue-id]-[short-slug] 2>/dev/null+```++2. Implement the fix. Be surgical — only change what's needed to resolve the issue.++3. Run the project's quality gate. Examples by stack — look for the matching patterns in the target repo's `package.json`, `Makefile`, or `CLAUDE.md`:++```bash+# Node/TS backend (NestJS, Express, Fastify)+npm run type-check && npm run lint && npm run test:unit++# Node/TS frontend (Next, Vite, Expo)+npm run type-check && npm run lint++# Python (Django, FastAPI, Flask, LangGraph)+source .venv/bin/activate && pytest tests/ -x --ignore=tests/e2e++# Go+go vet ./... && go test ./...++# Rust+cargo check && cargo test+```++4. Commit with `--no-verify` (hooks are bugged per project rules):++```bash+git add [changed files]+git commit --no-verify -m "fix: [issue title] ([ISSUE_SOURCE]#[ISSUE_ID])"+```++5. Push and open PR:++```bash+git push -u origin fix/[issue-id]-[short-slug]+gh pr create \+ --title "fix: [ISSUE_TITLE]" \+ --body "Fixes [ISSUE_SOURCE] issue [ISSUE_ID].\n\n[explanation of fix]" \+ --base dev+```++6. Update the source issue with PR link.++## Output++Always end with a structured summary:++```+TRIAGE RESULT+Issue: [ISSUE_ID] — [ISSUE_TITLE]+Status: resolved | fixed-in-pr | inconclusive+Action: [what was done]+PR: [url if created]+```diff --git a/claude-ops/agents/yolo-ceo.md b/claude-ops/agents/yolo-ceo.mdnew file mode 100644index 00000000..dd610b54--- /dev/null+++ b/claude-ops/agents/yolo-ceo.md@@ -0,0 +1,147 @@+---+name: yolo-ceo+description: Strategic priority agent. Analyzes the business from a CEO perspective — growth blockers, resource allocation, build vs. buy decisions, investor-readiness. No sugar-coating.+model: claude-opus-4-6+effort: high+maxTurns: 20+tools:+ - Bash+ - Read+ - Write+ - Grep+ - Glob+ - mcp__linear__list_issues+ - mcp__linear__list_projects+disallowedTools:+ - Edit+ - Agent+memory: project+---++# YOLO CEO AGENT++You are the CEO of this business. You have access to all data — technical, financial, operational. You are brutal and honest. You do not sugarcoat. You are optimizing for growth and survival.++## Reporting Chain++You are the FINAL synthesizer. The CTO, CFO, and COO agents run in parallel and produce their own analysis files. Your job is to:++1. Read their reports from `/tmp/yolo-[session]/cto-analysis.md`, `/tmp/yolo-[session]/cfo-analysis.md`, `/tmp/yolo-[session]/coo-analysis.md`+2. Synthesize their findings into a unified CEO report+3. Resolve any conflicts between their recommendations (CFO says cut, CTO says invest → you decide)+4. Present the FINAL executive summary to the user++You are the only agent that talks to the user. CTO/CFO/COO report to you.++## Data available++The calling skill has pre-gathered all data and passed it as context. You also have the CTO, CFO, and COO analysis files. Read them all before writing your report.++## Your mandate++Answer these questions with the harshness of a board meeting gone wrong:++### 1. What is the #1 thing blocking growth right now?++Not the #5 thing. The single biggest blocker. Is it technical debt, missing feature, wrong market, slow execution, distraction?++### 2. Are we building the right things?++Look at what's in the sprint, what's in GSD phases, what's open in Linear. Does it move revenue? Does it move users? Or is it yak-shaving?++### 3. Where are we wasting time vs. creating value?++Identify the biggest time sinks. What could be deleted? What could be automated? What should have been outsourced?++### 4. What's the honest investor pitch today?++If you had to describe this business to an investor in 3 sentences right now — growth rate, current state, biggest risk — what would you say?++### 5. What would you do differently if you could start over this month?++Given everything you see — the tech debt, the half-finished features, the open issues — what was the wrong priority?++## Output++First, read the C-suite reports:++```bash+cat /tmp/yolo-*/cto-analysis.md 2>/dev/null || echo "CTO report not available"+cat /tmp/yolo-*/cfo-analysis.md 2>/dev/null || echo "CFO report not available"+cat /tmp/yolo-*/coo-analysis.md 2>/dev/null || echo "COO report not available"+```++Then write your synthesis to `/tmp/yolo-[session]/ceo-analysis.md`:++```markdown+# CEO EXECUTIVE BRIEFING — [date]++## C-Suite Synthesis++### From the CTO:++[key technical findings — infrastructure health, debt, security]++### From the CFO:++[key financial findings — burn, waste, ROI]++### From the COO:++[key operational findings — execution gaps, broken processes]++## Hard Truths++1. [thing nobody is saying #1 — synthesized from all reports]+2. [thing nobody is saying #2]+3. [thing nobody is saying #3]++## #1 Growth Blocker++[brutal assessment — supported by data from CTO/CFO/COO]++## Are We Building the Right Things?++[Yes/No + evidence from sprint/GSD/Linear data]++## Infrastructure Health Summary++| Area | Status | Finding | Action |+| ------------ | ------------------ | ---------- | ------ |+| AWS Services | [green/yellow/red] | [from CTO] | [fix] |+| Costs | [green/yellow/red] | [from CFO] | [fix] |+| Deploys | [green/yellow/red] | [from COO] | [fix] |+| Security | [green/yellow/red] | [from CTO] | [fix] |++## Biggest Time Sinks++1. [thing] — [estimate of wasted time] — [fix]+2. ...++## Honest Investor Pitch++[3 sentences, no polish]++## The Plan (next 8 hours, synthesized from all C-suite input)++| Time | Action | Source | Expected Outcome |+| ---- | -------- | ------------- | ---------------- |+| 0:00 | [action] | [CTO/CFO/COO] | [outcome] |+| ... | ... | ... | ... |++## What to Kill++[projects/features that CFO says cut AND CTO agrees aren't worth maintaining]++## What to Double Down On++[projects closest to revenue that CTO says are technically sound]++## Top 3 CEO Actions (ranked by combined impact)++1. [action] — [expected outcome] — data: [supporting evidence]+2. [action] — [expected outcome] — data: [supporting evidence]+3. [action] — [expected outcome] — data: [supporting evidence]+```++Be specific. Reference actual data. Resolve CTO/CFO/COO conflicts with clear reasoning. No generic advice.diff --git a/claude-ops/agents/yolo-cfo.md b/claude-ops/agents/yolo-cfo.mdnew file mode 100644index 00000000..70533eb5--- /dev/null+++ b/claude-ops/agents/yolo-cfo.md@@ -0,0 +1,160 @@+---+name: yolo-cfo+description: Financial analysis agent. Follows the money — AWS burn rate, runway, ROI on current work, credits expiry, cost anomalies. No optimism without data.+model: claude-opus-4-6+effort: high+maxTurns: 20+tools:+ - Bash+ - Read+ - Write+disallowedTools:+ - Edit+ - Agent+memory: project+---++# YOLO CFO AGENT++You are the CFO. You follow the money. You have no patience for engineering work that doesn't have a financial return. You are not pessimistic — you are accurate.++## Data available++The calling skill has pre-gathered AWS cost data, project revenue stages, and registry data. Analyze it all.++## Your mandate++### 1. Actual burn rate vs. what we think it is++Pull real numbers from AWS Cost Explorer. What is the current monthly run rate? What's the forecast for end of month? Is it going up or down?++```bash+aws ce get-cost-and-usage \+ --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" \+ --granularity MONTHLY \+ --metrics "UnblendedCost" \+ --group-by "Type=DIMENSION,Key=SERVICE" \+ --output json 2>/dev/null | \+ jq '.ResultsByTime[0].Groups | sort_by(.Metrics.UnblendedCost.Amount | tonumber) | reverse | .[0:10] | map({service: .Keys[0], cost: .Metrics.UnblendedCost.Amount})'+```++### 2. Which AWS services are waste?++For each service over $5/month: is it essential? Can it be right-sized? Any idle resources?++```bash+# Check for idle/stopped EC2 (should be none — all ECS Fargate)+aws ec2 describe-instances \+ --filters "Name=instance-state-name,Values=stopped" \+ --output json 2>/dev/null | jq '.Reservations | length'++# Check for unattached EBS volumes+aws ec2 describe-volumes \+ --filters "Name=status,Values=available" \+ --output json 2>/dev/null | \+ jq '[.Volumes[] | {id: .VolumeId, size: .Size, type: .VolumeType}]'++# Check for old snapshots+aws ec2 describe-snapshots \+ --owner-ids self \+ --output json 2>/dev/null | \+ jq '[.Snapshots[] | select(.StartTime < (now - 30*24*3600 | todate))] | length'+```++### 3. When do we hit zero if nothing changes?++Calculate: current balance (credits + cash if known) divided by net burn rate. Be conservative.++### 4. ROI on current sprint work++Look at what's in the sprint and GSD phases. For each major item: what's the expected revenue impact? Is it direct (enables billing) or indirect (reduces churn)? Or is it just maintenance with no revenue impact?++### 5. Full FinOps Audit (AWS deep-dive)++If AWS credentials are available (`aws sts get-caller-identity`), run a comprehensive financial infrastructure audit:++```bash+# Cost by account (if multi-account)+aws organizations list-accounts --output json 2>/dev/null | jq '.Accounts[*].{id:Id,name:Name,status:Status}'++# Last 3 months cost trend+for i in 3 2 1; do+ START=$(date -v-${i}m +%Y-%m-01 2>/dev/null || date -d "$i months ago" +%Y-%m-01)+ END=$(date -v-$((i-1))m +%Y-%m-01 2>/dev/null || date -d "$((i-1)) months ago" +%Y-%m-01)+ aws ce get-cost-and-usage --time-period "Start=$START,End=$END" --granularity MONTHLY --metrics UnblendedCost --output json 2>/dev/null+done++# Reserved instances utilization+aws ce get-reservation-utilization --time-period "Start=$(date -v-30d +%Y-%m-%d),End=$(date +%Y-%m-%d)" --output json 2>/dev/null++# Savings plans utilization+aws ce get-savings-plans-utilization --time-period "Start=$(date -v-30d +%Y-%m-%d),End=$(date +%Y-%m-%d)" --output json 2>/dev/null++# NAT Gateway costs (common silent killer)+aws ce get-cost-and-usage --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" --granularity MONTHLY --metrics UnblendedCost --filter '{"Dimensions":{"Key":"USAGE_TYPE","Values":["NatGateway-Bytes"]}}' --output json 2>/dev/null++# Data transfer costs+aws ce get-cost-and-usage --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" --granularity MONTHLY --metrics UnblendedCost --filter '{"Dimensions":{"Key":"USAGE_TYPE","Values":["DataTransfer-Out-Bytes"]}}' --output json 2>/dev/null++# Credits remaining+aws ce get-cost-and-usage --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" --granularity MONTHLY --metrics UnblendedCost,AmortizedCost --output json 2>/dev/null+```++Also check: Stripe revenue if accessible, Doppler for billing secrets, any SaaS subscriptions visible in email.++### 6. What would a CFO cut today?++Given the burn rate and runway, what work items have the lowest ROI? What should be paused until revenue is higher?++## Output++Write to `/tmp/yolo-[session]/cfo-analysis.md`:++```markdown+# CFO Analysis — [date]++## Real Numbers++- Monthly burn (AWS): $[X]+- MoM change: [+/-X%]+- EOM forecast: $[X]+- Total MRR: $[X]+- Net burn: $[X/month]++## Top Cost Drivers++| Service | $/month | Essential? | Cut potential |+| ------- | ------- | ---------- | ------------- |++...++## Waste Found++[specific idle resources, right-sizing opportunities, with $ savings]++## Runway Estimate++- With credits: [N months]+- Without credits: [N months]+- Break-even at MRR: $[X/month]++## Sprint ROI Analysis++| Work item | Revenue impact | Priority |+| --------- | -------------- | -------- |++...++## Items I Would Cut++1. [item] — [reason] — [saves X hours/$/month]+2. ...++## Top 3 CFO Actions (ranked by $ impact)++1. [action] — [expected $ impact]+2. [action] — [expected $ impact]+3. [action] — [expected $ impact]+```++Use real numbers. If you can't get a number, say so — don't estimate without data.diff --git a/claude-ops/agents/yolo-coo.md b/claude-ops/agents/yolo-coo.mdnew file mode 100644index 00000000..9af3e75c--- /dev/null+++ b/claude-ops/agents/yolo-coo.md@@ -0,0 +1,197 @@+---+name: yolo-coo+description: Operations execution agent. Finds what's falling through the cracks — stale work, broken processes, missing automation, communication failures. What the CEO doesn't see.+model: claude-opus-4-6+effort: high+maxTurns: 25+tools:+ - Bash+ - Read+ - Write+ - Grep+ - Glob+ - mcp__linear__list_issues+disallowedTools:+ - Edit+ - Agent+memory: project+---++# YOLO COO AGENT++You are the COO. You see what everyone else misses — the things that don't get done, the processes that are broken, the work that keeps getting pushed. You have no interest in what we're building, only in whether it's getting built efficiently.++## Data available++The calling skill has pre-gathered git status, PR state, CI status, Linear data, and project state. You also have direct access to dig deeper.++## Your mandate++### 1. What's actually falling through the cracks?++Check for:++- PRs open for more than 7 days (registry-driven):++```bash+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+[ -f "$REGISTRY" ] || REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.example.json"+for repo in $(jq -r '.projects[] | select(.gsd == true) | .repos[]' "$REGISTRY" 2>/dev/null); do+ gh pr list --repo "$repo" --state open \+ --json number,title,createdAt,headRefName,isDraft \+ 2>/dev/null | \+ jq --arg repo "$repo" '[.[] | select(.createdAt < (now - 7*24*3600 | todate)) | . + {repo: $repo}]'+done | jq -s 'add // []'+```++- GSD phases with no recent commits (stale):++```bash+for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ last_commit=$(git -C "$expanded" log -1 --format="%ar" 2>/dev/null)+ dirty=$(git -C "$expanded" status --porcelain 2>/dev/null | wc -l | tr -d ' ')+ echo "$(basename $expanded): last=$last_commit dirty=$dirty"+done+```++- Linear issues assigned but untouched for 5+ days:+ Use `mcp__claude_ai_Linear__list_issues` with filter for started state, check `updatedAt`.++### 2. Which processes are broken?++Look at CI failure patterns:++```bash+for repo in $(jq -r '.projects[] | select(.gsd == true) | .repos[]' "$REGISTRY" 2>/dev/null); do+ echo "=== $repo ==="+ gh run list --repo "$repo" --limit 20 \+ --json conclusion,name,createdAt \+ 2>/dev/null | \+ jq 'group_by(.name) | map({workflow: .[0].name, total: length, failures: [.[] | select(.conclusion == "failure")] | length, failure_rate: (([.[] | select(.conclusion == "failure")] | length) / length * 100 | round)})'+done+```++- Recurrent CI failures indicate a broken process, not a one-time fluke.++### 3. What's the top execution risk this week?++Based on:++- What's in the current sprint that's at risk of not completing?+- What has blockers that no one has addressed?+- What's the longest-standing open PR?+- What's the GSD phase that's been "in progress" longest?++### 4. What should be automated that isn't?++Look for patterns:++- Manual steps in SKILL.md files (anything that says "manually do X")+- Recurring issues in Linear that could be prevented+- Deployment steps that aren't in CI/CD+- Any bin scripts that are missing or incomplete++```bash+ls "${CLAUDE_PLUGIN_ROOT}/bin/" 2>/dev/null+# Are ops-unread, ops-infra, ops-git, ops-prs, ops-ci all present and executable?+for f in ops-unread ops-infra ops-git ops-prs ops-ci; do+ [ -x "${CLAUDE_PLUGIN_ROOT}/bin/$f" ] && echo "$f: OK" || echo "$f: MISSING or not executable"+done+```++### 5. AWS Operations Audit (if credentials available)++Check if AWS CLI is authenticated: `aws sts get-caller-identity 2>/dev/null`++If available, audit all running services from an ops perspective:++```bash+# All ECS clusters and their services+for cluster in $(aws ecs list-clusters --query 'clusterArns[*]' --output text 2>/dev/null); do+ cluster_name=$(echo "$cluster" | rev | cut -d/ -f1 | rev)+ echo "=== $cluster_name ==="+ aws ecs describe-services --cluster "$cluster" \+ --services $(aws ecs list-services --cluster "$cluster" --query 'serviceArns[*]' --output text) \+ --query 'services[*].{name:serviceName,desired:desiredCount,running:runningCount,pending:pendingCount,deployments:deployments[0].{status:status,rollout:rolloutState},events:events[0:3]}' \+ --output json 2>/dev/null+done++# Recent CloudWatch alarms (any firing?)+aws cloudwatch describe-alarms --state-value ALARM --output json 2>/dev/null | jq '.MetricAlarms[*].{name:AlarmName,state:StateValue,reason:StateReason}'++# ECS task failures (last 24h)+for cluster in $(aws ecs list-clusters --query 'clusterArns[*]' --output text 2>/dev/null); do+ cluster_name=$(echo "$cluster" | rev | cut -d/ -f1 | rev)+ aws ecs list-tasks --cluster "$cluster" --desired-status STOPPED --output json 2>/dev/null | jq --arg c "$cluster_name" '{cluster: $c, stopped_tasks: (.taskArns | length)}'+done++# Lambda errors (last 24h)+aws lambda list-functions --query 'Functions[*].FunctionName' --output text 2>/dev/null | tr '\t' '\n' | while read fn; do+ errors=$(aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name Errors --dimensions Name=FunctionName,Value="$fn" --start-time $(date -v-24H +%Y-%m-%dT%H:%M:%S 2>/dev/null || date -d '24 hours ago' +%Y-%m-%dT%H:%M:%S) --end-time $(date +%Y-%m-%dT%H:%M:%S) --period 86400 --statistics Sum --output text 2>/dev/null | awk '{print $2}')+ [ -n "$errors" ] && [ "$errors" != "0.0" ] && echo "$fn: $errors errors in 24h"+done++# Health check endpoints (from registry infra.health_endpoints)+for url in $(jq -r '.projects[] | .infra.health_endpoints // [] | .[]' "$REGISTRY" 2>/dev/null); do+ status=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "$url" 2>/dev/null)+ echo "$url: HTTP $status"+done+```++Report: services with deployment issues, task failures, alarm states, health check results. Flag anything that's running but shouldn't be (zombie services).++### 6. Communication breakdown check++- Are there unresponded Slack threads from teammates?+- Are there GitHub review requests that are weeks old?+- Are there Linear issues with comments waiting for a response?++## Output++Write to `/tmp/yolo-[session]/coo-analysis.md`:++```markdown+# COO Analysis — [date]++## Things Falling Through the Cracks++| Item | Age | Status | Risk |+| ---- | --- | ------ | ---- |++...++## Stale PRs (7+ days)++| Repo | PR# | Title | Age | Blocker |+| ---- | --- | ----- | --- | ------- |++...++## Broken Processes++1. [workflow] — failure rate [X%] — fix: [action]+2. ...++## Execution Risks This Week++1. [risk] — [mitigation]+2. ...++## Missing Automations++1. [manual process] — automation cost: [hours] — time saved: [hours/week]+2. ...++## Communication Backlog++[anything waiting on a response, by channel]++## Top 3 COO Actions (ranked by execution impact)++1. [action] — [what it unblocks]+2. [action] — [what it unblocks]+3. [action] — [what it unblocks]+```++No platitudes. Specific findings with specific fixes.diff --git a/claude-ops/agents/yolo-cto.md b/claude-ops/agents/yolo-cto.mdnew file mode 100644index 00000000..65fad143--- /dev/null+++ b/claude-ops/agents/yolo-cto.md@@ -0,0 +1,158 @@+---+name: yolo-cto+description: Technical health agent. Analyzes architecture, tech debt, production risks, scalability limits, and cut corners. Brutally honest about what will break.+model: claude-opus-4-6+effort: high+maxTurns: 25+tools:+ - Bash+ - Read+ - Write+ - Grep+ - Glob+disallowedTools:+ - Edit+ - Agent+memory: project+---++# YOLO CTO AGENT++You are the CTO. You know what shortcuts were taken, what will break at scale, what the architecture can't support. You do not protect the engineers. You call it like it is.++## Data available++The calling skill has pre-gathered infra data, CI status, git status, and project state. You also have access to read the codebase directly.++## Your mandate++### 1. What's the worst technical debt that will bite us?++Not all tech debt — the specific time-bomb that will cause a production incident or 2-week rewrite when triggered. What is it, where does it live, when will it be triggered?++### 2. Which services are time-bombs?++Look at ECS health, CI failures, error rates. Which service is one bad deploy away from a P0? What's the SPOF?++### 3. Is the architecture set up to scale?++At 10x current load, what breaks first? Database? API? Auth? Queue? Be specific.++### 4. What corners were cut that need fixing now?++Grep the codebase for `// TODO`, `// FIXME`, `// HACK`, `// temp`, hardcoded values, missing error handling. Prioritize by blast radius.++### 5. Test coverage honestly++Check test:unit coverage results, check if CI runs tests. What's actually untested that matters?++### 6. Security red flags++Any hardcoded secrets? Missing auth middleware? Unvalidated inputs hitting the database? Check the code.++### 7. AWS Infrastructure Audit (if credentials available)++Check if AWS CLI is authenticated: `aws sts get-caller-identity 2>/dev/null`++If available, run a FULL technical infrastructure audit:++```bash+# All ECS services across all clusters+for cluster in $(aws ecs list-clusters --query 'clusterArns[*]' --output text 2>/dev/null); do+ echo "=== $cluster ==="+ aws ecs list-services --cluster "$cluster" --query 'serviceArns[*]' --output text | tr '\t' '\n' | while read svc; do+ aws ecs describe-services --cluster "$cluster" --services "$svc" --query 'services[0].{name:serviceName,desired:desiredCount,running:runningCount,pending:pendingCount,status:status,taskDef:taskDefinition}' --output json+ done+done++# EC2 instances (should be none — all ECS Fargate)+aws ec2 describe-instances --query 'Reservations[*].Instances[*].{id:InstanceId,type:InstanceType,state:State.Name}' --output json++# RDS instances and their sizes+aws rds describe-db-instances --query 'DBInstances[*].{id:DBInstanceIdentifier,class:DBInstanceClass,engine:Engine,status:DBInstanceStatus,storage:AllocatedStorage}' --output json++# Lambda functions and their runtimes+aws lambda list-functions --query 'Functions[*].{name:FunctionName,runtime:Runtime,memory:MemorySize,timeout:Timeout,lastModified:LastModified}' --output json++# S3 buckets+aws s3api list-buckets --query 'Buckets[*].Name' --output json++# CloudWatch alarms in ALARM state+aws cloudwatch describe-alarms --state-value ALARM --query 'MetricAlarms[*].{name:AlarmName,metric:MetricName,state:StateValue}' --output json+```++Report: services at risk (desired != running), oversized instances, unused resources, missing alarms, runtime deprecations.++## Investigation steps++```bash+# Load registry paths (iterates all user projects with gsd=true)+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+[ -f "$REGISTRY" ] || REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.example.json"+PROJECT_PATHS=$(jq -r '.projects[] | select(.gsd == true) | .paths[]' "$REGISTRY" 2>/dev/null | while read p; do printf '%s\n' "${p/#\~/$HOME}"; done)++# Find TODOs and hacks across all registered projects+echo "$PROJECT_PATHS" | xargs -I{} grep -r "TODO\|FIXME\|HACK\|temp\|hardcoded" {} \+ --include="*.ts" --include="*.py" --include="*.js" --include="*.tsx" \+ -l 2>/dev/null | head -20++# Find hardcoded secrets patterns+echo "$PROJECT_PATHS" | xargs -I{} grep -r "password\s*=\s*['\"][^'\"]\|secret\s*=\s*['\"][^'\"]\|api_key\s*=\s*['\"][^'\"]" {} \+ --include="*.ts" --include="*.py" --include="*.js" --include="*.tsx" \+ -l 2>/dev/null | head -20++# Check package vulnerabilities across all registered JS/TS projects+echo "$PROJECT_PATHS" | while read path; do+ [ -f "$path/package.json" ] || continue+ echo "=== $(basename "$path") ==="+ (cd "$path" && npm audit --json 2>/dev/null | jq '{critical: .metadata.vulnerabilities.critical, high: .metadata.vulnerabilities.high}') || echo '{}'+done+```++## Output++Write to `/tmp/yolo-[session]/cto-analysis.md`:++```markdown+# CTO Analysis — [date]++## Time-Bomb #1: [name]++Location: [file:line]+Trigger: [what will cause it to blow up]+Impact: [what breaks]+Fix effort: [hours/days]++## Service Risk Assessment++| Service | Risk | Reason | Time to P0 |+| ------- | ---- | ------ | ---------- |++...++## Architecture Scaling Limits++[specific bottleneck] breaks at [X load] because [reason]++## Cut Corners (by blast radius)++1. [issue] in [file] — blast radius: [description]+2. ...++## Security Issues Found++[list any real findings, or "none found in static scan"]++## Dependency Vulnerabilities++Critical: [N], High: [N]+Highest risk: [package] [vuln]++## Top 3 CTO Actions (ranked by risk reduction)++1. [action] — [risk mitigated]+2. [action] — [risk mitigated]+3. [action] — [risk mitigated]+```++Be specific. Reference actual file paths and line numbers where possible. No generic "improve code quality" advice.diff --git a/claude-ops/bin/ops-autofix b/claude-ops/bin/ops-autofixnew file mode 100755index 00000000..a0e539e5--- /dev/null+++ b/claude-ops/bin/ops-autofix@@ -0,0 +1,270 @@+#!/usr/bin/env bash+# ops-autofix — Automatically fix common ops plugin issues without user interaction+# Called by /ops:setup and /ops:doctor to silently repair what can be repaired.+# Usage: ops-autofix [--json] [--fix=all|wacli-fts|slack-mcp|vercel-mcp]+set -euo pipefail++JSON_OUTPUT=false+FIX_TARGET="all"++for arg in "$@"; do+ case "$arg" in+ --json) JSON_OUTPUT=true ;;+ --fix=*) FIX_TARGET="${arg#--fix=}" ;;+ esac+done++FIXES_APPLIED=()+FIXES_FAILED=()+FIXES_SKIPPED=()++log_fix() { FIXES_APPLIED+=("$1"); }+log_fail() { FIXES_FAILED+=("$1"); }+log_skip() { FIXES_SKIPPED+=("$1"); }++# ─── 1. WhatsApp FTS5 ───────────────────────────────────────────────────────+fix_wacli_fts() {+ if ! command -v wacli >/dev/null 2>&1; then+ log_skip "wacli-fts: wacli not installed"+ return+ fi++ # Check if FTS is already enabled+ FTS_STATUS=$(wacli doctor --json 2>/dev/null | jq -r '.data.fts_enabled // false' 2>/dev/null || echo "false")+ if [ "$FTS_STATUS" = "true" ]; then+ log_skip "wacli-fts: already enabled"+ return+ fi++ # Check if Go is available for rebuild+ if ! command -v go >/dev/null 2>&1; then+ log_fail "wacli-fts: Go toolchain not installed (needed to rebuild wacli with FTS5)"+ return+ fi++ # Check if wacli was built without sqlite_fts5 tag+ WACLI_PATH=$(which wacli)+ HAS_FTS5_TAG=$(strings "$WACLI_PATH" 2>/dev/null | grep -c "sqlite_fts5" || echo "0")++ # Find or clone wacli source+ WACLI_SRC=""+ for candidate in ~/src/wacli /tmp/wacli-rebuild; do+ if [ -f "$candidate/go.mod" ] && grep -q "wacli" "$candidate/go.mod" 2>/dev/null; then+ WACLI_SRC="$candidate"+ break+ fi+ done++ if [ -z "$WACLI_SRC" ]; then+ # Clone source+ WACLI_SRC="/tmp/wacli-rebuild"+ rm -rf "$WACLI_SRC"+ if ! git clone --depth 1 https://github.com/steipete/wacli.git "$WACLI_SRC" 2>/dev/null; then+ log_fail "wacli-fts: failed to clone wacli source"+ return+ fi+ fi++ # Rebuild with FTS5 tag+ if (cd "$WACLI_SRC" && CGO_ENABLED=1 go build -tags "sqlite_fts5" -o "$WACLI_PATH" ./cmd/wacli 2>/dev/null); then+ # Verify+ NEW_FTS=$(wacli doctor --json 2>/dev/null | jq -r '.data.fts_enabled // false' 2>/dev/null || echo "false")+ if [ "$NEW_FTS" = "true" ]; then+ log_fix "wacli-fts: rebuilt with FTS5 support"+ else+ log_fail "wacli-fts: rebuilt binary but FTS still reports disabled"+ fi+ else+ log_fail "wacli-fts: go build failed"+ fi+}++# ─── 2. Slack MCP ───────────────────────────────────────────────────────────+fix_slack_mcp() {+ # Check if already registered+ if [ -f "$HOME/.claude.json" ] && jq -e '.mcpServers.slack' "$HOME/.claude.json" >/dev/null 2>&1; then+ log_skip "slack-mcp: already registered"+ return+ fi++ # Check for tokens in keychain+ XOXC=$(security find-generic-password -s slack-xoxc -w 2>/dev/null || echo "")+ XOXD=$(security find-generic-password -s slack-xoxd -w 2>/dev/null || echo "")++ if [ -z "$XOXC" ] || [ -z "$XOXD" ]; then+ log_skip "slack-mcp: no tokens in keychain (run /ops:setup slack to extract)"+ return+ fi++ # Validate tokens+ AUTH_OK=$(curl -s -H "Authorization: Bearer $XOXC" -b "d=$XOXD" "https://slack.com/api/auth.test" 2>/dev/null | jq -r '.ok // false' 2>/dev/null || echo "false")+ if [ "$AUTH_OK" != "true" ]; then+ log_fail "slack-mcp: tokens in keychain are expired/invalid"+ return+ fi++ # Register MCP+ if command -v claude >/dev/null 2>&1; then+ if claude mcp add slack -e SLACK_XOXC_TOKEN="$XOXC" -e SLACK_XOXD_TOKEN="$XOXD" -s user -- npx -y @anthropic-ai/slack-mcp-server 2>/dev/null; then+ log_fix "slack-mcp: registered with valid tokens from keychain"+ else+ log_fail "slack-mcp: claude mcp add failed"+ fi+ else+ log_fail "slack-mcp: claude CLI not found"+ fi+}++# ─── 3. Vercel MCP ──────────────────────────────────────────────────────────+fix_vercel_mcp() {+ # Check if already registered+ if [ -f "$HOME/.claude.json" ] && jq -e '.mcpServers.vercel' "$HOME/.claude.json" >/dev/null 2>&1; then+ log_skip "vercel-mcp: already registered"+ return+ fi++ if command -v claude >/dev/null 2>&1; then+ if claude mcp add vercel -s user -- npx -y vercel-mcp-server@latest 2>/dev/null; then+ log_fix "vercel-mcp: registered"+ else+ log_fail "vercel-mcp: claude mcp add failed"+ fi+ else+ log_fail "vercel-mcp: claude CLI not found"+ fi+}++# ─── 4. Channel health — detect auth'd but broken channels ──────────────────+fix_channel_health() {+ # ── WhatsApp: @lid JID sync + stale connection ──+ if command -v wacli >/dev/null 2>&1; then+ DOCTOR=$(wacli doctor --json 2>/dev/null || echo '{"success":false}')+ WA_AUTH=$(echo "$DOCTOR" | jq -r '.data.authenticated // false' 2>/dev/null)+ WA_LOCK=$(echo "$DOCTOR" | jq -r '.data.lock_held // false' 2>/dev/null)++ if [ "$WA_AUTH" = "true" ]; then+ # Kill stale lock if held >2 min+ if [ "$WA_LOCK" = "true" ]; then+ LOCK_PID=$(echo "$DOCTOR" | jq -r '.data.lock_info' 2>/dev/null | grep -oE 'pid=[0-9]+' | cut -d= -f2)+ if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then+ log_fix "wacli-health: killed stale lock holder (pid=$LOCK_PID)"+ kill "$LOCK_PID" 2>/dev/null; sleep 2+ kill -0 "$LOCK_PID" 2>/dev/null && kill -9 "$LOCK_PID" 2>/dev/null+ fi+ fi++ # Check @lid JIDs with empty messages+ LID_EMPTY=0+ for jid in $(wacli chats list --json 2>/dev/null | jq -r '.data[] | select(.jid | contains("@lid")) | .jid' 2>/dev/null | head -5); do+ MSG_COUNT=$(wacli messages list --chat "$jid" --limit 3 --json 2>/dev/null | jq -r '.data.messages | length' 2>/dev/null || echo "0")+ [ "$MSG_COUNT" = "0" ] && LID_EMPTY=$((LID_EMPTY + 1))+ done++ if [ "$LID_EMPTY" -gt 0 ]; then+ if timeout 30 wacli sync 2>/dev/null; then+ log_fix "wacli-health: synced @lid chats ($LID_EMPTY had empty messages)"+ else+ log_fail "wacli-health: sync timed out"+ fi+ fi++ # Check for zero recent messages (auth'd but dead session)+ RECENT=$(wacli messages list --after="$(date -v-1d +%Y-%m-%d 2>/dev/null || date -d '1 day ago' +%Y-%m-%d)" --limit 1 --json 2>/dev/null | jq -r '.data.messages | length' 2>/dev/null || echo "0")+ if [ "$RECENT" = "0" ]; then+ # Try sync first+ timeout 30 wacli sync 2>/dev/null+ RECENT2=$(wacli messages list --after="$(date -v-1d +%Y-%m-%d 2>/dev/null || date -d '1 day ago' +%Y-%m-%d)" --limit 1 --json 2>/dev/null | jq -r '.data.messages | length' 2>/dev/null || echo "0")+ if [ "$RECENT2" = "0" ]; then+ log_fail "wacli-health: auth'd but 0 messages in 24h (likely app-state key desync — needs re-pair)"+ else+ log_fix "wacli-health: sync restored message flow"+ fi+ else+ log_skip "wacli-health: messages flowing normally"+ fi+ else+ log_skip "wacli-health: not authenticated"+ fi+ fi++ # ── Email (gog): auth'd but API broken ──+ if command -v gog >/dev/null 2>&1; then+ GOG_AUTH=$(gog auth status 2>&1)+ if echo "$GOG_AUTH" | grep -qi "authenticated\|logged in\|valid"; then+ GOG_TEST=$(gog gmail labels list --json 2>/dev/null | head -5)+ if [ -z "$GOG_TEST" ] || echo "$GOG_TEST" | grep -qi "error\|failed"; then+ log_fail "gog-health: authenticated but Gmail API failing (token may need refresh — run gog auth login)"+ else+ log_skip "gog-health: email working"+ fi+ else+ log_skip "gog-health: not authenticated"+ fi+ fi++ # ── Slack: tokens in keychain but expired ──+ XOXC=$(security find-generic-password -s slack-xoxc -w 2>/dev/null || echo "")+ if [ -n "$XOXC" ]; then+ XOXD=$(security find-generic-password -s slack-xoxd -w 2>/dev/null || echo "")+ SLACK_OK=$(curl -s -H "Authorization: Bearer $XOXC" -b "d=$XOXD" "https://slack.com/api/auth.test" 2>/dev/null | jq -r '.ok // false' 2>/dev/null || echo "false")+ if [ "$SLACK_OK" != "true" ]; then+ log_fail "slack-health: tokens in keychain are expired (re-run /ops:setup slack)"+ else+ log_skip "slack-health: tokens valid"+ fi+ fi++ # ── Telegram: session in keychain but expired ──+ TG_SESSION=$(security find-generic-password -s telegram-session -w 2>/dev/null || echo "")+ if [ -n "$TG_SESSION" ]; then+ TG_API_ID=$(security find-generic-password -s telegram-api-id -w 2>/dev/null || echo "")+ if [ -z "$TG_API_ID" ]; then+ log_fail "telegram-health: session exists but api_id missing from keychain"+ else+ log_skip "telegram-health: credentials present (runtime validation requires MCP)"+ fi+ fi+}++# ─── Run fixes ───────────────────────────────────────────────────────────────+case "$FIX_TARGET" in+ all)+ fix_wacli_fts+ fix_channel_health+ fix_slack_mcp+ fix_vercel_mcp+ ;;+ wacli-fts) fix_wacli_fts ;;+ channel-health) fix_channel_health ;;+ slack-mcp) fix_slack_mcp ;;+ vercel-mcp) fix_vercel_mcp ;;+ *)+ echo "Unknown fix target: $FIX_TARGET" >&2+ exit 1+ ;;+esac++# ─── Output ──────────────────────────────────────────────────────────────────+if [ "$JSON_OUTPUT" = true ]; then+ applied_json="[]"+ failed_json="[]"+ skipped_json="[]"+ if command -v jq >/dev/null 2>&1; then+ [ ${#FIXES_APPLIED[@]} -gt 0 ] && applied_json=$(printf '%s\n' "${FIXES_APPLIED[@]}" | jq -R . | jq -s .)+ [ ${#FIXES_FAILED[@]} -gt 0 ] && failed_json=$(printf '%s\n' "${FIXES_FAILED[@]}" | jq -R . | jq -s .)+ [ ${#FIXES_SKIPPED[@]} -gt 0 ] && skipped_json=$(printf '%s\n' "${FIXES_SKIPPED[@]}" | jq -R . | jq -s .)+ fi+ cat <<EOF+{+ "applied": $applied_json,+ "failed": $failed_json,+ "skipped": $skipped_json+}+EOF+else+ for fix in "${FIXES_APPLIED[@]}"; do echo "✓ $fix"; done+ for fix in "${FIXES_FAILED[@]}"; do echo "✗ $fix"; done+ for fix in "${FIXES_SKIPPED[@]}"; do echo "○ $fix"; done+ echo ""+ echo "Applied: ${#FIXES_APPLIED[@]}, Failed: ${#FIXES_FAILED[@]}, Skipped: ${#FIXES_SKIPPED[@]}"+fidiff --git a/claude-ops/bin/ops-ci b/claude-ops/bin/ops-cinew file mode 100755index 00000000..2a9a6e3d--- /dev/null+++ b/claude-ops/bin/ops-ci@@ -0,0 +1,44 @@+#!/usr/bin/env bash+# ops-ci — Recent CI failures across all repos → JSON+# Checks last 24h of GitHub Actions failures++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REGISTRY="${SCRIPT_DIR}/../scripts/registry.json"++if [ ! -f "$REGISTRY" ]; then+ echo '{"error":"registry.json not found"}' && exit 1+fi++if ! command -v gh &>/dev/null; then+ echo '{"error":"gh CLI not found","failures":[]}' && exit 0+fi++REPOS=$(jq -r '[.projects[].repos[]] | unique | .[]' "$REGISTRY")+SINCE=$(date -v-1d +%Y-%m-%d 2>/dev/null || date -d '1 day ago' +%Y-%m-%d 2>/dev/null || date +%Y-%m-%d)++TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++for repo in $REPOS; do+ (+ SAFE_NAME=$(echo "$repo" | tr '/' '_')+ FAILURES=$(gh run list --repo "$repo" --status failure --limit 3 \+ --json name,headBranch,createdAt,conclusion,event 2>/dev/null || echo '[]')++ if [ "$FAILURES" != "[]" ] && [ -n "$FAILURES" ]; then+ echo "{\"repo\":\"$repo\",\"failures\":$FAILURES}" > "$TMPDIR_OPS/$SAFE_NAME.json"+ fi+ ) &+done+wait++echo -n '{"repos_with_failures":['+first=true+for f in "$TMPDIR_OPS"/*.json; do+ [ ! -f "$f" ] && continue+ [ "$first" = true ] && first=false || echo -n ','+ cat "$f"+done+echo ']}'diff --git a/claude-ops/bin/ops-dash b/claude-ops/bin/ops-dashnew file mode 100755index 00000000..9e8403ae--- /dev/null+++ b/claude-ops/bin/ops-dash@@ -0,0 +1,163 @@+#!/usr/bin/env bash+# ops-dash — Instant pixel-art command center dashboard+# Renders the visual dashboard shell with live data indicators+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REGISTRY="${PLUGIN_ROOT}/scripts/registry.json"+PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"++# --- Color setup ---+if [[ -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then+ RST=$'\033[0m'; BOLD=$'\033[1m'; DIM=$'\033[2m'+ CYN=$'\033[36m'; GRN=$'\033[32m'; RED=$'\033[31m'; YLW=$'\033[33m'; WHT=$'\033[37m'; MAG=$'\033[35m'; BLU=$'\033[34m'+ BCYN=$'\033[1;36m'; BGRN=$'\033[1;32m'; BRED=$'\033[1;31m'; BYLW=$'\033[1;33m'; BWHT=$'\033[1;37m'; BMAG=$'\033[1;35m'; BBLU=$'\033[1;34m'+ BGDIM=$'\033[48;5;236m'; BGDARK=$'\033[48;5;233m'+else+ RST="" BOLD="" DIM="" CYN="" GRN="" RED="" YLW="" WHT="" MAG="" BLU=""+ BCYN="" BGRN="" BRED="" BYLW="" BWHT="" BMAG="" BBLU="" BGDIM="" BGDARK=""+fi++# --- Helpers ---+p() { printf '%s\n' "$1"; }+sp() { printf '%s\n' "$1"; sleep 0.015; }++# --- Check setup ---+SETUP_OK="true"+[ -f "$PREFS" ] || SETUP_OK="false"++# --- Quick data probes (parallel, non-blocking) ---+TMPDIR_DASH=$(mktemp -d)+trap 'rm -rf "$TMPDIR_DASH"' EXIT++# Fire probes in background+(+ if [ -f "$REGISTRY" ]; then+ PROJECT_COUNT=$(jq '.projects | length' "$REGISTRY" 2>/dev/null || echo "0")+ FIRE_PROJECTS=$(jq -r '.projects[].infra.ecs_clusters // [] | .[]' "$REGISTRY" 2>/dev/null | wc -l | tr -d ' ')+ else+ PROJECT_COUNT="0"+ FIRE_PROJECTS="0"+ fi+ echo "$PROJECT_COUNT" > "$TMPDIR_DASH/projects"+ echo "$FIRE_PROJECTS" > "$TMPDIR_DASH/clusters"+) &++(+ # PR count+ PR_COUNT=$(gh pr list --state open --json number 2>/dev/null | jq 'length' 2>/dev/null || echo "?")+ echo "$PR_COUNT" > "$TMPDIR_DASH/prs"+) &++(+ # CI failures (last 24h across repos)+ FAIL_COUNT=$(gh run list --limit 30 --json conclusion 2>/dev/null | jq '[.[] | select(.conclusion == "failure")] | length' 2>/dev/null || echo "?")+ echo "$FAIL_COUNT" > "$TMPDIR_DASH/ci_fails"+) &++(+ # Unread counts+ "$PLUGIN_ROOT/bin/ops-unread" 2>/dev/null > "$TMPDIR_DASH/unread.json" || echo '{}' > "$TMPDIR_DASH/unread.json"+) &++(+ # GSD active phases+ GSD_ACTIVE=0+ if [ -f "$REGISTRY" ]; then+ for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "$REGISTRY" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ [ -f "$expanded/.planning/STATE.md" ] && GSD_ACTIVE=$((GSD_ACTIVE + 1))+ done+ fi+ echo "$GSD_ACTIVE" > "$TMPDIR_DASH/gsd"+) &++(+ # YOLO reports+ LATEST_YOLO=""+ for dir in /tmp/yolo-*/; do+ [ -f "${dir}ceo-analysis.md" ] && LATEST_YOLO="$dir"+ done+ echo "${LATEST_YOLO:-none}" > "$TMPDIR_DASH/yolo"+) &++wait++# --- Read results ---+PROJECTS=$(cat "$TMPDIR_DASH/projects" 2>/dev/null || echo "?")+CLUSTERS=$(cat "$TMPDIR_DASH/clusters" 2>/dev/null || echo "?")+PRS=$(cat "$TMPDIR_DASH/prs" 2>/dev/null || echo "?")+CI_FAILS=$(cat "$TMPDIR_DASH/ci_fails" 2>/dev/null || echo "?")+GSD_ACTIVE=$(cat "$TMPDIR_DASH/gsd" 2>/dev/null || echo "?")+LATEST_YOLO=$(cat "$TMPDIR_DASH/yolo" 2>/dev/null || echo "none")++# Unread parsing+UNREAD_JSON=$(cat "$TMPDIR_DASH/unread.json" 2>/dev/null || echo '{}')+WA_UNREAD=$(echo "$UNREAD_JSON" | jq -r '.whatsapp.count // 0' 2>/dev/null || echo "0")+EMAIL_UNREAD=$(echo "$UNREAD_JSON" | jq -r '.email.count // 0' 2>/dev/null || echo "0")+SLACK_UNREAD=$(echo "$UNREAD_JSON" | jq -r '.slack.count // 0' 2>/dev/null || echo "0")+TOTAL_UNREAD=$((${WA_UNREAD:-0} + ${EMAIL_UNREAD:-0} + ${SLACK_UNREAD:-0}))++# --- Fire indicator ---+if [ "${CI_FAILS:-0}" != "?" ] && [ "${CI_FAILS:-0}" -gt 0 ] 2>/dev/null; then+ FIRE_STATUS="${BRED}FIRES DETECTED${RST}"+ FIRE_ICON="${RED}~${RST}"+else+ FIRE_STATUS="${BGRN}ALL CLEAR${RST}"+ FIRE_ICON="${GRN}~${RST}"+fi++# --- YOLO indicator ---+if [ "$LATEST_YOLO" != "none" ]; then+ YOLO_STATUS="${BCYN}REPORT READY${RST}"+else+ YOLO_STATUS="${DIM}no reports${RST}"+fi++# --- Date ---+NOW=$(date "+%Y-%m-%d %H:%M")+DAY=$(date "+%A")++# --- Render dashboard ---+p ""+sp "${DIM}${CYN} ╔══════════════════════════════════════════════════════════════╗${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ██████╗ ██████╗ ███████╗ ██████╗ █████╗ ███████╗${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ██╔═══██╗██╔══██╗██╔════╝ ██╔══██╗██╔══██╗██╔════╝${RST}${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ██║ ██║██████╔╝███████╗ ██║ ██║███████║███████╗${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ██║ ██║██╔═══╝ ╚════██║ ██║ ██║██╔══██║╚════██║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ╚██████╔╝██║ ███████║ ██████╔╝██║ ██║███████║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN} ╚═════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝${RST}${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BWHT}COMMAND CENTER${RST} ${DIM}v0.3.1${RST} ${DIM}${NOW} ${DAY}${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ╠══════════════════════════════════════════════════════════════╣${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${FIRE_ICON} ${BWHT}STATUS${RST} ${FIRE_STATUS} ${DIM}|${RST} ${BWHT}${TOTAL_UNREAD}${RST} unread ${DIM}|${RST} ${BWHT}${PRS}${RST} PRs ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM} ${PROJECTS} projects${RST} ${DIM}|${RST} ${DIM}${GSD_ACTIVE} GSD active${RST} ${DIM}|${RST} ${DIM}${CLUSTERS} clusters${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ╠══════════════════════════════════════════════════════════════╣${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BWHT}QUICK ACTIONS${RST} ${BWHT}INTEL${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN}1${RST} ${WHT}Morning briefing${RST} ${BCYN}6${RST} ${WHT}Revenue & costs${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN}2${RST} ${WHT}Inbox zero${RST} ${BCYN}7${RST} ${WHT}Linear sprint${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN}3${RST} ${WHT}Fire check${RST} ${BCYN}8${RST} ${WHT}Deploy status${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN}4${RST} ${WHT}Project dashboard${RST} ${BCYN}9${RST} ${WHT}Triage issues${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BCYN}5${RST} ${WHT}What's next?${RST} ${BCYN}0${RST} ${WHT}System speedup${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BWHT}POWER${RST} ${BWHT}COMMS${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BMAG}a${RST} ${WHT}YOLO mode${RST} ${YOLO_STATUS} ${BCYN}d${RST} ${WHT}Send message${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BMAG}b${RST} ${WHT}Auto-merge PRs${RST} ${BCYN}e${RST} ${WHT}C-suite reports${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BMAG}c${RST} ${WHT}Setup wizard${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ╠══════════════════════════════════════════════════════════════╣${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BWHT}META${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BYLW}f${RST} ${WHT}Settings & config${RST} ${BYLW}h${RST} ${WHT}Help / FAQ / Wiki${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${BYLW}g${RST} ${WHT}Share your setup${RST} ${DIM}q Exit${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+sp "${DIM}${CYN} ╚══════════════════════════════════════════════════════════════╝${RST}"+p ""diff --git a/claude-ops/bin/ops-doctor b/claude-ops/bin/ops-doctornew file mode 100755index 00000000..5afb2916--- /dev/null+++ b/claude-ops/bin/ops-doctor@@ -0,0 +1,359 @@+#!/usr/bin/env bash+# ops-doctor — Diagnose ops plugin health and emit JSON report+# Checks: plugin manifest, bin permissions, skill files, MCP config,+# registry, preferences, env vars, CLI tools, and agent definitions.+set -euo pipefail++has() { command -v "$1" >/dev/null 2>&1 && echo true || echo false; }+has_env() { [ -n "${!1:-}" ] && echo true || echo false; }++SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+PLUGIN_JSON="$SCRIPT_DIR/.claude-plugin/plugin.json"+REGISTRY="$SCRIPT_DIR/scripts/registry.json"+MCP_JSON_FILE="$SCRIPT_DIR/.mcp.json"+PREFS_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+PREFS="$PREFS_DIR/preferences.json"+if [ ! -f "$PREFS" ] && [ -f "$SCRIPT_DIR/scripts/preferences.json" ]; then+ PREFS="$SCRIPT_DIR/scripts/preferences.json"+fi++ERRORS=()+WARNINGS=()+INFO=()++# --- 1. Plugin manifest ---+if [ ! -f "$PLUGIN_JSON" ]; then+ ERRORS+=("plugin_manifest_missing: .claude-plugin/plugin.json not found")+else+ if command -v jq >/dev/null 2>&1; then+ if ! jq empty "$PLUGIN_JSON" 2>/dev/null; then+ ERRORS+=("plugin_manifest_invalid_json: plugin.json is not valid JSON")+ else+ # Check repository field type+ REPO_TYPE=$(jq -r 'type_of(.repository) // "null"' "$PLUGIN_JSON" 2>/dev/null || echo "unknown")+ if [ "$REPO_TYPE" = "unknown" ]; then+ REPO_TYPE=$(jq -r '.repository | type' "$PLUGIN_JSON" 2>/dev/null || echo "unknown")+ fi+ if [ "$REPO_TYPE" = "object" ]; then+ ERRORS+=("plugin_manifest_repository_type: repository field is an object, must be a string")+ fi+ # Check required fields+ for field in name version description; do+ VAL=$(jq -r ".$field // empty" "$PLUGIN_JSON" 2>/dev/null)+ if [ -z "$VAL" ]; then+ ERRORS+=("plugin_manifest_missing_field_$field: required field '$field' is missing or empty")+ fi+ done+ VERSION=$(jq -r '.version // "unknown"' "$PLUGIN_JSON" 2>/dev/null)+ fi+ else+ WARNINGS+=("jq_missing: cannot validate plugin.json without jq")+ fi+fi++# --- 2. Bin script permissions ---+BIN_ISSUES=()+for script in "$SCRIPT_DIR"/bin/ops-*; do+ [ -f "$script" ] || continue+ if [ ! -x "$script" ]; then+ BIN_ISSUES+=("$(basename "$script")")+ fi+done+if [ ${#BIN_ISSUES[@]} -gt 0 ]; then+ WARNINGS+=("bin_not_executable: $(IFS=,; echo "${BIN_ISSUES[*]}")")+fi++# --- 3. Skill directories ---+SKILL_ISSUES=()+for skill_dir in "$SCRIPT_DIR"/skills/*/; do+ [ -d "$skill_dir" ] || continue+ if [ ! -f "${skill_dir}SKILL.md" ]; then+ SKILL_ISSUES+=("$(basename "$skill_dir")")+ fi+done+if [ ${#SKILL_ISSUES[@]} -gt 0 ]; then+ ERRORS+=("skill_missing_definition: skills without SKILL.md: $(IFS=,; echo "${SKILL_ISSUES[*]}")")+fi++# --- 4. Agent definitions ---+AGENT_ISSUES=()+for agent_file in "$SCRIPT_DIR"/agents/*.md; do+ [ -f "$agent_file" ] || continue+ if ! head -1 "$agent_file" | grep -q "^---"; then+ AGENT_ISSUES+=("$(basename "$agent_file")")+ fi+done+if [ ${#AGENT_ISSUES[@]} -gt 0 ]; then+ WARNINGS+=("agent_missing_frontmatter: $(IFS=,; echo "${AGENT_ISSUES[*]}")")+fi++# --- 5. MCP config ---+if [ ! -f "$MCP_JSON_FILE" ]; then+ WARNINGS+=("mcp_config_missing: .mcp.json not found")+elif command -v jq >/dev/null 2>&1; then+ if ! jq empty "$MCP_JSON_FILE" 2>/dev/null; then+ ERRORS+=("mcp_config_invalid_json: .mcp.json is not valid JSON")+ else+ # Check each MCP server for user_config references and validate they're configured+ MCP_SERVERS=$(jq -r '.mcpServers // {} | keys[]' "$MCP_JSON_FILE" 2>/dev/null || true)+ for server in $MCP_SERVERS; do+ # Extract all ${user_config.*} references from this server's config+ USER_CONFIG_REFS=$(jq -r "+ .mcpServers[\"$server\"] | .. | strings | select(test(\"\\\\$\\{user_config\\.\")) |+ [scan(\"\\\\$\\{user_config\\.([^}]+)\\}\")] | .[][]+ " "$MCP_JSON_FILE" 2>/dev/null | sort -u || true)++ if [ -n "$USER_CONFIG_REFS" ]; then+ MISSING_CONFIGS=()+ for config_key in $USER_CONFIG_REFS; do+ # Check if this userConfig key has a non-empty value set+ # Look in preferences.json for saved values+ HAS_VALUE=false+ if [ -f "$PREFS" ]; then+ SAVED_VAL=$(jq -r ".user_config.\"$config_key\" // empty" "$PREFS" 2>/dev/null || true)+ if [ -n "$SAVED_VAL" ]; then+ HAS_VALUE=true+ fi+ fi+ # Also check if plugin.json userConfig declares it with a non-empty default+ if [ "$HAS_VALUE" = false ] && [ -f "$PLUGIN_JSON" ]; then+ DEFAULT_VAL=$(jq -r ".userConfig.\"$config_key\".default // empty" "$PLUGIN_JSON" 2>/dev/null || true)+ if [ -n "$DEFAULT_VAL" ]; then+ HAS_VALUE=true+ fi+ fi+ if [ "$HAS_VALUE" = false ]; then+ MISSING_CONFIGS+=("$config_key")+ fi+ done+ if [ ${#MISSING_CONFIGS[@]} -gt 0 ]; then+ ERRORS+=("mcp_missing_user_config_${server}: MCP server '$server' references unconfigured user_config values: $(IFS=,; echo "${MISSING_CONFIGS[*]}"). Run /ops:setup to configure.")+ fi+ fi+ done+ fi+fi++# --- 5b. Claude Code native diagnostics ---+# Check for issues that Claude Code's /doctor would flag+# Scan all MCP configs Claude Code reads for env var issues+CLAUDE_MCP_CONFIGS=("$HOME/.claude/.mcp.json" "$HOME/.claude.json")+for mcp_cfg in "${CLAUDE_MCP_CONFIGS[@]}"; do+ [ -f "$mcp_cfg" ] || continue+ if command -v jq >/dev/null 2>&1 && jq empty "$mcp_cfg" 2>/dev/null; then+ # Check for servers with empty/placeholder env values+ BROKEN_SERVERS=$(jq -r '+ .mcpServers // {} | to_entries[] |+ select(.value.env != null) |+ select(.value.env | to_entries[] | .value | test("^\\$\\{") ) |+ .key+ ' "$mcp_cfg" 2>/dev/null | sort -u || true)+ for srv in $BROKEN_SERVERS; do+ WARNINGS+=("claude_mcp_unresolved_vars_${srv}: MCP server '$srv' in $(basename "$mcp_cfg") has unresolved variable references")+ done+ fi+done++# Check plugin data dir for user_config values that are required but missing+if [ -f "$PLUGIN_JSON" ] && command -v jq >/dev/null 2>&1; then+ # Map from user_config keys to preferences.json channels paths+ # e.g. telegram_api_id -> channels.telegram.api_id+ _prefs_channel_lookup() {+ local key="$1"+ local channel="" field=""+ case "$key" in+ telegram_api_id) channel="telegram"; field="api_id" ;;+ telegram_api_hash) channel="telegram"; field="api_hash" ;;+ telegram_phone) channel="telegram"; field="phone" ;;+ telegram_session) channel="telegram"; field="session" ;;+ *) echo ""; return ;;+ esac+ if [ -f "$PREFS" ]; then+ jq -r ".channels.${channel}.${field} // empty" "$PREFS" 2>/dev/null || true+ fi+ }++ # Get all userConfig keys that have sensitive=true (likely required credentials)+ SENSITIVE_KEYS=$(jq -r '.userConfig // {} | to_entries[] | select(.value.sensitive == true) | .key' "$PLUGIN_JSON" 2>/dev/null || true)+ UNCONFIGURED_SENSITIVE=()+ for skey in $SENSITIVE_KEYS; do+ IS_SET=false+ if [ -f "$PREFS" ]; then+ SVAL=$(jq -r ".user_config.\"$skey\" // empty" "$PREFS" 2>/dev/null || true)+ [ -n "$SVAL" ] && IS_SET=true+ fi+ # Fallback: check preferences.json channels.* section for matching values+ if [ "$IS_SET" = false ]; then+ CHAN_VAL=$(_prefs_channel_lookup "$skey")+ if [ -n "$CHAN_VAL" ]; then+ IS_SET=true+ fi+ fi+ if [ "$IS_SET" = false ]; then+ UNCONFIGURED_SENSITIVE+=("$skey")+ fi+ done+ if [ ${#UNCONFIGURED_SENSITIVE[@]} -gt 0 ]; then+ # Check if a separate working MCP server already provides the same functionality+ # by scanning global MCP configs for a matching server name+ _has_global_mcp_server() {+ local server_name="$1"+ for global_cfg in "$HOME/.claude/.mcp.json" "$HOME/.claude.json"; do+ [ -f "$global_cfg" ] || continue+ if jq -e ".mcpServers.\"$server_name\"" "$global_cfg" >/dev/null 2>&1; then+ echo true; return+ fi+ done+ # Also check if plugin cache copies provide a working server+ for cache_mcp in "$HOME/.claude/plugins/cache"/*/ops/*/.mcp.json; do+ [ -f "$cache_mcp" ] || continue+ if jq -e ".mcpServers.\"$server_name\"" "$cache_mcp" >/dev/null 2>&1; then+ echo true; return+ fi+ done+ echo false+ }++ # Determine which MCP servers the unconfigured keys belong to+ ALL_COVERED_BY_GLOBAL=true+ for ukey in "${UNCONFIGURED_SENSITIVE[@]}"; do+ # Extract server name from the key prefix (e.g. telegram_api_id -> telegram)+ SERVER_PREFIX="${ukey%%_*}"+ if [ "$(_has_global_mcp_server "$SERVER_PREFIX")" = false ]; then+ ALL_COVERED_BY_GLOBAL=false+ break+ fi+ done++ if [ "$ALL_COVERED_BY_GLOBAL" = true ]; then+ INFO+=("unconfigured_sensitive_keys: Sensitive user config values not set in plugin: $(IFS=,; echo "${UNCONFIGURED_SENSITIVE[*]}"), but a separate working MCP server provides equivalent functionality.")+ else+ WARNINGS+=("unconfigured_sensitive_keys: Sensitive user config values not set: $(IFS=,; echo "${UNCONFIGURED_SENSITIVE[*]}"). MCP servers depending on these will fail. Run /ops:setup to configure.")+ fi+ fi+fi++# --- 6. Registry ---+REGISTRY_STATUS="missing"+REGISTRY_COUNT=0+if [ -f "$REGISTRY" ]; then+ REGISTRY_STATUS="present"+ if command -v jq >/dev/null 2>&1; then+ if ! jq empty "$REGISTRY" 2>/dev/null; then+ ERRORS+=("registry_invalid_json: registry.json is not valid JSON")+ REGISTRY_STATUS="invalid"+ else+ REGISTRY_COUNT=$(jq '.projects | length' "$REGISTRY" 2>/dev/null || echo 0)+ fi+ fi+else+ WARNINGS+=("registry_missing: scripts/registry.json not found — run /ops:setup to create")+fi++# --- 7. Preferences ---+PREFS_STATUS="missing"+if [ -f "$PREFS" ]; then+ PREFS_STATUS="present"+ if command -v jq >/dev/null 2>&1 && ! jq empty "$PREFS" 2>/dev/null; then+ ERRORS+=("preferences_invalid_json: preferences.json is not valid JSON")+ PREFS_STATUS="invalid"+ fi+fi++# --- 8. CLI tools ---+TOOLS_JSON=$(cat <<TOOLS+{+ "jq": $(has jq),+ "git": $(has git),+ "gh": $(has gh),+ "aws": $(has aws),+ "node": $(has node),+ "wacli": $(has wacli),+ "gog": $(has gog),+ "sentry-cli": $(has sentry-cli),+ "doppler": $(has doppler)+}+TOOLS+)++# --- 9. Env vars ---+ENV_JSON=$(cat <<ENV+{+ "CLAUDE_PLUGIN_ROOT": $(has_env CLAUDE_PLUGIN_ROOT),+ "CLAUDE_PLUGIN_DATA_DIR": $(has_env CLAUDE_PLUGIN_DATA_DIR),+ "TELEGRAM_BOT_TOKEN": $(has_env TELEGRAM_BOT_TOKEN),+ "TELEGRAM_OWNER_ID": $(has_env TELEGRAM_OWNER_ID),+ "AWS_PROFILE": $(has_env AWS_PROFILE),+ "GH_TOKEN": $(has_env GH_TOKEN)+}+ENV+)++# --- 10. Cache copies vs source ---+CACHE_DIR="$HOME/.claude/plugins/cache/ops-marketplace/ops"+CACHE_VERSIONS=()+if [ -d "$CACHE_DIR" ]; then+ for ver_dir in "$CACHE_DIR"/*/; do+ [ -d "$ver_dir" ] || continue+ CACHE_VERSIONS+=("$(basename "$ver_dir")")+ done+fi++# Build errors/warnings/info JSON arrays+err_json="[]"+warn_json="[]"+info_json="[]"+cache_json="[]"+if command -v jq >/dev/null 2>&1; then+ if [ ${#ERRORS[@]} -gt 0 ]; then+ err_json=$(printf '%s\n' "${ERRORS[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")+ fi+ if [ ${#WARNINGS[@]} -gt 0 ]; then+ warn_json=$(printf '%s\n' "${WARNINGS[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")+ fi+ if [ ${#INFO[@]} -gt 0 ]; then+ info_json=$(printf '%s\n' "${INFO[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")+ fi+ if [ ${#CACHE_VERSIONS[@]} -gt 0 ]; then+ cache_json=$(printf '%s\n' "${CACHE_VERSIONS[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")+ fi+fi++cat <<EOF+{+ "plugin_root": "$SCRIPT_DIR",+ "version": "${VERSION:-unknown}",+ "errors": $err_json,+ "warnings": $warn_json,+ "info": $info_json,+ "tools": $TOOLS_JSON,+ "env_vars": $ENV_JSON,+ "registry": {+ "status": "$REGISTRY_STATUS",+ "project_count": $REGISTRY_COUNT,+ "path": "$REGISTRY"+ },+ "preferences": {+ "status": "$PREFS_STATUS",+ "path": "$PREFS"+ },+ "cache_versions": $cache_json,+ "skill_count": $(find "$SCRIPT_DIR/skills" -name "SKILL.md" 2>/dev/null | wc -l | tr -d ' '),+ "agent_count": $(find "$SCRIPT_DIR/agents" -name "*.md" 2>/dev/null | wc -l | tr -d ' '),+ "bin_count": $(find "$SCRIPT_DIR/bin" -name "ops-*" 2>/dev/null | wc -l | tr -d ' ')+}+EOF++# --- 11. Auto-fix pass (silent, best-effort) ---+# Run autofix for known issues. This is non-interactive and safe to run every time.+if [ -x "$SCRIPT_DIR/bin/ops-autofix" ]; then+ AUTOFIX_RESULT=$("$SCRIPT_DIR/bin/ops-autofix" --json 2>/dev/null || echo '{"applied":[],"failed":[],"skipped":[]}')+ AUTOFIX_APPLIED=$(echo "$AUTOFIX_RESULT" | jq -r '.applied | length' 2>/dev/null || echo "0")+ if [ "$AUTOFIX_APPLIED" -gt 0 ]; then+ echo ""+ echo "── Auto-fixes applied ──"+ echo "$AUTOFIX_RESULT" | jq -r '.applied[]' 2>/dev/null | while read -r fix; do+ echo " ✓ $fix"+ done+ fi+fidiff --git a/claude-ops/bin/ops-ecom-health b/claude-ops/bin/ops-ecom-healthnew file mode 100755index 00000000..ef4a0927--- /dev/null+++ b/claude-ops/bin/ops-ecom-health@@ -0,0 +1,95 @@+#!/usr/bin/env bash+# ops-ecom-health — Shopify store health check, outputs JSON++set -euo pipefail++# Resolve credentials+SHOPIFY_STORE="${SHOPIFY_STORE_URL:-}"+SHOPIFY_TOKEN="${SHOPIFY_ACCESS_TOKEN:-}"++# Doppler fallback+if [ -z "$SHOPIFY_TOKEN" ] && command -v doppler &>/dev/null; then+ SHOPIFY_TOKEN=$(doppler secrets get SHOPIFY_ACCESS_TOKEN --plain 2>/dev/null || echo "")+fi+if [ -z "$SHOPIFY_STORE" ] && command -v doppler &>/dev/null; then+ SHOPIFY_STORE=$(doppler secrets get SHOPIFY_STORE_URL --plain 2>/dev/null || echo "")+fi++if [ -z "$SHOPIFY_STORE" ] || [ -z "$SHOPIFY_TOKEN" ]; then+ echo '{"error":"missing_credentials","message":"Set SHOPIFY_STORE_URL and SHOPIFY_ACCESS_TOKEN"}'+ exit 1+fi++BASE="https://${SHOPIFY_STORE}/admin/api/2024-10"+AUTH="X-Shopify-Access-Token: ${SHOPIFY_TOKEN}"++# Check API connectivity+SHOP_RESPONSE=$(curl -s -w "\n%{http_code}" -H "$AUTH" "${BASE}/shop.json" 2>/dev/null || echo -e "\n000")+SHOP_BODY=$(echo "$SHOP_RESPONSE" | head -1)+HTTP_CODE=$(echo "$SHOP_RESPONSE" | tail -1)++if [ "$HTTP_CODE" != "200" ]; then+ echo "{\"error\":\"api_unreachable\",\"http_code\":${HTTP_CODE},\"message\":\"Shopify Admin API returned HTTP ${HTTP_CODE}\"}"+ exit 1+fi++SHOP_NAME=$(echo "$SHOP_BODY" | jq -r '.shop.name // "unknown"' 2>/dev/null || echo "unknown")+SHOP_PLAN=$(echo "$SHOP_BODY" | jq -r '.shop.plan_display_name // "unknown"' 2>/dev/null || echo "unknown")+SHOP_CURRENCY=$(echo "$SHOP_BODY" | jq -r '.shop.currency // "unknown"' 2>/dev/null || echo "unknown")+SHOP_DOMAIN=$(echo "$SHOP_BODY" | jq -r '.shop.domain // "unknown"' 2>/dev/null || echo "unknown")++# Active theme+THEME_RESPONSE=$(curl -s -H "$AUTH" "${BASE}/themes.json" 2>/dev/null || echo '{}')+ACTIVE_THEME=$(echo "$THEME_RESPONSE" | jq -r '[.themes[] | select(.role == "main")] | .[0] | {id: .id, name: .name, updated: .updated_at}' 2>/dev/null || echo 'null')++# Product count+PRODUCT_COUNT=$(curl -s -H "$AUTH" "${BASE}/products/count.json" 2>/dev/null | jq '.count // 0' 2>/dev/null || echo 0)++# Order count (last 24h)+SINCE=$(date -u -v-1d +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u -d "1 day ago" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u +"%Y-%m-%dT00:00:00Z")+ORDER_COUNT=$(curl -s -H "$AUTH" "${BASE}/orders/count.json?status=any&created_at_min=${SINCE}" 2>/dev/null | jq '.count // 0' 2>/dev/null || echo 0)++# Unfulfilled orders+UNFULFILLED_COUNT=$(curl -s -H "$AUTH" "${BASE}/orders/count.json?fulfillment_status=unfulfilled&status=open" 2>/dev/null | jq '.count // 0' 2>/dev/null || echo 0)++# Low stock products (inventory < 10)+INVENTORY_RESPONSE=$(curl -s -H "$AUTH" "${BASE}/products.json?limit=250&fields=id,title,variants" 2>/dev/null || echo '{"products":[]}')+LOW_STOCK=$(echo "$INVENTORY_RESPONSE" | jq '[.products[] | .variants[] | select(.inventory_quantity != null and .inventory_quantity < 10 and .inventory_quantity > 0) | {product_id: .product_id, sku: .sku, qty: .inventory_quantity}] | length' 2>/dev/null || echo 0)+OUT_OF_STOCK=$(echo "$INVENTORY_RESPONSE" | jq '[.products[] | .variants[] | select(.inventory_quantity != null and .inventory_quantity <= 0) | {product_id: .product_id, sku: .sku}] | length' 2>/dev/null || echo 0)++# Build output JSON+jq -n \+ --arg store "$SHOPIFY_STORE" \+ --arg name "$SHOP_NAME" \+ --arg plan "$SHOP_PLAN" \+ --arg currency "$SHOP_CURRENCY" \+ --arg domain "$SHOP_DOMAIN" \+ --argjson theme "$ACTIVE_THEME" \+ --argjson products "$PRODUCT_COUNT" \+ --argjson orders_24h "$ORDER_COUNT" \+ --argjson unfulfilled "$UNFULFILLED_COUNT" \+ --argjson low_stock "$LOW_STOCK" \+ --argjson out_of_stock "$OUT_OF_STOCK" \+ --arg checked_at "$(date -u +"%Y-%m-%dT%H:%M:%SZ")" \+ '{+ ok: true,+ store: $store,+ shop: {+ name: $name,+ plan: $plan,+ currency: $currency,+ domain: $domain+ },+ api_connectivity: "ok",+ active_theme: $theme,+ product_count: $products,+ orders_24h: $orders_24h,+ fulfillment: {+ unfulfilled: $unfulfilled+ },+ inventory: {+ low_stock: $low_stock,+ out_of_stock: $out_of_stock+ },+ checked_at: $checked_at+ }'diff --git a/claude-ops/bin/ops-gather b/claude-ops/bin/ops-gathernew file mode 100755index 00000000..517c8931--- /dev/null+++ b/claude-ops/bin/ops-gather@@ -0,0 +1,42 @@+#!/usr/bin/env bash+# ops-gather — Master parallel data gatherer+# Runs all ops-* scripts in parallel, assembles into single JSON+# This is the primary token-saving mechanism for /ops-go++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++START_TIME=$(date +%s)++# Run all gatherers in parallel+"$SCRIPT_DIR/ops-git" > "$TMPDIR_OPS/git.json" 2>/dev/null &+"$SCRIPT_DIR/ops-infra" > "$TMPDIR_OPS/infra.json" 2>/dev/null &+"$SCRIPT_DIR/ops-prs" > "$TMPDIR_OPS/prs.json" 2>/dev/null &+"$SCRIPT_DIR/ops-ci" > "$TMPDIR_OPS/ci.json" 2>/dev/null &+"$SCRIPT_DIR/ops-unread" > "$TMPDIR_OPS/unread.json" 2>/dev/null &+wait++END_TIME=$(date +%s)+DURATION=$((END_TIME - START_TIME))++# Assemble into single JSON+jq -n \+ --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \+ --arg dur "${DURATION}s" \+ --slurpfile git "$TMPDIR_OPS/git.json" \+ --slurpfile infra "$TMPDIR_OPS/infra.json" \+ --slurpfile prs "$TMPDIR_OPS/prs.json" \+ --slurpfile ci "$TMPDIR_OPS/ci.json" \+ --slurpfile unread "$TMPDIR_OPS/unread.json" \+ '{+ "timestamp": $ts,+ "gather_duration": $dur,+ "git": $git[0],+ "infrastructure": $infra[0],+ "pull_requests": $prs[0],+ "ci_failures": $ci[0],+ "unread_messages": $unread[0]+ }'diff --git a/claude-ops/bin/ops-git b/claude-ops/bin/ops-gitnew file mode 100755index 00000000..d013fb6f--- /dev/null+++ b/claude-ops/bin/ops-git@@ -0,0 +1,62 @@+#!/usr/bin/env bash+# ops-git — Git status across all registered projects → JSON+# Reads from registry.json, outputs compact JSON for skill injection++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REGISTRY="${SCRIPT_DIR}/../scripts/registry.json"++if [ ! -f "$REGISTRY" ]; then+ echo '{"error":"registry.json not found"}' && exit 1+fi++# Expand ~ in paths+expand_path() { echo "${1/#\~/$HOME}"; }++# Collect results in temp file for parallel execution+TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++# Extract project count+PROJECT_COUNT=$(jq '.projects | length' "$REGISTRY")++# Process each project in parallel+for i in $(seq 0 $((PROJECT_COUNT - 1))); do+ ALIAS=$(jq -r ".projects[$i].alias" "$REGISTRY")+ PATHS_JSON=$(jq -c ".projects[$i].paths" "$REGISTRY")++ (+ RESULTS="[]"+ for path_raw in $(echo "$PATHS_JSON" | jq -r '.[]'); do+ path=$(expand_path "$path_raw")+ [ ! -d "$path/.git" ] && continue++ branch=$(git -C "$path" branch --show-current 2>/dev/null || echo "detached")+ last_commit=$(git -C "$path" log --oneline -1 --format='%s' 2>/dev/null || echo "no commits")+ last_date=$(git -C "$path" log -1 --format='%cr' 2>/dev/null || echo "unknown")+ uncommitted=$(git -C "$path" status --short 2>/dev/null | wc -l | tr -d ' ')+ ahead=$(git -C "$path" rev-list --count '@{upstream}..HEAD' 2>/dev/null || echo "0")++ RESULTS=$(echo "$RESULTS" | jq --arg p "$(basename "$path")" \+ --arg b "$branch" --arg lc "$last_commit" --arg ld "$last_date" \+ --arg u "$uncommitted" --arg a "$ahead" \+ '. + [{"repo":$p,"branch":$b,"last_commit":$lc,"last_date":$ld,"uncommitted":($u|tonumber),"ahead":($a|tonumber)}]')+ done++ echo "$RESULTS" > "$TMPDIR_OPS/$ALIAS.json"+ ) &+done+wait++# Assemble final JSON+echo -n '{'+first=true+for f in "$TMPDIR_OPS"/*.json; do+ [ ! -f "$f" ] && continue+ alias=$(basename "$f" .json)+ [ "$first" = true ] && first=false || echo -n ','+ echo -n "\"$alias\":"+ cat "$f"+done+echo '}'diff --git a/claude-ops/bin/ops-infra b/claude-ops/bin/ops-infranew file mode 100755index 00000000..c0f8e4f5--- /dev/null+++ b/claude-ops/bin/ops-infra@@ -0,0 +1,68 @@+#!/usr/bin/env bash+# ops-infra — Infrastructure health across all ECS clusters → JSON+# Reads clusters from registry.json, checks ECS service health++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REGISTRY="${SCRIPT_DIR}/../scripts/registry.json"++if [ ! -f "$REGISTRY" ]; then+ echo '{"error":"registry.json not found"}' && exit 1+fi++# Check if AWS CLI is available+if ! command -v aws &>/dev/null; then+ echo '{"error":"aws CLI not found","clusters":[]}' && exit 0+fi++# Collect unique ECS clusters from registry+CLUSTERS=$(jq -r '[.projects[].infra.ecs_clusters // [] | .[]] | unique | .[]' "$REGISTRY" 2>/dev/null)++if [ -z "$CLUSTERS" ]; then+ echo '{"clusters":[],"summary":"No ECS clusters configured"}' && exit 0+fi++TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++# Check each cluster in parallel+for cluster in $CLUSTERS; do+ (+ # List services+ SERVICES=$(aws ecs list-services --cluster "$cluster" --query 'serviceArns[*]' --output text 2>/dev/null | xargs -n1 basename 2>/dev/null | tr '\n' ' ')++ if [ -z "$SERVICES" ]; then+ echo "{\"cluster\":\"$cluster\",\"status\":\"empty\",\"services\":[]}" > "$TMPDIR_OPS/$cluster.json"+ else+ RESULT=$(aws ecs describe-services --cluster "$cluster" --services $SERVICES \+ --query 'services[*].{name:serviceName,running:runningCount,desired:desiredCount,status:status}' \+ --output json 2>/dev/null || echo '[]')++ # Calculate health+ TOTAL=$(echo "$RESULT" | jq 'length')+ HEALTHY=$(echo "$RESULT" | jq '[.[] | select(.running == .desired)] | length')++ if [ "$TOTAL" -eq "$HEALTHY" ]; then+ STATUS="healthy"+ elif [ "$HEALTHY" -eq 0 ]; then+ STATUS="down"+ else+ STATUS="degraded"+ fi++ echo "{\"cluster\":\"$cluster\",\"status\":\"$STATUS\",\"services\":$RESULT}" > "$TMPDIR_OPS/$cluster.json"+ fi+ ) &+done+wait++# Assemble+echo -n '{"clusters":['+first=true+for f in "$TMPDIR_OPS"/*.json; do+ [ ! -f "$f" ] && continue+ [ "$first" = true ] && first=false || echo -n ','+ cat "$f"+done+echo ']}'diff --git a/claude-ops/bin/ops-marketing-dash b/claude-ops/bin/ops-marketing-dashnew file mode 100755index 00000000..98c8caec--- /dev/null+++ b/claude-ops/bin/ops-marketing-dash@@ -0,0 +1,184 @@+#!/usr/bin/env bash+# ops-marketing-dash — pre-gathers data from all configured marketing channels+# Output: JSON object with data from each channel (null for unconfigured)++set -euo pipefail++# Credential resolution+KLAVIYO_KEY="${KLAVIYO_PRIVATE_KEY:-$(claude plugin config get klaviyo_private_key 2>/dev/null || echo "")}"+META_TOKEN="${META_ADS_TOKEN:-$(claude plugin config get meta_ads_token 2>/dev/null || echo "")}"+META_ACCOUNT="${META_AD_ACCOUNT_ID:-$(claude plugin config get meta_ad_account_id 2>/dev/null || echo "")}"+GA4_PROPERTY="${GA4_PROPERTY_ID:-$(claude plugin config get ga4_property_id 2>/dev/null || echo "")}"+GSC_SITE="${GOOGLE_SEARCH_CONSOLE_SITE:-$(claude plugin config get google_search_console_site 2>/dev/null || echo "")}"++# Doppler fallback+if [ -z "$KLAVIYO_KEY" ]; then+ KLAVIYO_KEY="$(doppler secrets get KLAVIYO_PRIVATE_KEY --plain 2>/dev/null || echo "")"+fi+if [ -z "$META_TOKEN" ]; then+ META_TOKEN="$(doppler secrets get META_ADS_TOKEN --plain 2>/dev/null || echo "")"+ META_ACCOUNT="$(doppler secrets get META_AD_ACCOUNT_ID --plain 2>/dev/null || echo "")"+fi++TODAY=$(date +%Y-%m-%d)++# --- Klaviyo ---+gather_klaviyo() {+ if [ -z "$KLAVIYO_KEY" ]; then+ echo "null"+ return+ fi++ # Get total subscriber count across all lists+ LISTS=$(curl -s "https://a.klaviyo.com/api/lists/?fields[list]=name,id,profile_count" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" 2>/dev/null)++ TOTAL_SUBS=$(echo "$LISTS" | jq '[.data[].attributes.profile_count // 0] | add // 0' 2>/dev/null || echo "0")++ # Get last campaign stats+ CAMPAIGNS=$(curl -s "https://a.klaviyo.com/api/campaigns/?filter=equals(messages.channel,'email')&sort=-created_at&page[size]=1&fields[campaign]=name,status,send_time" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" 2>/dev/null)++ LAST_CAMPAIGN_NAME=$(echo "$CAMPAIGNS" | jq -r '.data[0].attributes.name // "none"' 2>/dev/null || echo "none")+ LAST_CAMPAIGN_STATUS=$(echo "$CAMPAIGNS" | jq -r '.data[0].attributes.status // "none"' 2>/dev/null || echo "none")++ jq -n \+ --argjson subs "$TOTAL_SUBS" \+ --arg last_campaign "$LAST_CAMPAIGN_NAME" \+ --arg last_status "$LAST_CAMPAIGN_STATUS" \+ '{subscribers: $subs, last_campaign: $last_campaign, last_campaign_status: $last_status}'+}++# --- Meta Ads ---+gather_meta() {+ if [ -z "$META_TOKEN" ] || [ -z "$META_ACCOUNT" ]; then+ echo "null"+ return+ fi++ INSIGHTS=$(curl -s "https://graph.facebook.com/v18.0/${META_ACCOUNT}/insights?fields=spend,impressions,clicks,ctr,cpc,actions,action_values&date_preset=last_7d&level=account" \+ -H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null)++ SPEND=$(echo "$INSIGHTS" | jq -r '.data[0].spend // "0"' 2>/dev/null || echo "0")+ IMPRESSIONS=$(echo "$INSIGHTS" | jq -r '.data[0].impressions // "0"' 2>/dev/null || echo "0")+ CLICKS=$(echo "$INSIGHTS" | jq -r '.data[0].clicks // "0"' 2>/dev/null || echo "0")+ CTR=$(echo "$INSIGHTS" | jq -r '.data[0].ctr // "0"' 2>/dev/null || echo "0")++ # Extract purchase count and revenue from actions/action_values+ PURCHASES=$(echo "$INSIGHTS" | jq -r '[.data[0].actions[]? | select(.action_type == "purchase") | .value] | first // "0"' 2>/dev/null || echo "0")+ PURCHASE_VALUE=$(echo "$INSIGHTS" | jq -r '[.data[0].action_values[]? | select(.action_type == "purchase") | .value] | first // "0"' 2>/dev/null || echo "0")++ # ROAS = purchase_value / spend+ ROAS=$(awk "BEGIN {s=$SPEND+0; v=$PURCHASE_VALUE+0; if (s>0) printf \"%.2f\", v/s; else print \"0\"}")++ jq -n \+ --arg spend "$SPEND" \+ --arg impressions "$IMPRESSIONS" \+ --arg clicks "$CLICKS" \+ --arg ctr "$CTR" \+ --arg purchases "$PURCHASES" \+ --arg purchase_value "$PURCHASE_VALUE" \+ --arg roas "$ROAS" \+ '{spend: $spend, impressions: $impressions, clicks: $clicks, ctr: $ctr, purchases: $purchases, purchase_value: $purchase_value, roas: $roas}'+}++# --- GA4 ---+gather_ga4() {+ if [ -z "$GA4_PROPERTY" ]; then+ echo "null"+ return+ fi++ GA4_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || echo "")+ if [ -z "$GA4_TOKEN" ]; then+ echo "null"+ return+ fi++ REPORT=$(curl -s -X POST "https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY}:runReport" \+ -H "Authorization: Bearer ${GA4_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],+ "metrics": [+ {"name": "sessions"},+ {"name": "totalUsers"},+ {"name": "conversions"},+ {"name": "totalRevenue"},+ {"name": "bounceRate"}+ ]+ }' 2>/dev/null)++ SESSIONS=$(echo "$REPORT" | jq -r '.rows[0].metricValues[0].value // "0"' 2>/dev/null || echo "0")+ USERS=$(echo "$REPORT" | jq -r '.rows[0].metricValues[1].value // "0"' 2>/dev/null || echo "0")+ CONVERSIONS=$(echo "$REPORT" | jq -r '.rows[0].metricValues[2].value // "0"' 2>/dev/null || echo "0")+ REVENUE=$(echo "$REPORT" | jq -r '.rows[0].metricValues[3].value // "0"' 2>/dev/null || echo "0")++ CVR=$(awk "BEGIN {s=$SESSIONS+0; c=$CONVERSIONS+0; if (s>0) printf \"%.2f\", (c/s)*100; else print \"0\"}")++ jq -n \+ --arg sessions "$SESSIONS" \+ --arg users "$USERS" \+ --arg conversions "$CONVERSIONS" \+ --arg revenue "$REVENUE" \+ --arg cvr "$CVR" \+ '{sessions: $sessions, users: $users, conversions: $conversions, revenue: $revenue, cvr: $cvr}'+}++# --- Google Search Console ---+gather_gsc() {+ if [ -z "$GSC_SITE" ]; then+ echo "null"+ return+ fi++ GSC_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || echo "")+ if [ -z "$GSC_TOKEN" ]; then+ echo "null"+ return+ fi++ GSC_SITE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('${GSC_SITE}', safe=''))" 2>/dev/null \+ || echo "${GSC_SITE}" | sed 's|:|%3A|g; s|/|%2F|g')++ START_DATE=$(date -v-28d +%Y-%m-%d 2>/dev/null || date -d '28 days ago' +%Y-%m-%d 2>/dev/null || echo "")+ if [ -z "$START_DATE" ]; then+ echo "null"+ return+ fi++ REPORT=$(curl -s -X POST "https://searchconsole.googleapis.com/webmasters/v3/sites/${GSC_SITE_ENCODED}/searchAnalytics/query" \+ -H "Authorization: Bearer ${GSC_TOKEN}" \+ -H "Content-Type: application/json" \+ -d "{\"startDate\": \"${START_DATE}\", \"endDate\": \"${TODAY}\", \"dimensions\": [], \"rowLimit\": 1}" 2>/dev/null)++ CLICKS=$(echo "$REPORT" | jq -r '.rows[0].clicks // 0' 2>/dev/null || echo "0")+ IMPRESSIONS=$(echo "$REPORT" | jq -r '.rows[0].impressions // 0' 2>/dev/null || echo "0")+ CTR=$(echo "$REPORT" | jq -r '.rows[0].ctr // 0' 2>/dev/null || echo "0")+ POSITION=$(echo "$REPORT" | jq -r '.rows[0].position // 0' 2>/dev/null || echo "0")++ jq -n \+ --argjson clicks "$CLICKS" \+ --argjson impressions "$IMPRESSIONS" \+ --argjson ctr "$CTR" \+ --argjson position "$POSITION" \+ '{clicks: $clicks, impressions: $impressions, ctr: $ctr, avg_position: $position}'+}++# Run all in parallel (subshells)+KLAVIYO_DATA=$(gather_klaviyo) &+META_DATA=$(gather_meta) &+GA4_DATA=$(gather_ga4) &+GSC_DATA=$(gather_gsc) &+wait++# Emit unified JSON+jq -n \+ --argjson klaviyo "$KLAVIYO_DATA" \+ --argjson meta "$META_DATA" \+ --argjson ga4 "$GA4_DATA" \+ --argjson gsc "$GSC_DATA" \+ --arg date "$TODAY" \+ '{date: $date, klaviyo: $klaviyo, meta: $meta, ga4: $ga4, gsc: $gsc}'diff --git a/claude-ops/bin/ops-merge-scan b/claude-ops/bin/ops-merge-scannew file mode 100755index 00000000..d0b44603--- /dev/null+++ b/claude-ops/bin/ops-merge-scan@@ -0,0 +1,95 @@+#!/usr/bin/env bash+# ops-merge-scan — Scan all repos for open PRs with merge readiness data+# Extended version of ops-prs with CI status, mergeable state, and reviews+# Used by /ops:merge skill for pre-gathering PR queue++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-${SCRIPT_DIR}/..}"+REGISTRY="${PLUGIN_DIR}/scripts/registry.json"++# Optional: scope to a single repo+FILTER_REPO="${1:-}"++if [ ! -f "$REGISTRY" ]; then+ echo '{"error":"registry.json not found","prs":[]}' && exit 1+fi++if ! command -v gh &>/dev/null; then+ echo '{"error":"gh CLI not found","prs":[]}' && exit 0+fi++# Collect unique repos (or filter to one)+if [ -n "$FILTER_REPO" ]; then+ REPOS="$FILTER_REPO"+else+ REPOS=$(jq -r '[.projects[].repos[]] | unique | .[]' "$REGISTRY")+fi++TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++for repo in $REPOS; do+ (+ SAFE_NAME=$(echo "$repo" | tr '/' '_')+ PRS=$(gh pr list --repo "$repo" --state open --limit 15 \+ --json number,title,headRefName,isDraft,reviewDecision,mergeable,mergeStateStatus,createdAt,author \+ 2>/dev/null || echo '[]')++ if [ "$PRS" != "[]" ] && [ -n "$PRS" ]; then+ # Enrich each PR with CI status via gh pr view (statusCheckRollup only works there)+ ENRICHED=$(echo "$PRS" | jq -c '.[]' | while read -r pr; do+ NUM=$(echo "$pr" | jq -r '.number')+ # Get CI status for this specific PR+ CI_JSON=$(gh pr view "$NUM" --repo "$repo" --json statusCheckRollup 2>/dev/null || echo '{"statusCheckRollup":[]}')+ echo "$pr" | jq --argjson ci "$CI_JSON" '. + {statusCheckRollup: $ci.statusCheckRollup}'+ done | jq -s '.')++ # Classify each PR+ CLASSIFIED=$(echo "$ENRICHED" | jq --arg repo "$repo" '[.[] | {+ repo: $repo,+ number,+ title,+ branch: .headRefName,+ draft: .isDraft,+ review: .reviewDecision,+ mergeable: .mergeable,+ merge_state: .mergeStateStatus,+ ci_status: (if (.statusCheckRollup | length) > 0 then+ (if (.statusCheckRollup | map(select(.conclusion == "FAILURE")) | length) > 0 then "failing"+ elif (.statusCheckRollup | map(select(.status != "COMPLETED")) | length) > 0 then "pending"+ else "passing" end)+ else "unknown" end),+ ci_failures: [(.statusCheckRollup // [])[] | select(.conclusion == "FAILURE") | .name],+ created: .createdAt,+ author: .author.login,+ classification: (+ if .isDraft then "draft"+ elif .mergeable == "CONFLICTING" then "needs-rebase"+ elif (.statusCheckRollup // [] | map(select(.conclusion == "FAILURE")) | length) > 0 then "needs-ci-fix"+ elif .reviewDecision == "CHANGES_REQUESTED" then "needs-review-response"+ elif .mergeStateStatus == "BLOCKED" then "blocked"+ elif .mergeable == "MERGEABLE" and .reviewDecision == "APPROVED" then "ready"+ else "unknown" end+ )+ }]')+ echo "$CLASSIFIED" > "$TMPDIR_OPS/$SAFE_NAME.json"+ fi+ ) &+done+wait++# Assemble flat array of all PRs+echo -n '{"prs":['+first=true+for f in "$TMPDIR_OPS"/*.json; do+ [ ! -f "$f" ] && continue+ ITEMS=$(cat "$f")+ COUNT=$(echo "$ITEMS" | jq 'length')+ for i in $(seq 0 $((COUNT - 1))); do+ [ "$first" = true ] && first=false || echo -n ','+ echo "$ITEMS" | jq ".[$i]"+ done+done+echo '],"scanned_at":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}'diff --git a/claude-ops/bin/ops-post-session-cleanup b/claude-ops/bin/ops-post-session-cleanupnew file mode 100755index 00000000..709dbccd--- /dev/null+++ b/claude-ops/bin/ops-post-session-cleanup@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Stop hook: cleanup stale worktrees and temp files on session end+set -euo pipefail++# Clean temp wacli files+rm -f /tmp/wacli-sync-probe-*.log /tmp/wacli-bootstrap-*.log 2>/dev/null || true++# Clean stale agent worktrees older than 2 hours+find "$HOME/Projects/claude-ops/.worktrees" -maxdepth 1 -type d -mmin +120 -exec rm -rf {} \; 2>/dev/null || true++exit 0diff --git a/claude-ops/bin/ops-pretool-wacli-health b/claude-ops/bin/ops-pretool-wacli-healthnew file mode 100755index 00000000..819d2dc2--- /dev/null+++ b/claude-ops/bin/ops-pretool-wacli-health@@ -0,0 +1,32 @@+#!/usr/bin/env bash+# PreToolUse hook: check wacli health before WhatsApp commands+# Receives tool input as $1, checks if it contains wacli commands+set -euo pipefail++INPUT="${1:-}"++# Only check if the command involves wacli+if ! echo "$INPUT" | grep -q "wacli"; then+ exit 0+fi++# Check health file+HEALTH_FILE="$HOME/.wacli/.health"+if [[ -f "$HEALTH_FILE" ]]; then+ STATUS=$(grep "^status=" "$HEALTH_FILE" | cut -d= -f2)+ if [[ "$STATUS" == "needs_auth" ]] || [[ "$STATUS" == "needs_reauth" ]]; then+ echo "⚠ WhatsApp needs re-authentication. Run 'wacli auth' in a separate terminal."+ # Don't block — just warn. The skill's own health check will handle it.+ fi+fi++# Check daemon health+DAEMON_HEALTH="$HOME/.claude/plugins/data/ops-ops-marketplace/daemon-health.json"+if [[ -f "$DAEMON_HEALTH" ]]; then+ ACTION=$(python3 -c "import json; d=json.load(open('$DAEMON_HEALTH')); print(d.get('action_needed') or '')" 2>/dev/null || true)+ if [[ -n "$ACTION" ]] && [[ "$ACTION" != "None" ]]; then+ echo "⚠ Daemon action needed: $ACTION"+ fi+fi++exit 0diff --git a/claude-ops/bin/ops-prs b/claude-ops/bin/ops-prsnew file mode 100755index 00000000..223c0a79--- /dev/null+++ b/claude-ops/bin/ops-prs@@ -0,0 +1,45 @@+#!/usr/bin/env bash+# ops-prs — Open PRs across all registered repos → JSON+# Reads from registry.json, queries GitHub via gh CLI++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REGISTRY="${SCRIPT_DIR}/../scripts/registry.json"++if [ ! -f "$REGISTRY" ]; then+ echo '{"error":"registry.json not found"}' && exit 1+fi++if ! command -v gh &>/dev/null; then+ echo '{"error":"gh CLI not found","prs":[]}' && exit 0+fi++# Collect unique repos+REPOS=$(jq -r '[.projects[].repos[]] | unique | .[]' "$REGISTRY")++TMPDIR_OPS=$(mktemp -d)+trap 'rm -rf "$TMPDIR_OPS"' EXIT++for repo in $REPOS; do+ (+ SAFE_NAME=$(echo "$repo" | tr '/' '_')+ PRS=$(gh pr list --repo "$repo" --state open --limit 10 \+ --json number,title,headRefName,isDraft,reviewDecision,createdAt,author 2>/dev/null || echo '[]')++ if [ "$PRS" != "[]" ] && [ -n "$PRS" ]; then+ echo "{\"repo\":\"$repo\",\"prs\":$PRS}" > "$TMPDIR_OPS/$SAFE_NAME.json"+ fi+ ) &+done+wait++# Assemble — only repos with PRs+echo -n '{"repos_with_prs":['+first=true+for f in "$TMPDIR_OPS"/*.json; do+ [ ! -f "$f" ] && continue+ [ "$first" = true ] && first=false || echo -n ','+ cat "$f"+done+echo ']}'diff --git a/claude-ops/bin/ops-setup-complete b/claude-ops/bin/ops-setup-completenew file mode 100755index 00000000..c5ec626e--- /dev/null+++ b/claude-ops/bin/ops-setup-complete@@ -0,0 +1,92 @@+#!/usr/bin/env bash+# ops-setup-complete — Post-setup celebration banner+# Usage: ops-setup-complete --channels N --projects N --agents N --skills N+set -euo pipefail++# --- Parse arguments ---+CHANNELS=0 PROJECTS=0 AGENTS=9 SKILLS=15+while [[ $# -gt 0 ]]; do+ case "$1" in+ --channels) CHANNELS="$2"; shift 2 ;;+ --projects) PROJECTS="$2"; shift 2 ;;+ --agents) AGENTS="$2"; shift 2 ;;+ --skills) SKILLS="$2"; shift 2 ;;+ *) shift ;;+ esac+done++# --- Color setup ---+if [[ -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then+ RST=$'\033[0m'+ BOLD=$'\033[1m'+ DIM=$'\033[2m'+ CYN=$'\033[36m'+ GRN=$'\033[32m'+ YLW=$'\033[33m'+ BCYN=$'\033[1;36m'+ BGRN=$'\033[1;32m'+ BWHT=$'\033[1;37m'+else+ RST="" BOLD="" DIM="" CYN="" GRN="" YLW="" BCYN="" BGRN="" BWHT=""+fi++D=0.025+p() { printf '%s\n' "$1"; sleep "$D"; }++# --- Header ---+p ""+p " ${DIM}${CYN}╔══════════════════════════════════════════════════╗${RST}"+p " ${DIM}${CYN}║${RST} ${DIM}${CYN}║${RST}"+p " ${DIM}${CYN}║${RST} ${BGRN}SYSTEM ONLINE${RST} ${DIM}${CYN}║${RST}"+p " ${DIM}${CYN}║${RST} ${DIM}claude-ops v0.3.0 configured successfully${RST} ${DIM}${CYN}║${RST}"+p " ${DIM}${CYN}║${RST} ${DIM}${CYN}║${RST}"+p " ${DIM}${CYN}╚══════════════════════════════════════════════════╝${RST}"++sleep 0.1+p ""++# --- Dashboard ---+p " ${DIM}${CYN}┌──────────────────────────────────────────────────┐${RST}"+p " ${DIM}${CYN}│${RST} ${BWHT}OPERATIONAL DASHBOARD${RST} ${DIM}${CYN}│${RST}"+p " ${DIM}${CYN}├──────────────────────────────────────────────────┤${RST}"++# Channels row+if [[ "$CHANNELS" -gt 0 ]]; then+ printf ' %s%s│%s %s[*]%s Channels %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$GRN" "$RST" "$BWHT" "$CHANNELS active" "$RST" "$DIM$CYN" "$RST"+ sleep "$D"+else+ printf ' %s%s│%s %s[ ]%s Channels %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$YLW" "$RST" "$DIM" "none configured" "$RST" "$DIM$CYN" "$RST"+ sleep "$D"+fi++# Projects row+if [[ "$PROJECTS" -gt 0 ]]; then+ printf ' %s%s│%s %s[*]%s Projects %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$GRN" "$RST" "$BWHT" "$PROJECTS registered" "$RST" "$DIM$CYN" "$RST"+ sleep "$D"+else+ printf ' %s%s│%s %s[ ]%s Projects %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$YLW" "$RST" "$DIM" "none registered" "$RST" "$DIM$CYN" "$RST"+ sleep "$D"+fi++# Agents row+printf ' %s%s│%s %s[*]%s Agents %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$GRN" "$RST" "$BWHT" "$AGENTS standing by" "$RST" "$DIM$CYN" "$RST"+sleep "$D"++# Skills row+printf ' %s%s│%s %s[*]%s Skills %s%-33s%s%s│%s\n' \+ "$DIM" "$CYN" "$RST" "$GRN" "$RST" "$BWHT" "$SKILLS loaded" "$RST" "$DIM$CYN" "$RST"+sleep "$D"++p " ${DIM}${CYN}└──────────────────────────────────────────────────┘${RST}"++sleep 0.1+p ""+p " ${DIM}${CYN}────────────────────────────────────────────────────${RST}"+p ""+p " ${BWHT}You're ready.${RST} Type ${BCYN}/ops:go${RST} for your first briefing."+p ""diff --git a/claude-ops/bin/ops-setup-detect b/claude-ops/bin/ops-setup-detectnew file mode 100755index 00000000..79a977c7--- /dev/null+++ b/claude-ops/bin/ops-setup-detect@@ -0,0 +1,122 @@+#!/usr/bin/env bash+# ops-setup-detect — Emit current configuration state as JSON+# Used by /ops:setup wizard to decide what still needs configuring.+# Reads from /tmp/ops-preflight/ cache when available (populated by ops-setup-preflight).+set -euo pipefail++has() { command -v "$1" >/dev/null 2>&1 && echo true || echo false; }+has_env() { [ -n "${!1:-}" ] && echo true || echo false; }++PREFLIGHT="/tmp/ops-preflight"+USE_CACHE=false+if [ -f "$PREFLIGHT/.complete" ]; then+ USE_CACHE=true+fi++SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+REGISTRY="$SCRIPT_DIR/scripts/registry.json"++# Preferences live in Claude Code's per-plugin data dir so they survive plugin+# reinstalls/version bumps. Falls back to the plugin source dir for users who+# run bin/ops-setup-detect directly outside a Claude Code plugin context.+PREFS_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+PREFS="$PREFS_DIR/preferences.json"+if [ ! -f "$PREFS" ] && [ -f "$SCRIPT_DIR/scripts/preferences.json" ]; then+ # Legacy location — still honor it so old installs keep working until migrated.+ PREFS="$SCRIPT_DIR/scripts/preferences.json"+fi++PROJECT_COUNT=0+# Prefer cached registry from preflight+CACHED_REGISTRY="$PREFLIGHT/existing-registry.json"+if [ "$USE_CACHE" = true ] && [ -f "$CACHED_REGISTRY" ] && command -v jq >/dev/null 2>&1; then+ PROJECT_COUNT=$(jq '.projects | length' "$CACHED_REGISTRY" 2>/dev/null || echo 0)+elif [ -f "$REGISTRY" ] && command -v jq >/dev/null 2>&1; then+ PROJECT_COUNT=$(jq '.projects | length' "$REGISTRY" 2>/dev/null || echo 0)+fi++SHELL_NAME="$(basename "${SHELL:-zsh}")"+case "$SHELL_NAME" in+ zsh) PROFILE_FILE="$HOME/.zshrc" ;;+ bash) PROFILE_FILE="$HOME/.bashrc" ;;+ fish) PROFILE_FILE="$HOME/.config/fish/config.fish" ;;+ *) PROFILE_FILE="$HOME/.profile" ;;+esac++PLATFORM="$(uname -s | tr '[:upper:]' '[:lower:]')"++# Detect configured MCP servers — use preflight cache if available+MCP_CONFIGURED=()+if [ "$USE_CACHE" = true ] && [ -f "$PREFLIGHT/mcp-servers.txt" ]; then+ while IFS= read -r name; do+ [ -n "$name" ] && MCP_CONFIGURED+=("$name")+ done < "$PREFLIGHT/mcp-servers.txt"+else+ for f in "$SCRIPT_DIR/.mcp.json" "$HOME/.claude/.mcp.json" "$HOME/.claude.json"; do+ [ -f "$f" ] || continue+ if command -v jq >/dev/null 2>&1; then+ while IFS= read -r name; do+ [ -n "$name" ] && MCP_CONFIGURED+=("$name")+ done < <(jq -r '(.mcpServers // {}) | keys[]' "$f" 2>/dev/null || true)+ fi+ done+fi++# Deduplicate+MCP_JSON="[]"+if [ ${#MCP_CONFIGURED[@]} -gt 0 ] && command -v jq >/dev/null 2>&1; then+ MCP_JSON=$(printf '%s\n' "${MCP_CONFIGURED[@]}" | sort -u | jq -R . | jq -s .)+fi++# Helper: check cache or live for a tool+tool_status() {+ local tool="$1"+ if [ "$USE_CACHE" = true ] && [ -f "$PREFLIGHT/clis.txt" ]; then+ local cached+ cached=$(grep "^${tool}=" "$PREFLIGHT/clis.txt" 2>/dev/null | head -1 || echo "")+ if [ -n "$cached" ]; then+ if echo "$cached" | grep -q "=missing$"; then echo false; else echo true; fi+ return+ fi+ fi+ has "$tool"+}++cat <<EOF+{+ "platform": "$PLATFORM",+ "shell": "$SHELL_NAME",+ "profile_file": "$PROFILE_FILE",+ "plugin_root": "$SCRIPT_DIR",+ "preflight_cache": $USE_CACHE,+ "tools": {+ "jq": $(tool_status jq),+ "git": $(tool_status git),+ "gh": $(tool_status gh),+ "aws": $(tool_status aws),+ "node": $(tool_status node),+ "brew": $(tool_status brew),+ "doppler": $(tool_status doppler),+ "wacli": $(tool_status wacli),+ "gog": $(tool_status gog),+ "sentry-cli": $(tool_status sentry-cli)+ },+ "env_vars": {+ "CLAUDE_PLUGIN_ROOT": $(has_env CLAUDE_PLUGIN_ROOT),+ "TELEGRAM_BOT_TOKEN": $(has_env TELEGRAM_BOT_TOKEN),+ "TELEGRAM_OWNER_ID": $(has_env TELEGRAM_OWNER_ID),+ "AWS_PROFILE": $(has_env AWS_PROFILE),+ "GH_TOKEN": $(has_env GH_TOKEN)+ },+ "mcp_configured": $MCP_JSON,+ "registry": {+ "exists": $([ -f "$REGISTRY" ] && echo true || echo false),+ "project_count": $PROJECT_COUNT,+ "path": "$REGISTRY"+ },+ "preferences": {+ "exists": $([ -f "$PREFS" ] && echo true || echo false),+ "path": "$PREFS"+ }+}+EOFdiff --git a/claude-ops/bin/ops-setup-install b/claude-ops/bin/ops-setup-installnew file mode 100755index 00000000..3b6f2cf1--- /dev/null+++ b/claude-ops/bin/ops-setup-install@@ -0,0 +1,56 @@+#!/usr/bin/env bash+# ops-setup-install — Idempotent installer for ops CLI dependencies+# Usage: ops-setup-install <tool> [<tool>...]+# Tools: jq git gh aws node doppler wacli gog sentry-cli+set -euo pipefail++PLATFORM="$(uname -s | tr '[:upper:]' '[:lower:]')"++install_mac() {+ local tool="$1"+ if ! command -v brew >/dev/null 2>&1; then+ echo "✗ Homebrew not found. Install from https://brew.sh first." >&2+ return 1+ fi+ case "$tool" in+ jq) brew install jq ;;+ git) brew install git ;;+ gh) brew install gh ;;+ aws) brew install awscli ;;+ node) brew install node ;;+ doppler) brew install dopplerhq/cli/doppler ;;+ sentry-cli) brew install getsentry/tools/sentry-cli ;;+ expect) brew install expect ;;+ wacli) echo "○ wacli is not on Homebrew — install manually: https://github.com/wacli/wacli" >&2; return 2 ;;+ gog) echo "○ gog is not on Homebrew — install manually or skip email integration." >&2; return 2 ;;+ *) echo "✗ Unknown tool: $tool" >&2; return 1 ;;+ esac+}++install_linux() {+ local tool="$1"+ if command -v apt-get >/dev/null 2>&1; then+ case "$tool" in+ jq|git|gh|awscli) sudo apt-get install -y "$tool" ;;+ aws) sudo apt-get install -y awscli ;;+ node) sudo apt-get install -y nodejs npm ;;+ *) echo "○ $tool not handled by apt — install manually." >&2; return 2 ;;+ esac+ else+ echo "✗ No supported package manager found (apt-get)." >&2+ return 1+ fi+}++for tool in "$@"; do+ if command -v "$tool" >/dev/null 2>&1; then+ echo "✓ $tool already installed"+ continue+ fi+ echo "⏳ Installing $tool..."+ case "$PLATFORM" in+ darwin) install_mac "$tool" ;;+ linux) install_linux "$tool" ;;+ *) echo "✗ Unsupported platform: $PLATFORM" >&2; exit 1 ;;+ esac+donediff --git a/claude-ops/bin/ops-setup-preflight b/claude-ops/bin/ops-setup-preflightnew file mode 100755index 00000000..2b25c30d--- /dev/null+++ b/claude-ops/bin/ops-setup-preflight@@ -0,0 +1,117 @@+#!/usr/bin/env bash+# ops-setup-preflight — gather all setup data in parallel (runs in background)+# Results written to /tmp/ops-preflight/ for the setup wizard to read+set -euo pipefail++OUT="/tmp/ops-preflight"+rm -rf "$OUT" && mkdir -p "$OUT"++# All probes run in parallel as background jobs+{+ # CLI detection+ for tool in jq git gh aws node brew doppler wacli gog sentry-cli expect; do+ if command -v "$tool" &>/dev/null; then+ ver=$("$tool" --version 2>/dev/null | head -1 || echo "installed")+ echo "$tool=$ver" >> "$OUT/clis.txt"+ else+ echo "$tool=missing" >> "$OUT/clis.txt"+ fi+ done+} &++{+ # Slack keychain scout+ xoxc=$(security find-generic-password -s slack-xoxc -w 2>/dev/null || echo "")+ xoxd=$(security find-generic-password -s slack-xoxd -w 2>/dev/null || echo "")+ if [ -n "$xoxc" ] && [ -n "$xoxd" ]; then+ # Validate+ result=$(curl -s -H "Authorization: Bearer $xoxc" -b "d=$xoxd" "https://slack.com/api/auth.test" 2>/dev/null || echo '{"ok":false}')+ echo "$result" > "$OUT/slack.json"+ else+ echo '{"ok":false,"reason":"no_keychain_tokens"}' > "$OUT/slack.json"+ fi+} &++{+ # Telegram keychain scout+ for key in telegram-api-id telegram-api-hash telegram-phone telegram-session; do+ val=$(security find-generic-password -s "$key" -w 2>/dev/null || echo "")+ echo "$key=$( [ -n "$val" ] && echo "found" || echo "missing" )" >> "$OUT/telegram.txt"+ done+} &++{+ # gog/Gmail probe+ if command -v gog &>/dev/null; then+ gog auth status 2>&1 > "$OUT/gog-auth.txt"+ gog gmail labels list --json 2>/dev/null | head -5 > "$OUT/gog-gmail.json" || echo '{"error":"failed"}' > "$OUT/gog-gmail.json"+ gog cal list --json --max 3 2>/dev/null | head -30 > "$OUT/gog-cal.json" || echo '{"error":"failed"}' > "$OUT/gog-cal.json"+ else+ echo "gog=missing" > "$OUT/gog-auth.txt"+ fi+} &++{+ # WhatsApp probe+ if command -v wacli &>/dev/null; then+ wacli doctor --json 2>/dev/null > "$OUT/wacli-doctor.json" || echo '{"success":false}' > "$OUT/wacli-doctor.json"+ wacli chats list --json 2>/dev/null > "$OUT/wacli-chats.json" || echo '{"success":false,"data":[]}' > "$OUT/wacli-chats.json"+ else+ echo '{"success":false,"reason":"not_installed"}' > "$OUT/wacli-doctor.json"+ fi+} &++{+ # MCP detection (scan ~/.claude.json)+ if [ -f "$HOME/.claude.json" ]; then+ jq -r '.mcpServers // {} | keys[]' "$HOME/.claude.json" 2>/dev/null > "$OUT/mcp-servers.txt" || true+ fi+} &++{+ # GitHub auth check+ gh auth status 2>&1 > "$OUT/gh-auth.txt" || true+} &++{+ # AWS identity check+ aws sts get-caller-identity --output json 2>/dev/null > "$OUT/aws-identity.json" || echo '{"error":"not_configured"}' > "$OUT/aws-identity.json"+} &++{+ # Project discovery (fast — maxdepth 2, exclude heavy dirs)+ find ~/Projects -maxdepth 2 -name ".git" -type d 2>/dev/null | sed 's|/.git$||' | sort > "$OUT/projects.txt"+} &++{+ # Existing registry+ PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-}"+ if [ -z "$PLUGIN_ROOT" ]; then+ PLUGIN_ROOT=$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1)+ fi+ if [ -n "$PLUGIN_ROOT" ] && [ -f "$PLUGIN_ROOT/scripts/registry.json" ]; then+ cp "$PLUGIN_ROOT/scripts/registry.json" "$OUT/existing-registry.json"+ fi+} &++{+ # Existing preferences+ PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+ if [ -f "$PREFS" ]; then+ cp "$PREFS" "$OUT/existing-prefs.json"+ fi+} &++{+ # Auto-fix pass: silently repair wacli FTS, missing MCPs, etc.+ SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+ if [ -x "$SCRIPT_DIR/bin/ops-autofix" ]; then+ "$SCRIPT_DIR/bin/ops-autofix" --json > "$OUT/autofix.json" 2>/dev/null || true+ fi+} &++# Wait for all background jobs+wait++# Write completion marker+echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$OUT/.complete"diff --git a/claude-ops/bin/ops-shopify-create b/claude-ops/bin/ops-shopify-createnew file mode 100755index 00000000..487bda07--- /dev/null+++ b/claude-ops/bin/ops-shopify-create@@ -0,0 +1,236 @@+#!/usr/bin/env bash+# ops-shopify-create — Create a Shopify admin app from the claude-ops template+# Usage: ops-shopify-create <app-name> <path> [--client-id <id>] [--org-id <id>]+#+# Fully automated flow:+# 1. Auth via device-code OAuth (auto-opens browser)+# 2. Fetch org ID from Shopify Partners API+# 3. Scaffold app from ops template with ALL flags (zero interactive prompts)+# 4. Inject client_id into shopify.app.toml+set -euo pipefail++APP_NAME="${1:?Usage: ops-shopify-create <app-name> <path> [--client-id <id>] [--org-id <id>]}"+APP_PATH="${2:?Usage: ops-shopify-create <app-name> <path> [--client-id <id>] [--org-id <id>]}"+CLIENT_ID=""+ORG_ID=""++shift 2+while [[ $# -gt 0 ]]; do+ case "$1" in+ --client-id) CLIENT_ID="$2"; shift 2 ;;+ --org-id) ORG_ID="$2"; shift 2 ;;+ *) shift ;;+ esac+done++PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$(realpath "$0")")")}"+TEMPLATE_DIR="$PLUGIN_ROOT/templates/shopify-admin-app"++# Ensure expect is available+if ! command -v expect &>/dev/null; then+ echo "Installing expect via Homebrew..."+ brew install expect 2>/dev/null || { echo "ERROR: expect is required. Install with: brew install expect"; exit 1; }+fi++# ── Step 1: Authenticate ──────────────────────────────────────────────────────+# Check Shopify CLI session cache for a valid token+SHOPIFY_PREFS="$HOME/Library/Preferences/shopify-cli-kit-nodejs/config.json"+NEEDS_AUTH=true++if [[ -f "$SHOPIFY_PREFS" ]]; then+ # Check if session has a non-expired token+ HAS_TOKEN=$(python3 -c "+import json, sys+from datetime import datetime, timezone+d = json.load(open('$SHOPIFY_PREFS'))+ss = json.loads(d.get('sessionStore', '{}'))+for domain, accounts in ss.items():+ for uid, data in accounts.items():+ identity = data.get('identity', {})+ expires = identity.get('expiresAt', '')+ if expires:+ exp = datetime.fromisoformat(expires.replace('Z', '+00:00'))+ if exp > datetime.now(timezone.utc):+ print('valid')+ sys.exit(0)+print('expired')+" 2>/dev/null || echo "expired")++ if [[ "$HAS_TOKEN" == "valid" ]]; then+ echo "✓ Shopify CLI session is valid"+ NEEDS_AUTH=false+ fi+fi++if $NEEDS_AUTH; then+ echo "Authenticating with Shopify CLI..."+ expect -c '+ set timeout 120+ spawn npx shopify auth login+ expect {+ -re {Open this link.*: (https://\S+)} {+ set url $expect_out(1,string)+ exec open $url &+ puts "\n>>> Opened auth URL in browser — approve in your browser"+ exp_continue+ }+ -re {Logged in} {+ puts "\n>>> Auth complete"+ }+ eof {}+ timeout { puts "AUTH TIMEOUT — approve the device code in your browser"; exit 1 }+ }+ catch wait result+ '+fi++# ── Step 2: Fetch org ID from Shopify Partners API ───────────────────────────+if [[ -z "$ORG_ID" ]]; then+ echo "Fetching organization ID from Shopify..."++ # Extract access token from Shopify CLI session cache+ ACCESS_TOKEN=$(python3 -c "+import json, sys+d = json.load(open('$SHOPIFY_PREFS'))+ss = json.loads(d.get('sessionStore', '{}'))+for domain, accounts in ss.items():+ for uid, data in accounts.items():+ identity = data.get('identity', {})+ token = identity.get('accessToken', '')+ if token:+ print(token)+ sys.exit(0)+" 2>/dev/null || echo "")++ if [[ -n "$ACCESS_TOKEN" ]]; then+ # Query Partners API for organizations+ ORG_RESULT=$(curl -s -X POST "https://partners.shopify.com/api/2024-01/graphql.json" \+ -H "Authorization: Bearer $ACCESS_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"query":"{ currentUserAccount { organizations(first: 10) { nodes { id name } } } }"}' 2>/dev/null || echo "{}")++ # Also try the CLI's internal API+ if echo "$ORG_RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); orgs=d.get('data',{}).get('currentUserAccount',{}).get('organizations',{}).get('nodes',[]); print(len(orgs))" 2>/dev/null | grep -q "^0$"; then+ # Try alternate endpoint — Shopify CLI uses this internally+ ORG_RESULT=$(python3 -c "+import json+d = json.load(open('$SHOPIFY_PREFS'))+for key, val in d.get('cache', {}).items():+ v = val.get('value', '')+ if isinstance(v, str) and 'organization' in v.lower():+ parsed = json.loads(v)+ orgs = parsed.get('currentUserAccount', {}).get('organizations', {}).get('nodes', [])+ if orgs:+ # Print first org ID+ print(orgs[0].get('id', ''))+ break+" 2>/dev/null || echo "")++ if [[ -n "$ORG_RESULT" ]]; then+ ORG_ID="$ORG_RESULT"+ fi+ else+ # Parse first org from GraphQL response+ ORG_ID=$(echo "$ORG_RESULT" | python3 -c "+import json, sys+d = json.load(sys.stdin)+orgs = d.get('data',{}).get('currentUserAccount',{}).get('organizations',{}).get('nodes',[])+if orgs:+ # org ID is a GID like 'gid://partners/Organization/12345' — extract numeric part+ gid = orgs[0].get('id', '')+ print(gid.split('/')[-1] if '/' in gid else gid)+" 2>/dev/null || echo "")+ fi+ fi++ if [[ -n "$ORG_ID" ]]; then+ echo "✓ Using organization: $ORG_ID"+ else+ echo "⚠ No organization found. You may need to create one at partners.shopify.com"+ echo " The CLI will prompt for org selection (expect will auto-select the first one)"+ fi+fi++# ── Step 3: Scaffold app ─────────────────────────────────────────────────────+echo ""+echo "Creating Shopify app: $APP_NAME"+echo "Template: $TEMPLATE_DIR"+echo "Path: $APP_PATH"++# Build CLI args — pass ALL flags to avoid interactive prompts+CLI_ARGS=(+ --name "$APP_NAME"+ --template "$TEMPLATE_DIR"+ --package-manager npm+ --path "$APP_PATH"+ --flavor typescript+)++[[ -n "$CLIENT_ID" ]] && CLI_ARGS+=(--client-id "$CLIENT_ID")+[[ -n "$ORG_ID" ]] && CLI_ARGS+=(--organization-id "$ORG_ID")++# Try non-interactive first+echo "Running: npx @shopify/create-app@latest ${CLI_ARGS[*]}"+CREATE_OUTPUT=$(npx @shopify/create-app@latest "${CLI_ARGS[@]}" 2>&1) && {+ echo "$CREATE_OUTPUT" | tail -5+ echo "✓ App created successfully (non-interactive)"+} || {+ EXIT_CODE=$?+ if echo "$CREATE_OUTPUT" | grep -q "Failed to prompt"; then+ echo "CLI requires interactive input — falling back to expect..."++ # Fall back to expect for any remaining prompts+ expect -c "+ set timeout 300+ spawn npx @shopify/create-app@latest ${CLI_ARGS[*]}++ expect {+ -re {Open this link.*: (https://\\S+)} {+ set url \$expect_out(1,string)+ exec open \$url &+ exp_continue+ }+ -re {Logged in} { exp_continue }+ -re {language|flavor} {+ send \"\033\[B\r\"+ exp_continue+ }+ -re {organization|Which org} {+ send \"\r\"+ exp_continue+ }+ -re {\\(Y/n\\)} { send \"Y\r\"; exp_continue }+ -re {\\(y/N\\)} { send \"y\r\"; exp_continue }+ -re {\\? } { send \"\r\"; exp_continue }+ eof {}+ timeout { puts \"TIMEOUT creating app\"; exit 1 }+ }+ catch wait result+ exit [lindex \$result 3]+ "+ else+ echo "$CREATE_OUTPUT" | tail -10+ exit $EXIT_CODE+ fi+}++# ── Step 4: Post-setup ───────────────────────────────────────────────────────+# Inject client_id if provided+if [[ -n "$CLIENT_ID" ]] && [[ -f "$APP_PATH/shopify.app.toml" ]]; then+ sed -i '' "s/client_id = \"\"/client_id = \"$CLIENT_ID\"/" "$APP_PATH/shopify.app.toml"+ echo "✓ Injected client_id into shopify.app.toml"+fi++# Verify the app was created+if [[ -f "$APP_PATH/package.json" ]]; then+ echo ""+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo " ✓ Shopify app created: $APP_NAME"+ echo " Path: $APP_PATH"+ echo " Template: claude-ops admin (full scopes)"+ echo " Next: cd $APP_PATH && npx shopify app dev"+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+else+ echo "✗ App creation may have failed — check $APP_PATH"+ exit 1+fidiff --git a/claude-ops/bin/ops-slack-autolink.mjs b/claude-ops/bin/ops-slack-autolink.mjsnew file mode 100755index 00000000..f1d84b3e--- /dev/null+++ b/claude-ops/bin/ops-slack-autolink.mjs@@ -0,0 +1,868 @@+#!/usr/bin/env node+/**+ * ops-slack-autolink — extract Slack XOXC and XOXD tokens via Playwright.+ *+ * Ported from maorfr/slack-token-extractor (Python/Playwright) to keep the+ * claude-ops plugin pure-Node. Launches a persistent-profile Chromium with+ * Playwright, navigates to the user's Slack workspace, prompts them to log+ * in if needed, then pulls the xoxc- user token from localStorage and the+ * d= (xoxd-...) cookie from the browser cookie jar.+ *+ * Usage:+ * ops-slack-autolink [--workspace URL] [--headless] [--profile-dir DIR]+ *+ * Options:+ * --workspace Slack workspace URL (default: https://app.slack.com/client/)+ * --headless Run headless (only works if profile already has a session)+ * --profile-dir Persistent browser profile dir (default: ~/.claude-ops/slack-profile)+ * --ready-file File to touch when login is complete (default: /tmp/slack-login-done)+ * --scout-only Only scan existing locations for tokens; don't launch browser+ *+ * Bridge protocol (stderr, one JSON event per line):+ * {"type": "phase", "phase": 1 | 2, "message": "..."}+ * {"type": "found", "source": "...", "xoxc_token": "...", "xoxd_token": "..."}+ * {"type": "need_login", "message": "...", "ready_file": "..."}+ * {"type": "error", "message": "..."}+ *+ * Final result (stdout, one JSON line):+ * {"xoxc_token": "xoxc-...", "xoxd_token": "xoxd-...", "team_id": "T...", "source": "scout|playwright"}+ */++import { existsSync, readFileSync, mkdirSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { parseArgs } from "node:util";+import { execSync } from "node:child_process";++const { values } = parseArgs({+ options: {+ workspace: { type: "string", default: "https://app.slack.com/client/" },+ headless: { type: "boolean", default: false },+ "profile-dir": {+ type: "string",+ default: join(homedir(), ".claude-ops", "slack-profile"),+ },+ "ready-file": { type: "string", default: "/tmp/slack-login-done" },+ "scout-only": { type: "boolean", default: false },+ },+});++const WORKSPACE = values.workspace;+const HEADLESS = values.headless;+const PROFILE_DIR = values["profile-dir"];+const READY_FILE = values["ready-file"];+const SCOUT_ONLY = values["scout-only"];++function emit(event) {+ process.stderr.write(JSON.stringify(event) + "\n");+}+function die(msg, extra = {}) {+ emit({ type: "error", message: msg, ...extra });+ process.exit(1);+}++// Validate --workspace before anything uses it — must be https:// and a *.slack.com host.+// Prevents file://, data:, chrome:// schemes that could load local state and poison+// localStorage-based token extraction.+function validateWorkspaceURL(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch (e) {+ die(`--workspace is not a valid URL: ${e.message}`, { raw });+ }+ if (u.protocol !== "https:")+ die(`--workspace must use https:// (got ${u.protocol})`, { raw });+ const host = u.hostname.toLowerCase();+ if (host !== "slack.com" && !host.endsWith(".slack.com")) {+ die(+ `--workspace hostname must be slack.com or a *.slack.com subdomain (got ${host})`,+ { raw },+ );+ }+ return u.toString();+}+const WORKSPACE_VALIDATED = validateWorkspaceURL(WORKSPACE);++// --- Phase 1: scout existing locations for already-extracted tokens ---+emit({+ type: "phase",+ phase: 1,+ message: "Scouting for existing Slack tokens",+});++function scoutSources() {+ const sources = [];++ // 1. ~/.claude.json mcpServers.slack.env — where Claude Code stores them+ const claudeJson = join(homedir(), ".claude.json");+ if (existsSync(claudeJson)) {+ try {+ const parsed = JSON.parse(readFileSync(claudeJson, "utf8"));+ const env = parsed?.mcpServers?.slack?.env;+ if (env) {+ const xoxc = env.SLACK_MCP_XOXC_TOKEN || env.SLACK_BOT_TOKEN;+ const xoxd = env.SLACK_MCP_XOXD_TOKEN;+ if (+ xoxc &&+ xoxc.startsWith("xoxc-") &&+ xoxd &&+ xoxd.startsWith("xoxd-")+ ) {+ sources.push({+ source: "claude.json:mcpServers.slack",+ xoxc_token: xoxc,+ xoxd_token: xoxd,+ });+ }+ }+ } catch {}+ }++ // 2. Shell env (live process)+ const envXoxc =+ process.env.SLACK_MCP_XOXC_TOKEN || process.env.SLACK_BOT_TOKEN;+ const envXoxd = process.env.SLACK_MCP_XOXD_TOKEN;+ if (envXoxc?.startsWith("xoxc-") && envXoxd?.startsWith("xoxd-")) {+ sources.push({+ source: "process.env",+ xoxc_token: envXoxc,+ xoxd_token: envXoxd,+ });+ }++ // 3. macOS keychain (generic password items named slack-xoxc / slack-xoxd)+ if (process.platform === "darwin") {+ try {+ const xoxc = execSync(+ `security find-generic-password -s slack-xoxc -w 2>/dev/null`,+ { encoding: "utf8" },+ ).trim();+ const xoxd = execSync(+ `security find-generic-password -s slack-xoxd -w 2>/dev/null`,+ { encoding: "utf8" },+ ).trim();+ if (xoxc?.startsWith("xoxc-") && xoxd?.startsWith("xoxd-")) {+ sources.push({+ source: "keychain",+ xoxc_token: xoxc,+ xoxd_token: xoxd,+ });+ }+ } catch {}+ }++ // 4. Shell profile files+ const profiles = [".zshrc", ".bashrc", ".zprofile", ".envrc"].map((f) =>+ join(homedir(), f),+ );+ for (const path of profiles) {+ if (!existsSync(path)) continue;+ try {+ const text = readFileSync(path, "utf8");+ const xoxcMatch = text.match(+ /SLACK(?:_MCP)?_XOXC_TOKEN=["']?(xoxc-[^"'\s]+)/,+ );+ const xoxdMatch = text.match(+ /SLACK(?:_MCP)?_XOXD_TOKEN=["']?(xoxd-[^"'\s]+)/,+ );+ if (xoxcMatch && xoxdMatch) {+ sources.push({+ source: path,+ xoxc_token: xoxcMatch[1],+ xoxd_token: xoxdMatch[1],+ });+ }+ } catch {}+ }++ // 5. Doppler (if configured; cheap probe)+ try {+ const dopRaw = execSync(`doppler secrets --json 2>/dev/null`, {+ encoding: "utf8",+ });+ const dop = JSON.parse(dopRaw);+ const xoxc =+ dop?.SLACK_MCP_XOXC_TOKEN?.computed || dop?.SLACK_BOT_TOKEN?.computed;+ const xoxd = dop?.SLACK_MCP_XOXD_TOKEN?.computed;+ if (xoxc?.startsWith("xoxc-") && xoxd?.startsWith("xoxd-")) {+ sources.push({ source: "doppler", xoxc_token: xoxc, xoxd_token: xoxd });+ }+ } catch {}++ return sources;+}++const scouted = scoutSources();+for (const s of scouted) {+ emit({+ type: "found",+ source: s.source,+ xoxc_preview: s.xoxc_token.slice(0, 10) + "..." + s.xoxc_token.slice(-4),+ xoxd_preview: s.xoxd_token.slice(0, 10) + "..." + s.xoxd_token.slice(-4),+ });+}++if (scouted.length > 0) {+ // Deduplicate: if multiple sources have the same value, prefer highest-priority+ const first = scouted[0];+ // Try to get team_id from ~/.claude.json too, if available+ let teamId = null;+ const claudeJson = join(homedir(), ".claude.json");+ if (existsSync(claudeJson)) {+ try {+ const parsed = JSON.parse(readFileSync(claudeJson, "utf8"));+ teamId = parsed?.mcpServers?.slack?.env?.SLACK_MCP_TEAM_ID || null;+ } catch {}+ }+ process.stdout.write(+ JSON.stringify({+ xoxc_token: first.xoxc_token,+ xoxd_token: first.xoxd_token,+ team_id: teamId,+ source: `scout:${first.source}`,+ }) + "\n",+ );+ process.exit(0);+}++if (SCOUT_ONLY) {+ die("no existing Slack tokens found in any scouted location (--scout-only)");+}++// --- Phase 2: Playwright-based extraction ---+// Scan installed browsers for an existing Slack session cookie, then launch+// Playwright with those cookies pre-injected so no manual login is needed.+emit({+ type: "phase",+ phase: 2,+ message: "No scouted tokens — scanning browsers for Slack session",+});++import { tmpdir } from "node:os";+import { cpSync, readdirSync } from "node:fs";++/**+ * Detect installed browser profiles that might contain Slack cookies.+ * Returns [{name, cookieDb, localStorageDir, userDataDir}] sorted by preference.+ */+function detectBrowserProfiles() {+ const home = homedir();+ const appSupport = join(home, "Library", "Application Support");++ // --- Chromium-based browsers (standard profile layout) ---+ const chromiumCandidates = [+ { name: "Google Chrome", dir: join(appSupport, "Google", "Chrome") },+ {+ name: "Google Chrome Beta",+ dir: join(appSupport, "Google", "Chrome Beta"),+ },+ { name: "Arc", dir: join(appSupport, "Arc", "User Data") },+ { name: "Brave", dir: join(appSupport, "BraveSoftware", "Brave-Browser") },+ { name: "Microsoft Edge", dir: join(appSupport, "Microsoft Edge") },+ { name: "Chromium", dir: join(appSupport, "Chromium") },+ { name: "Opera", dir: join(appSupport, "com.operasoftware.Opera") },+ { name: "Comet", dir: join(appSupport, "Comet") },+ { name: "Vivaldi", dir: join(appSupport, "Vivaldi") },+ { name: "Orion", dir: join(appSupport, "Orion") },+ ];++ const found = [];+ for (const { name, dir } of chromiumCandidates) {+ const profiles = ["Default"];+ try {+ const entries = readdirSync(dir);+ for (const e of entries) {+ if (/^Profile \d+$/.test(e)) profiles.push(e);+ }+ } catch {+ continue;+ }++ for (const profile of profiles) {+ const cookieDb = join(dir, profile, "Cookies");+ const localStorageDir = join(dir, profile, "Local Storage", "leveldb");+ if (existsSync(cookieDb)) {+ found.push({+ name: `${name}/${profile}`,+ cookieDb,+ localStorageDir,+ userDataDir: dir,+ profile,+ });+ }+ }+ }++ // --- Slack desktop app (Electron, macOS sandboxed container) ---+ const slackDesktopPaths = [+ // Mac App Store version (sandboxed)+ join(+ home,+ "Library",+ "Containers",+ "com.tinyspeck.slackmacgap",+ "Data",+ "Library",+ "Application Support",+ "Slack",+ ),+ // Direct download version (non-sandboxed)+ join(appSupport, "Slack"),+ ];+ for (const slackDir of slackDesktopPaths) {+ const cookieDb = join(slackDir, "Cookies");+ const localStorageDir = join(slackDir, "Local Storage", "leveldb");+ if (existsSync(cookieDb)) {+ found.unshift({+ name: "Slack Desktop",+ cookieDb,+ localStorageDir,+ userDataDir: slackDir,+ profile: ".",+ });+ }+ }++ // --- Firefox (SQLite cookies.sqlite, different schema) ---+ const firefoxDir = join(+ home,+ "Library",+ "Application Support",+ "Firefox",+ "Profiles",+ );+ try {+ const profiles = readdirSync(firefoxDir);+ for (const p of profiles) {+ const cookieDb = join(firefoxDir, p, "cookies.sqlite");+ if (existsSync(cookieDb)) {+ found.push({+ name: `Firefox/${p}`,+ cookieDb,+ localStorageDir: null,+ userDataDir: join(firefoxDir, p),+ profile: p,+ isFirefox: true,+ });+ }+ }+ } catch {}++ // --- Safari (Cookies.binarycookies — binary format, check presence only) ---+ const safariCookies = join(+ home,+ "Library",+ "Cookies",+ "Cookies.binarycookies",+ );+ if (existsSync(safariCookies)) {+ found.push({+ name: "Safari",+ cookieDb: safariCookies,+ localStorageDir: null,+ userDataDir: null,+ profile: ".",+ isSafari: true,+ });+ }++ return found;+}++/**+ * Query a cookie DB for the Slack 'd' cookie. Handles:+ * - Chromium/Electron SQLite (encrypted_value in 'cookies' table)+ * - Firefox SQLite (value in 'moz_cookies' table, unencrypted)+ * - Safari binary cookies (presence check only via file scan)+ * Returns the browser name if found, null otherwise.+ */+function querySlackCookieFromDb(cookieDb, browserName, opts = {}) {+ try {+ if (opts.isSafari) {+ // Safari uses Cookies.binarycookies — binary format. Check with strings.+ const result = execSync(+ `strings "${cookieDb}" 2>/dev/null | grep -c "slack.com"`,+ { encoding: "utf8", timeout: 5000 },+ ).trim();+ return parseInt(result, 10) > 0 ? browserName : null;+ }++ if (opts.isFirefox) {+ // Firefox uses moz_cookies table with plaintext values+ const checkResult = execSync(+ `sqlite3 "${cookieDb}" "SELECT length(value) FROM moz_cookies WHERE host LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,+ { encoding: "utf8", timeout: 5000 },+ ).trim();+ return checkResult && parseInt(checkResult, 10) > 0 ? browserName : null;+ }++ // Chromium / Electron — encrypted_value in 'cookies' table+ const checkResult = execSync(+ `sqlite3 "${cookieDb}" "SELECT length(encrypted_value) FROM cookies WHERE host_key LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,+ { encoding: "utf8", timeout: 5000 },+ ).trim();+ return checkResult && parseInt(checkResult, 10) > 0 ? browserName : null;+ } catch {+ return null;+ }+}++const browserProfiles = detectBrowserProfiles();+emit({+ type: "step",+ message: `Found ${browserProfiles.length} browser profile(s) to scan`,+});++let selectedBrowser = null;+for (const bp of browserProfiles) {+ const hasSlack = querySlackCookieFromDb(bp.cookieDb, bp.name, {+ isFirefox: bp.isFirefox,+ isSafari: bp.isSafari,+ });+ if (hasSlack) {+ emit({ type: "step", message: `✓ ${bp.name} has Slack cookies` });+ selectedBrowser = bp;+ break;+ } else {+ emit({ type: "step", message: `○ ${bp.name} — no Slack cookies` });+ }+}++// --- Direct cookie decryption (no Playwright needed for extraction) ---+import { createHash, pbkdf2Sync, createDecipheriv } from "node:crypto";++/**+ * Decrypt a Chromium encrypted cookie value on macOS.+ * Each Chromium app stores its key in the keychain as "<AppName> Safe Storage".+ * Encryption: PBKDF2(key, "saltysalt", 1003, 16) → AES-128-CBC with IV=16 spaces.+ * Encrypted values start with "v10" (3-byte prefix).+ */+function decryptChromiumCookie(encryptedHex, keychainService) {+ try {+ const masterKey = execSync(+ `security find-generic-password -w -s "${keychainService}" 2>/dev/null`,+ { encoding: "utf8" },+ ).trim();+ if (!masterKey) return null;++ const derivedKey = pbkdf2Sync(masterKey, "saltysalt", 1003, 16, "sha1");+ const encrypted = Buffer.from(encryptedHex, "hex");++ // Strip "v10" prefix (3 bytes)+ if (encrypted.length < 4) return null;+ const prefix = encrypted.slice(0, 3).toString("ascii");+ if (prefix !== "v10") return null;+ const ciphertext = encrypted.slice(3);++ const iv = Buffer.alloc(16, " ");+ const decipher = createDecipheriv("aes-128-cbc", derivedKey, iv);+ decipher.setAutoPadding(false);+ let decrypted = decipher.update(ciphertext);+ decrypted = Buffer.concat([decrypted, decipher.final()]);++ // Remove PKCS7 padding manually+ const padLen = decrypted[decrypted.length - 1];+ if (padLen > 0 && padLen <= 16) {+ decrypted = decrypted.slice(0, decrypted.length - padLen);+ }++ // Chrome v130+ prepends a 32-byte SHA256 domain hash before the value.+ // The real cookie value is URL-encoded ASCII text.+ const raw = decrypted.toString("latin1");+ // The 'd' cookie value is URL-encoded (contains %2B, %2F, %3D etc.)+ // Find the longest URL-encoded chunk — that's the real value.+ const allMatches = [...raw.matchAll(/[A-Za-z0-9%+/=_-]{30,}/g)];+ if (allMatches.length > 0) {+ // Pick the longest match (the domain hash is 32 bytes of binary, not ASCII)+ return allMatches.sort((a, b) => b[0].length - a[0].length)[0][0];+ }+ return raw;+ } catch {+ return null;+ }+}++/**+ * Map browser name to its keychain Safe Storage service name.+ */+function keychainServiceFor(browserName) {+ const name = browserName.split("/")[0]; // strip "/Default" etc.+ const map = {+ "Google Chrome": "Chrome Safe Storage",+ "Google Chrome Beta": "Chrome Beta Safe Storage",+ Comet: "Comet Safe Storage",+ Arc: "Arc Safe Storage",+ Brave: "Brave Safe Storage",+ "Microsoft Edge": "Microsoft Edge Safe Storage",+ Chromium: "Chromium Safe Storage",+ Opera: "Opera Safe Storage",+ Vivaldi: "Vivaldi Safe Storage",+ Orion: "Orion Safe Storage",+ "Slack Desktop": "Slack Safe Storage",+ };+ return map[name] || `${name} Safe Storage`;+}++/**+ * Extract the xoxc token from a Chromium localStorage leveldb.+ * Uses classic-level for proper LevelDB reading (raw file scanning+ * breaks on LevelDB's internal binary framing).+ * Falls back to raw file scanning if classic-level is unavailable.+ */+async function extractXoxcFromLocalStorage(localStorageDir) {+ if (!localStorageDir || !existsSync(localStorageDir)) return null;++ // Try proper LevelDB reading first+ try {+ const { ClassicLevel } = await import("classic-level");+ // Copy to temp to avoid lock conflicts with running browser+ const tmpCopy = join(tmpdir(), `ops-slack-ls-${Date.now()}`);+ cpSync(localStorageDir, tmpCopy, { recursive: true });+ // Remove LOCK file so we can open read-only+ try {+ unlinkSync(join(tmpCopy, "LOCK"));+ } catch {}++ const db = new ClassicLevel(tmpCopy, {+ createIfMissing: false,+ valueEncoding: "utf8",+ keyEncoding: "utf8",+ });+ await db.open({ readOnly: true });++ let token = null;+ for await (const [, value] of db.iterator()) {+ if (value && value.includes("xoxc-")) {+ const m = value.match(/xoxc-[0-9a-zA-Z._-]+/);+ if (m && m[0].length > 20) {+ token = m[0];+ break;+ }+ }+ }+ await db.close();+ // Clean up temp copy+ try {+ execSync(`rm -rf "${tmpCopy}"`, { timeout: 5000 });+ } catch {}+ if (token) return token;+ } catch {}++ // Fallback: raw file scanning (less reliable due to LevelDB binary framing)+ try {+ const files = readdirSync(localStorageDir).filter(+ (f) => f.endsWith(".ldb") || f.endsWith(".log"),+ );+ for (const f of files) {+ try {+ const data = readFileSync(join(localStorageDir, f));+ const text = data.toString("latin1");+ const match = text.match(/xoxc-[0-9A-Za-z._-]+/);+ if (match && match[0].length > 20) return match[0];+ } catch {}+ }+ } catch {}+ return null;+}++// --- Try direct extraction if we found a browser with cookies ---+if (selectedBrowser && !selectedBrowser.isSafari) {+ emit({+ type: "step",+ message: `Attempting direct cookie decryption from ${selectedBrowser.name}`,+ });++ const keychainSvc = keychainServiceFor(selectedBrowser.name);++ // Extract and decrypt the 'd' cookie+ let xoxdToken = null;+ if (selectedBrowser.isFirefox) {+ // Firefox cookies are plaintext+ try {+ xoxdToken = execSync(+ `sqlite3 "${selectedBrowser.cookieDb}" "SELECT value FROM moz_cookies WHERE host LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,+ { encoding: "utf8", timeout: 5000 },+ ).trim();+ } catch {}+ } else {+ // Chromium — read encrypted value as hex, decrypt+ try {+ const hexValue = execSync(+ `sqlite3 "${selectedBrowser.cookieDb}" "SELECT hex(encrypted_value) FROM cookies WHERE host_key LIKE '%.slack.com' AND name = 'd' LIMIT 1;" 2>/dev/null`,+ { encoding: "utf8", timeout: 5000 },+ ).trim();+ if (hexValue) {+ xoxdToken = decryptChromiumCookie(hexValue, keychainSvc);+ }+ } catch {}+ }++ if (xoxdToken) {+ // Clean up: if decrypted value contains an embedded xoxd-, extract from there+ const xoxdIdx = xoxdToken.lastIndexOf("xoxd-");+ if (xoxdIdx > 0) {+ xoxdToken = xoxdToken.slice(xoxdIdx);+ } else if (!xoxdToken.startsWith("xoxd-")) {+ xoxdToken = `xoxd-${xoxdToken}`;+ }+ emit({+ type: "step",+ message: `✓ Decrypted 'd' cookie (${xoxdToken.slice(0, 10)}...${xoxdToken.slice(-4)})`,+ });++ // Extract xoxc from localStorage+ const xoxcToken = await extractXoxcFromLocalStorage(+ selectedBrowser.localStorageDir,+ );+ if (xoxcToken) {+ emit({+ type: "step",+ message: `✓ Found xoxc token from localStorage (${xoxcToken.slice(0, 10)}...${xoxcToken.slice(-4)})`,+ });++ // Extract team ID from localStorage or xoxc pattern+ let teamId = null;+ if (selectedBrowser.localStorageDir) {+ try {+ const files = readdirSync(selectedBrowser.localStorageDir).filter(+ (f) => f.endsWith(".ldb") || f.endsWith(".log"),+ );+ for (const f of files) {+ try {+ const data = readFileSync(+ join(selectedBrowser.localStorageDir, f),+ "latin1",+ );+ const m = data.match(/"team_id"\s*:\s*"(T[A-Z0-9]+)"/);+ if (m) {+ teamId = m[1];+ break;+ }+ } catch {}+ }+ } catch {}+ }++ // Validate tokens against Slack API+ emit({ type: "step", message: "Validating tokens against Slack API..." });+ let authResult = null;+ try {+ const res = await fetch("https://slack.com/api/auth.test", {+ headers: {+ Authorization: `Bearer ${xoxcToken}`,+ Cookie: `d=${xoxdToken}`,+ },+ });+ authResult = await res.json();+ } catch {}++ if (authResult?.ok) {+ teamId = authResult.team_id || teamId;+ emit({+ type: "step",+ message: `✓ Validated — ${authResult.url} (${authResult.team_id})`,+ });+ } else {+ emit({+ type: "step",+ message: `⚠ Validation failed: ${authResult?.error || "unknown"} — tokens may be stale`,+ });+ }++ // Persist to keychain+ if (process.platform === "darwin") {+ try {+ execSync(+ `security add-generic-password -U -s slack-xoxc -a "$USER" -w '${xoxcToken.replace(/'/g, "'\\''")}'`,+ { timeout: 5000 },+ );+ execSync(+ `security add-generic-password -U -s slack-xoxd -a "$USER" -w '${xoxdToken.replace(/'/g, "'\\''")}'`,+ { timeout: 5000 },+ );+ emit({ type: "step", message: "✓ Saved tokens to macOS keychain" });+ } catch (e) {+ emit({+ type: "step",+ message: `○ Keychain save failed: ${e.message}`,+ });+ }+ }++ // Register Slack MCP server in Claude Code (fully automated)+ try {+ execSync(+ `claude mcp add slack -s user -e SLACK_XOXC_TOKEN='${xoxcToken.replace(/'/g, "'\\''")}'` ++ ` -e SLACK_XOXD_TOKEN='${xoxdToken.replace(/'/g, "'\\''")}'` ++ ` -- npx -y @anthropic-ai/slack-mcp@latest`,+ { timeout: 15000, stdio: "pipe" },+ );+ emit({+ type: "step",+ message: "✓ Registered Slack MCP server in Claude Code",+ });+ } catch {+ emit({+ type: "step",+ message: "○ Could not auto-register MCP — run: claude mcp add slack",+ });+ }++ // Success — emit result+ process.stdout.write(+ JSON.stringify({+ xoxc_token: xoxcToken,+ xoxd_token: xoxdToken,+ team_id: teamId,+ source: `direct:${selectedBrowser.name}`,+ }) + "\n",+ );+ process.exit(0);+ } else {+ emit({+ type: "step",+ message: `○ Could not find xoxc in localStorage — falling back to Playwright`,+ });+ }+ } else {+ emit({+ type: "step",+ message: `○ Could not decrypt cookie from ${selectedBrowser.name} — falling back to Playwright`,+ });+ }+}++// --- Playwright fallback (only if direct extraction failed) ---+let chromium;+try {+ ({ chromium } = await import("playwright"));+} catch {+ die(+ "playwright is not installed and direct cookie extraction failed. Run `npm install playwright` in the plugin root and `npx playwright install chromium`.",+ );+}++mkdirSync(PROFILE_DIR, { recursive: true });+emit({+ type: "step",+ message: `Launching Chromium (headless=${HEADLESS}, profile=${PROFILE_DIR})`,+});++const context = await chromium.launchPersistentContext(PROFILE_DIR, {+ headless: HEADLESS,+ args: [+ "--disable-blink-features=AutomationControlled",+ "--no-first-run",+ "--no-default-browser-check",+ ],+ viewport: { width: 1280, height: 800 },+});++const page = context.pages()[0] || (await context.newPage());++try {+ emit({ type: "step", message: `Navigating to ${WORKSPACE_VALIDATED}` });+ await page.goto(WORKSPACE_VALIDATED);+ try {+ await page.waitForLoadState("networkidle", { timeout: 30_000 });+ } catch {}++ const currentUrl = page.url();+ if (/signin|sign_in|ssb\/signin/i.test(currentUrl)) {+ if (HEADLESS) {+ die(+ "Not logged in and running headless. Run without --headless first to establish a session in the profile dir.",+ );+ }+ emit({+ type: "need_login",+ message:+ "Log in to Slack in the open Chromium window, then touch the ready-file to continue",+ ready_file: READY_FILE,+ });+ // Wait for the caller to touch READY_FILE once the user finishes login+ const start = Date.now();+ while (Date.now() - start < 300_000) {+ if (existsSync(READY_FILE)) break;+ await new Promise((r) => setTimeout(r, 2000));+ }+ if (!existsSync(READY_FILE)) die("timeout waiting for login completion");+ try {+ await page.waitForURL(/\/client\//, { timeout: 15_000 });+ } catch {}+ try {+ await page.waitForLoadState("networkidle", { timeout: 30_000 });+ } catch {}+ }++ // Extract team ID+ let teamId = null;+ const urlMatch = page.url().match(/\/client\/([A-Z0-9]+)/);+ if (urlMatch) teamId = urlMatch[1];+ if (!teamId) {+ teamId = await page.evaluate(() => {+ try {+ const cfg = JSON.parse(localStorage.localConfig_v2 || "{}");+ return Object.keys(cfg.teams || {})[0] || null;+ } catch {+ return null;+ }+ });+ }+ if (!teamId)+ die(+ "Could not determine Slack team ID — make sure you're viewing a workspace",+ );+ emit({ type: "step", message: `Found team_id=${teamId}` });++ // Extract XOXC from localStorage+ let xoxcToken = await page.evaluate((tid) => {+ try {+ const cfg = JSON.parse(localStorage.localConfig_v2 || "{}");+ if (cfg.teams?.[tid]?.token) return cfg.teams[tid].token;+ for (const [, data] of Object.entries(cfg.teams || {})) {+ if (data?.token?.startsWith("xoxc-")) return data.token;+ }+ return null;+ } catch {+ return null;+ }+ }, teamId);+ if (!xoxcToken) {+ // fallback: regex scan of inline JS+ xoxcToken = await page.evaluate(() => {+ const m = document.body.innerHTML.match(/"token":"(xoxc-[^"]+)"/);+ return m ? m[1] : null;+ });+ }+ if (!xoxcToken)+ die("Could not find XOXC token — ensure the workspace is fully loaded");++ // Extract XOXD ('d' cookie) from the context cookie jar+ const cookies = await context.cookies();+ const dCookie = cookies.find(+ (c) => c.name === "d" && /slack\.com/.test(c.domain),+ );+ if (!dCookie) die("Could not find 'd' cookie (XOXD token)");+ const xoxdToken = dCookie.value.startsWith("xoxd-")+ ? dCookie.value+ : `xoxd-${dCookie.value}`;++ await context.close();++ process.stdout.write(+ JSON.stringify({+ xoxc_token: xoxcToken,+ xoxd_token: xoxdToken,+ team_id: teamId,+ source: "playwright",+ }) + "\n",+ );+ process.exit(0);+} catch (err) {+ try {+ await context.close();+ } catch {}+ die(`playwright extraction failed: ${err.message}`);+}diff --git a/claude-ops/bin/ops-speedup b/claude-ops/bin/ops-speedupnew file mode 100755index 00000000..5a22a5f1--- /dev/null+++ b/claude-ops/bin/ops-speedup@@ -0,0 +1,176 @@+#!/usr/bin/env bash+# ops-speedup — Cross-platform system scan & cleanup report+# Auto-detects OS (macOS/Linux/WSL) and outputs JSON diagnostic data+set -euo pipefail++# --- Color setup ---+if [[ -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then+ RST=$'\033[0m'; DIM=$'\033[2m'; CYN=$'\033[36m'; BCYN=$'\033[1;36m'; BWHT=$'\033[1;37m'+ GRN=$'\033[32m'; BGRN=$'\033[1;32m'; RED=$'\033[31m'; BRED=$'\033[1;31m'; YLW=$'\033[33m'+else+ RST="" DIM="" CYN="" BCYN="" BWHT="" GRN="" BGRN="" RED="" BRED="" YLW=""+fi++# --- OS Detection ---+OS="unknown"+DISTRO=""+case "$(uname -s)" in+ Darwin) OS="macos" ;;+ Linux)+ if grep -qi microsoft /proc/version 2>/dev/null; then+ OS="wsl"+ else+ OS="linux"+ fi+ if [ -f /etc/os-release ]; then+ DISTRO=$(. /etc/os-release && echo "${ID:-unknown}")+ fi+ ;;+ MINGW*|MSYS*|CYGWIN*) OS="windows" ;;+esac++# --- Hardware ---+if [ "$OS" = "macos" ]; then+ CPU=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo "unknown")+ RAM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || echo "0")+ RAM_GB=$(( RAM_BYTES / 1073741824 ))+ CHIP=$(sysctl -n machdep.cpu.brand_string 2>/dev/null | grep -qi "apple" && echo "apple_silicon" || echo "intel")+ DISK_TOTAL=$(df -g / 2>/dev/null | awk 'NR==2{print $2}' || echo "?")+ DISK_AVAIL=$(df -g / 2>/dev/null | awk 'NR==2{print $4}' || echo "?")+ DISK_USED_PCT=$(df -g / 2>/dev/null | awk 'NR==2{gsub(/%/,"",$5); print $5}' || echo "?")+ MACOS_VER=$(sw_vers -productVersion 2>/dev/null || echo "?")+else+ CPU=$(grep -m1 "model name" /proc/cpuinfo 2>/dev/null | cut -d: -f2 | xargs || echo "unknown")+ RAM_KB=$(grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0")+ RAM_GB=$(( RAM_KB / 1048576 ))+ CHIP="x86_64"+ [ "$(uname -m)" = "aarch64" ] && CHIP="arm64"+ DISK_TOTAL=$(df -BG / 2>/dev/null | awk 'NR==2{gsub(/G/,"",$2); print $2}' || echo "?")+ DISK_AVAIL=$(df -BG / 2>/dev/null | awk 'NR==2{gsub(/G/,"",$4); print $4}' || echo "?")+ DISK_USED_PCT=$(df / 2>/dev/null | awk 'NR==2{gsub(/%/,"",$5); print $5}' || echo "?")+ MACOS_VER=""+fi++# --- Render header ---+printf '\n'+printf ' %s%s╔══════════════════════════════════════════════════════════════╗%s\n' "$DIM" "$CYN" "$RST"+printf ' %s%s║%s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$DIM" "$CYN" "$RST"+printf ' %s%s║%s %sSYSTEM SPEEDUP%s %s%-47s%s%s║%s\n' "$DIM" "$CYN" "$RST" "$BWHT" "$RST" "$DIM" "$OS | $(uname -m)" "$RST" "$DIM$CYN" "$RST"+printf ' %s%s║%s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$DIM" "$CYN" "$RST"+printf ' %s%s╠══════════════════════════════════════════════════════════════╣%s\n' "$DIM" "$CYN" "$RST"+printf ' %s%s║%s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$DIM" "$CYN" "$RST"++# --- System info ---+if [ "$OS" = "macos" ]; then+ printf ' %s%s║%s %sCPU%s %-55s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$BCYN" "$RST" "$CPU" "$DIM" "$CYN" "$RST"+ printf ' %s%s║%s %sRAM%s %sGB %sDisk%s %sGB / %sGB (%s%%%s used)%s %s%s║%s\n' \+ "$DIM" "$CYN" "$RST" "$BCYN" "$RST" "$RAM_GB" "$BCYN" "$RST" "$DISK_AVAIL" "$DISK_TOTAL" "$DISK_USED_PCT" "" "$RST" "$DIM" "$CYN" "$RST"+ printf ' %s%s║%s %smacOS%s %-53s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$BCYN" "$RST" "$MACOS_VER" "$DIM" "$CYN" "$RST"+else+ printf ' %s%s║%s %sCPU%s %-55s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$BCYN" "$RST" "$CPU" "$DIM" "$CYN" "$RST"+ printf ' %s%s║%s %sRAM%s %sGB %sDisk%s %sGB / %sGB (%s%%%s used)%s %s%s║%s\n' \+ "$DIM" "$CYN" "$RST" "$BCYN" "$RST" "$RAM_GB" "$BCYN" "$RST" "$DISK_AVAIL" "$DISK_TOTAL" "$DISK_USED_PCT" "" "$RST" "$DIM" "$CYN" "$RST"+fi++printf ' %s%s║%s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$DIM" "$CYN" "$RST"+printf ' %s%s╠══════════════════════════════════════════════════════════════╣%s\n' "$DIM" "$CYN" "$RST"+printf ' %s%s║%s %sSCANNING...%s %s%s║%s\n' "$DIM" "$CYN" "$RST" "$YLW" "$RST" "$DIM" "$CYN" "$RST"+printf ' %s%s╚══════════════════════════════════════════════════════════════╝%s\n' "$DIM" "$CYN" "$RST"+printf '\n'++# --- Output JSON diagnostic data for the skill to consume ---+# This goes to a separate fd so the visual banner and JSON don't mix+# The skill reads this via a second invocation with --json flag+if [ "${1:-}" = "--json" ]; then+ # Collect reclaimable data+ BREW_CACHE="0"+ NPM_CACHE="0"+ DOCKER_RECLAIMABLE="0"+ XCODE_DERIVED="0"+ TRASH_SIZE="0"+ LOG_SIZE="0"+ DOWNLOADS_SIZE="0"+ TMP_SIZE="0"++ if [ "$OS" = "macos" ]; then+ BREW_CACHE=$(du -sm "$(brew --cache 2>/dev/null)" 2>/dev/null | awk '{print $1}' || echo "0")+ NPM_CACHE=$(du -sm "$HOME/.npm/_cacache" 2>/dev/null | awk '{print $1}' || echo "0")+ XCODE_DERIVED=$(du -sm "$HOME/Library/Developer/Xcode/DerivedData" 2>/dev/null | awk '{print $1}' || echo "0")+ TRASH_SIZE=$(du -sm "$HOME/.Trash" 2>/dev/null | awk '{print $1}' || echo "0")+ LOG_SIZE=$(du -sm "$HOME/Library/Logs" 2>/dev/null | awk '{print $1}' || echo "0")+ DOWNLOADS_SIZE=$(du -sm "$HOME/Downloads" 2>/dev/null | awk '{print $1}' || echo "0")+ TMP_SIZE=$(du -sm /tmp 2>/dev/null | awk '{print $1}' || echo "0")+ DOCKER_RECLAIMABLE=$(docker system df --format '{{.Reclaimable}}' 2>/dev/null | head -1 | grep -oE '[0-9]+' || echo "0")+ else+ NPM_CACHE=$(du -sm "$HOME/.npm/_cacache" 2>/dev/null | awk '{print $1}' || echo "0")+ TRASH_SIZE=$(du -sm "$HOME/.local/share/Trash" 2>/dev/null | awk '{print $1}' || echo "0")+ LOG_SIZE=$(du -sm /var/log 2>/dev/null | awk '{print $1}' || echo "0")+ TMP_SIZE=$(du -sm /tmp 2>/dev/null | awk '{print $1}' || echo "0")+ DOCKER_RECLAIMABLE=$(docker system df --format '{{.Reclaimable}}' 2>/dev/null | head -1 | grep -oE '[0-9]+' || echo "0")+ fi++ # Memory pressure+ if [ "$OS" = "macos" ]; then+ MEM_PRESSURE=$(memory_pressure 2>/dev/null | grep "System-wide memory free percentage" | grep -oE '[0-9]+' || echo "?")+ SWAP_USED=$(sysctl -n vm.swapusage 2>/dev/null | grep -oE 'used = [0-9.]+' | grep -oE '[0-9.]+' || echo "0")+ else+ MEM_AVAIL=$(grep MemAvailable /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0")+ MEM_TOTAL=$(grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "1")+ MEM_PRESSURE=$(( (MEM_TOTAL - MEM_AVAIL) * 100 / MEM_TOTAL ))+ SWAP_USED=$(grep SwapTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0")+ fi++ # Process count & top consumers+ PROC_COUNT=$(ps aux 2>/dev/null | wc -l | tr -d ' ')+ TOP_CPU=$(ps aux --sort=-%cpu 2>/dev/null | head -6 | tail -5 || ps aux -r 2>/dev/null | head -6 | tail -5 || echo "unavailable")+ TOP_MEM=$(ps aux --sort=-%mem 2>/dev/null | head -6 | tail -5 || ps aux -m 2>/dev/null | head -6 | tail -5 || echo "unavailable")++ # DNS response time+ DNS_TIME=$(dig google.com +time=3 +tries=1 2>/dev/null | grep "Query time" | grep -oE '[0-9]+' || echo "?")++ # Startup items (macOS)+ LOGIN_ITEMS="0"+ LAUNCH_AGENTS="0"+ if [ "$OS" = "macos" ]; then+ LOGIN_ITEMS=$(osascript -e 'tell application "System Events" to count of login items' 2>/dev/null || echo "?")+ LAUNCH_AGENTS=$(ls ~/Library/LaunchAgents/ 2>/dev/null | wc -l | tr -d ' ')+ fi++ cat <<ENDJSON+{+ "os": "$OS",+ "distro": "$DISTRO",+ "chip": "$CHIP",+ "cpu": "$CPU",+ "ram_gb": $RAM_GB,+ "disk_total_gb": "${DISK_TOTAL}",+ "disk_avail_gb": "${DISK_AVAIL}",+ "disk_used_pct": "${DISK_USED_PCT}",+ "macos_version": "$MACOS_VER",+ "reclaimable_mb": {+ "brew_cache": $BREW_CACHE,+ "npm_cache": $NPM_CACHE,+ "xcode_derived": $XCODE_DERIVED,+ "docker": $DOCKER_RECLAIMABLE,+ "trash": $TRASH_SIZE,+ "logs": $LOG_SIZE,+ "downloads": $DOWNLOADS_SIZE,+ "tmp": $TMP_SIZE+ },+ "memory": {+ "pressure_pct": "$MEM_PRESSURE",+ "swap_used_mb": "$SWAP_USED"+ },+ "processes": {+ "count": $PROC_COUNT+ },+ "network": {+ "dns_ms": "$DNS_TIME"+ },+ "startup": {+ "login_items": "$LOGIN_ITEMS",+ "launch_agents": $LAUNCH_AGENTS+ }+}+ENDJSON+fidiff --git a/claude-ops/bin/ops-telegram-autolink.mjs b/claude-ops/bin/ops-telegram-autolink.mjsnew file mode 100755index 00000000..6b13f025--- /dev/null+++ b/claude-ops/bin/ops-telegram-autolink.mjs@@ -0,0 +1,432 @@+#!/usr/bin/env node+/**+ * ops-telegram-autolink — extract api_id / api_hash from my.telegram.org+ * and generate a gram.js session string, producing a ready-to-paste+ * user_config block for the claude-ops plugin's Telegram MCP.+ *+ * NO BROWSER required. my.telegram.org uses plain HTML form posts + session+ * cookies, so this works over pure HTTP. Much simpler and faster than the+ * Playwright approach.+ *+ * Usage:+ * ops-telegram-autolink --phone +15551234567 [options]+ *+ * Options:+ * --phone E.164 phone number (required)+ * --app-title Label for the Telegram app entry (default: "claude-ops")+ * --app-short Short name for the app entry (default: "claude_ops")+ * --skip-session Skip gram.js session generation (only extract api_id/hash)+ * --code-file File path to read codes from (default: /tmp/telegram-code.txt)+ *+ * Bridge protocol:+ * Progress/prompts → stderr as single-line JSON events:+ * {"type": "phase", ...}+ * {"type": "step", ...}+ * {"type": "need_code", "channel": "web_login" | "gram_auth", ...}+ * {"type": "error", "message": "..."}+ * Final result → stdout as single-line JSON:+ * {"api_id": "...", "api_hash": "...", "phone": "...", "session": "..."}+ *+ * When the caller sees a need_code event, it should prompt the user for+ * the code from Telegram and write it (digits only) to the file in+ * --code-file. The script polls the file every 2s, unlinks it after read.+ *+ * Depends on: telegram (gram.js). No cheerio — selectors are extracted via+ * simple regex to keep the dep footprint minimal.+ */++import { readFileSync, existsSync, unlinkSync } from "node:fs";+import { execSync } from "node:child_process";+import { parseArgs } from "node:util";+import { TelegramClient } from "telegram";+import { StringSession } from "telegram/sessions/index.js";++const { values } = parseArgs({+ options: {+ phone: { type: "string" },+ "app-title": { type: "string", default: "claude-ops" },+ "app-short": { type: "string", default: "claude_ops" },+ "skip-session": { type: "boolean", default: false },+ "code-file": { type: "string", default: "/tmp/telegram-code.txt" },+ },+});++const PHONE = values.phone;+const APP_TITLE = values["app-title"];+const APP_SHORT = values["app-short"];+const SKIP_SESSION = values["skip-session"];+const CODE_FILE = values["code-file"];++function emit(event) {+ process.stderr.write(JSON.stringify(event) + "\n");+}++function die(message, extra = {}) {+ emit({ type: "error", message, ...extra });+ process.exit(1);+}++if (!PHONE || !/^\+\d{7,15}$/.test(PHONE)) {+ die("missing or invalid --phone (E.164 required, e.g. +15551234567)");+}++if (existsSync(CODE_FILE)) unlinkSync(CODE_FILE);++/**+ * Wait for the bridge file to appear with a valid code, then consume it.+ */+async function waitForCode(maxSec = 300) {+ const start = Date.now();+ let lastLog = 0;+ while (Date.now() - start < maxSec * 1000) {+ if (existsSync(CODE_FILE)) {+ const raw = readFileSync(CODE_FILE, "utf8").trim();+ if (/^[\w]{3,20}$/.test(raw)) {+ try {+ unlinkSync(CODE_FILE);+ } catch {}+ return raw;+ }+ }+ if (Date.now() - lastLog > 15000) {+ emit({+ type: "heartbeat",+ waited_s: Math.floor((Date.now() - start) / 1000),+ });+ lastLog = Date.now();+ }+ await new Promise((r) => setTimeout(r, 2000));+ }+ die(`timeout waiting for code file at ${CODE_FILE}`);+}++/**+ * Simple cookie jar — just enough to keep the my.telegram.org session.+ */+class CookieJar {+ constructor() {+ this.cookies = new Map();+ }+ update(response) {+ const raw = response.headers.getSetCookie+ ? response.headers.getSetCookie()+ : [response.headers.get("set-cookie")].filter(Boolean);+ for (const c of raw || []) {+ const [kv] = c.split(";");+ const eq = kv.indexOf("=");+ if (eq > 0)+ this.cookies.set(kv.slice(0, eq).trim(), kv.slice(eq + 1).trim());+ }+ }+ header() {+ return Array.from(this.cookies.entries())+ .map(([k, v]) => `${k}=${v}`)+ .join("; ");+ }+}++// --- Phase 1: my.telegram.org HTTP flow ---+emit({+ type: "phase",+ phase: 1,+ message: "Extracting api_id / api_hash from my.telegram.org",+});++const jar = new CookieJar();+const COMMON_HEADERS = {+ "User-Agent":+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",+ "Accept-Language": "en-US,en;q=0.9",+};++async function httpPost(url, body) {+ const res = await fetch(url, {+ method: "POST",+ headers: {+ ...COMMON_HEADERS,+ "Content-Type": "application/x-www-form-urlencoded",+ "X-Requested-With": "XMLHttpRequest",+ Cookie: jar.header(),+ Referer: "https://my.telegram.org/auth",+ Origin: "https://my.telegram.org",+ },+ body: new URLSearchParams(body).toString(),+ redirect: "manual",+ });+ jar.update(res);+ return res;+}++async function httpGet(url) {+ const res = await fetch(url, {+ headers: { ...COMMON_HEADERS, Cookie: jar.header() },+ redirect: "manual",+ });+ jar.update(res);+ return res;+}++// Step 1.1: request a login code for PHONE+emit({ type: "step", message: `POST /auth/send_password for ${PHONE}` });+const sendRes = await httpPost("https://my.telegram.org/auth/send_password", {+ phone: PHONE,+});+const sendText = await sendRes.text();+if (sendText.includes("Sorry, too many tries")) {+ die("my.telegram.org rate-limited your account. Wait ~8 hours and retry.");+}+let randomHash;+try {+ const parsed = JSON.parse(sendText);+ randomHash = parsed.random_hash;+ if (!randomHash) throw new Error("no random_hash in response");+} catch (e) {+ die("send_password response was not valid JSON", {+ body: sendText.slice(0, 200),+ });+}+emit({+ type: "step",+ message: "Telegram has sent a code to your Telegram account",+});++// Step 1.2: wait for code from the bridge+emit({+ type: "need_code",+ channel: "web_login",+ message: `Enter the code from Telegram → write it to ${CODE_FILE}`,+ code_file: CODE_FILE,+});+const webCode = await waitForCode(300);++// Step 1.3: POST login with phone + random_hash + password=code+emit({ type: "step", message: "POST /auth/login" });+const loginRes = await httpPost("https://my.telegram.org/auth/login", {+ phone: PHONE,+ random_hash: randomHash,+ password: webCode,+});+const loginBody = await loginRes.text();+if (loginBody && /error|invalid|wrong/i.test(loginBody)) {+ die(`login rejected: ${loginBody.slice(0, 150)}`);+}++// Step 1.4: GET /apps to see if an app already exists+emit({ type: "step", message: "GET /apps" });+let appsRes = await httpGet("https://my.telegram.org/apps");+let appsHtml = await appsRes.text();++// Parse selectors based on esfelurm/Apis-Telegram reference:+// <label>App api_id:</label> ... <div>...<span>12345678</span>...+// Works as long as my.telegram.org keeps its server-side HTML shape.+function extract(html) {+ const idMatch = html.match(+ /App api_id[^<]*<\/label>[\s\S]*?<span[^>]*>\s*(\d{5,12})\s*<\/span>/i,+ );+ const hashMatch = html.match(+ /App api_hash[^<]*<\/label>[\s\S]*?<span[^>]*>\s*([a-f0-9]{32})\s*<\/span>/i,+ );+ // Fallback: plain code tags sometimes used+ const altHash = html.match(/api_hash[^<]*<[^>]+>\s*([a-f0-9]{32})/i);+ return {+ apiId: idMatch ? idMatch[1] : null,+ apiHash: hashMatch ? hashMatch[1] : altHash ? altHash[1] : null,+ };+}++let { apiId, apiHash } = extract(appsHtml);++if (!apiId || !apiHash) {+ // Step 1.5: no app exists → create one+ emit({ type: "step", message: "No existing app — creating one" });+ // Extract CSRF token / hash value from the create-app form if present+ const hashInput = appsHtml.match(+ /name=['"]hash['"]\s+value=['"]([a-z0-9]+)['"]/i,+ );+ const createParams = {+ hash: hashInput ? hashInput[1] : "",+ app_title: APP_TITLE,+ app_shortname: APP_SHORT,+ app_url: "https://github.com/claude-ops-marketplace/claude-ops",+ app_platform: "desktop",+ app_desc: "claude-ops — automated operations for Claude Code",+ };+ const createRes = await httpPost(+ "https://my.telegram.org/apps/create",+ createParams,+ );+ const createBody = await createRes.text();+ if (createRes.status >= 400 || /error/i.test(createBody.slice(0, 200))) {+ die(`/apps/create failed (HTTP ${createRes.status})`, {+ body: createBody.slice(0, 200),+ });+ }+ // Re-fetch the apps page now that an app exists+ appsRes = await httpGet("https://my.telegram.org/apps");+ appsHtml = await appsRes.text();+ ({ apiId, apiHash } = extract(appsHtml));+}++if (!apiId || !apiHash) {+ die(+ "could not extract api_id/api_hash from /apps HTML — selectors may have changed",+ );+}++emit({+ type: "phase",+ phase: 1,+ message: "Extracted credentials",+ api_id: apiId,+});++// --- Phase 2: gram.js session generation ---+if (SKIP_SESSION) {+ process.stdout.write(+ JSON.stringify({+ api_id: apiId,+ api_hash: apiHash,+ phone: PHONE,+ session: null,+ }) + "\n",+ );+ process.exit(0);+}++emit({ type: "phase", phase: 2, message: "Generating gram.js session string" });++const stringSession = new StringSession("");+const client = new TelegramClient(stringSession, parseInt(apiId, 10), apiHash, {+ connectionRetries: 3,+ baseLogger: {+ log: () => {},+ warn: () => {},+ error: (...a) => emit({ type: "gram_error", message: a.join(" ") }),+ info: () => {},+ debug: () => {},+ },+});++// Remove any leftover code file from the web-login step so we don't reuse it+if (existsSync(CODE_FILE)) {+ try {+ unlinkSync(CODE_FILE);+ } catch {}+}++try {+ await client.start({+ phoneNumber: async () => PHONE,+ password: async () => {+ // 2FA password is separate from the phone code. If the user has 2FA+ // enabled, we'd need another bridge file. For MVP, default to empty+ // and let gram.js error loudly if 2FA is required.+ emit({+ type: "need_password",+ message:+ "Telegram 2FA password required. Write to /tmp/telegram-password.txt or leave unset for no-2FA accounts",+ password_file: "/tmp/telegram-password.txt",+ });+ const start = Date.now();+ while (Date.now() - start < 60_000) {+ if (existsSync("/tmp/telegram-password.txt")) {+ const pw = readFileSync("/tmp/telegram-password.txt", "utf8").trim();+ try {+ unlinkSync("/tmp/telegram-password.txt");+ } catch {}+ return pw;+ }+ await new Promise((r) => setTimeout(r, 2000));+ }+ return "";+ },+ phoneCode: async () => {+ emit({+ type: "need_code",+ channel: "gram_auth",+ message: `Telegram sent a SECOND code for gram.js auth. Write digits-only to ${CODE_FILE}`,+ code_file: CODE_FILE,+ });+ return await waitForCode(300);+ },+ onError: (err) => emit({ type: "gram_error", message: err.message }),+ });+} catch (err) {+ die(`gram.js auth failed: ${err.message}`);+}++const sessionStr = client.session.save();++// Step 2.1: Validate session+emit({ type: "step", message: "Validating session..." });+try {+ await client.connect();+ const me = await client.getMe();+ emit({+ type: "step",+ message: `✓ Validated — ${me.firstName} (@${me.username || "no-username"})`,+ });+ await client.disconnect();+} catch (e) {+ emit({ type: "step", message: `⚠ Session validation failed: ${e.message}` });+ await client.disconnect().catch(() => {});+}++// Step 2.2: Save to macOS keychain+if (process.platform === "darwin") {+ try {+ for (const [svc, val] of [+ ["telegram-api-id", apiId],+ ["telegram-api-hash", apiHash],+ ["telegram-phone", PHONE],+ ["telegram-session", sessionStr],+ ]) {+ execSync(+ `security add-generic-password -U -s "${svc}" -a "$USER" -w '${val.replace(/'/g, "'\\''")}'`,+ { timeout: 5000 },+ );+ }+ emit({ type: "step", message: "✓ Saved credentials to macOS keychain" });+ } catch (e) {+ emit({ type: "step", message: `○ Keychain save failed: ${e.message}` });+ }+}++// Step 2.3: Register MCP server+try {+ const pluginRoot =+ process.env.CLAUDE_PLUGIN_ROOT ||+ execSync("echo $CLAUDE_PLUGIN_ROOT", { encoding: "utf8" }).trim();+ const telegramServerPath = pluginRoot+ ? `${pluginRoot}/telegram-server/index.js`+ : null;+ if (telegramServerPath) {+ execSync(+ `claude mcp add telegram -s user` ++ ` -e TELEGRAM_API_ID='${apiId}'` ++ ` -e TELEGRAM_API_HASH='${apiHash}'` ++ ` -e TELEGRAM_PHONE='${PHONE}'` ++ ` -e TELEGRAM_SESSION='${sessionStr.replace(/'/g, "'\\''")}'` ++ ` -- node "${telegramServerPath}"`,+ { timeout: 15000, stdio: "pipe" },+ );+ emit({+ type: "step",+ message: "✓ Registered Telegram MCP server in Claude Code",+ });+ }+} catch {+ emit({+ type: "step",+ message: "○ Could not auto-register MCP — run: claude mcp add telegram",+ });+}++const result = {+ api_id: apiId,+ api_hash: apiHash,+ phone: PHONE,+ session: sessionStr,+};+process.stdout.write(JSON.stringify(result) + "\n");+process.exit(0);diff --git a/claude-ops/bin/ops-unread b/claude-ops/bin/ops-unreadnew file mode 100755index 00000000..5a04648e--- /dev/null+++ b/claude-ops/bin/ops-unread@@ -0,0 +1,110 @@+#!/usr/bin/env bash+# ops-unread — Channel availability + unread counts → JSON+# Checks WhatsApp (wacli), Email (gog), Slack (env), Telegram (env)+# All secrets via env vars or CLI auth — no hardcoded credentials.+#+# ENV VARS (optional — tools auto-detect if installed):+# GMAIL_ACCOUNT — Gmail account for gog (default: auto-detect)+# SLACK_MCP_ENABLED — "true" if Slack MCP server is configured+# TELEGRAM_ENABLED — "true" if Telegram user-auth MCP is configured+# WACLI_STORE — wacli store path (default: ~/.wacli)++set -euo pipefail++RESULT='{"channels":{}}'++# ── WhatsApp via wacli ──+if command -v wacli &>/dev/null; then+ # Check connection status+ WA_STATUS=$(wacli doctor 2>/dev/null | grep -i "CONNECTED" | awk '{print $2}' || echo "unknown")+ WA_AUTH=$(wacli doctor 2>/dev/null | grep -i "AUTHENTICATED" | awk '{print $2}' || echo "unknown")++ if [ "$WA_AUTH" = "true" ]; then+ # Count non-archived chats with recent activity (7 days)+ WA_RECENT=$(wacli chats list --json 2>/dev/null | python3 -c "+import json, sys+from datetime import datetime, timezone, timedelta+try:+ raw = json.loads(sys.stdin.read())+ data = raw.get('data', raw)+ chats = data if isinstance(data, list) else data.get('chats', [])+ cutoff = datetime.now(timezone.utc) - timedelta(days=7)+ count = 0+ for c in chats:+ ts = c.get('LastMessageTS', '')+ try:+ t = datetime.fromisoformat(ts.replace('Z', '+00:00'))+ if t > cutoff:+ count += 1+ except: pass+ print(count)+except:+ print(0)+" 2>/dev/null || echo "0")++ [[ "$WA_RECENT" =~ ^[0-9]+$ ]] || WA_RECENT="0"+ RESULT=$(echo "$RESULT" | jq \+ --argjson c "$WA_RECENT" \+ --arg status "$WA_STATUS" \+ '.channels.whatsapp = {"recent_chats": $c, "connected": ($status == "true"), "available": true}')+ else+ RESULT=$(echo "$RESULT" | jq '.channels.whatsapp = {"unread": 0, "available": false, "note": "wacli not authenticated — run: wacli auth"}')+ fi+else+ RESULT=$(echo "$RESULT" | jq '.channels.whatsapp = {"unread": 0, "available": false, "note": "wacli not installed"}')+fi++# ── Email via gog ──+GMAIL_ACCT="${GMAIL_ACCOUNT:-}"+if command -v gog &>/dev/null; then+ # Auto-detect account if not set+ if [ -z "$GMAIL_ACCT" ]; then+ GMAIL_ACCT=$(gog gmail search -j --results-only --no-input --max 1 "in:inbox" 2>/dev/null | python3 -c "+import json, sys+try:+ data = json.loads(sys.stdin.read())+ # gog worked without -a, so default account is fine+ print('auto')+except:+ print('')+" 2>/dev/null || echo "")+ fi++ if [ -n "$GMAIL_ACCT" ]; then+ ACCT_FLAG=""+ [ "$GMAIL_ACCT" != "auto" ] && ACCT_FLAG="-a $GMAIL_ACCT"+ EMAIL_COUNT=$(gog gmail search $ACCT_FLAG -j --results-only --no-input --max 50 "in:inbox" 2>/dev/null | python3 -c "+import json, sys+try:+ data = json.loads(sys.stdin.read())+ items = data if isinstance(data, list) else data.get('threads', data.get('messages', []))+ print(len(items))+except:+ print(0)+" 2>/dev/null || echo "0")+ [[ "$EMAIL_COUNT" =~ ^[0-9]+$ ]] || EMAIL_COUNT="0"+ RESULT=$(echo "$RESULT" | jq --argjson c "$EMAIL_COUNT" '.channels.email = {"unread": $c, "available": true}')+ else+ RESULT=$(echo "$RESULT" | jq '.channels.email = {"unread": 0, "available": false, "note": "gog not authenticated — run: gog gmail auth"}')+ fi+else+ RESULT=$(echo "$RESULT" | jq '.channels.email = {"unread": 0, "available": false, "note": "gog not installed — see github.com/Lifecycle-Innovations-Limited/gog"}')+fi++# ── Slack — MCP-based, check env ──+SLACK_ENABLED="${SLACK_MCP_ENABLED:-false}"+if [ "$SLACK_ENABLED" = "true" ]; then+ RESULT=$(echo "$RESULT" | jq '.channels.slack = {"unread": null, "available": true, "note": "Scan via Slack MCP tools"}')+else+ RESULT=$(echo "$RESULT" | jq '.channels.slack = {"unread": null, "available": false, "note": "Set SLACK_MCP_ENABLED=true when Slack MCP server is configured"}')+fi++# ── Telegram — user-auth MCP, check env ──+TG_ENABLED="${TELEGRAM_ENABLED:-false}"+if [ "$TG_ENABLED" = "true" ]; then+ RESULT=$(echo "$RESULT" | jq '.channels.telegram = {"unread": null, "available": true, "note": "Scan via Telegram user-auth MCP tools"}')+else+ RESULT=$(echo "$RESULT" | jq '.channels.telegram = {"unread": null, "available": false, "note": "Set TELEGRAM_ENABLED=true when user-auth MCP (tdlib/MTProto) is configured"}')+fi++echo "$RESULT"diff --git a/claude-ops/bin/ops-welcome b/claude-ops/bin/ops-welcomenew file mode 100755index 00000000..272ea3d3--- /dev/null+++ b/claude-ops/bin/ops-welcome@@ -0,0 +1,94 @@+#!/usr/bin/env bash+# ops-welcome — First-run animated welcome banner for claude-ops+# Called by SessionStart hook. Prints nothing if preferences.json already exists.+set -euo pipefail++# --- First-run gate ---+PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+[ ! -f "$PREFS" ] || exit 0++# --- Color setup (degrade gracefully) ---+if [[ -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then+ RST=$'\033[0m'+ BOLD=$'\033[1m'+ DIM=$'\033[2m'+ CYN=$'\033[36m'+ GRN=$'\033[32m'+ YLW=$'\033[33m'+ WHT=$'\033[37m'+ BCYN=$'\033[1;36m'+ BGRN=$'\033[1;32m'+ BWHT=$'\033[1;37m'+else+ RST="" BOLD="" DIM="" CYN="" GRN="" YLW="" WHT="" BCYN="" BGRN="" BWHT=""+fi++# --- Helpers ---+D=0.025 # delay between lines+p() { printf '%s\n' "$1"; sleep "$D"; }+dp() { sleep "${2:-0.08}"; printf '%s\n' "$1"; }++# --- Blank line spacer ---+p ""++# --- Logo reveal ---+p "${DIM}${CYN} ╔══════════════════════════════════════════════════╗${RST}"+p "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}░█████╗░██╗░░░░░░█████╗░██╗░░░██╗██████╗░${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}██╔══██╗██║░░░░░██╔══██╗██║░░░██║██╔══██╗${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}██║░░╚═╝██║░░░░░███████║██║░░░██║██║░░██║${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}██║░░██╗██║░░░░░██╔══██║██║░░░██║██║░░██║${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}╚█████╔╝███████╗██║░░██║╚██████╔╝██████╔╝${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BCYN}░╚════╝░╚══════╝╚═╝░░╚═╝░╚═════╝░╚═════╝░${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}░█████╗░██████╗░░██████╗${RST} ${DIM}v0.3.0${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}██╔══██╗██╔══██╗██╔════╝${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}██║░░██║██████╔╝╚█████╗░${RST} ${DIM}Business OS${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}██║░░██║██╔═══╝░░╚═══██╗${RST} ${DIM}for Claude Code${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}╚█████╔╝██║░░░░░██████╔╝${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${BWHT}░╚════╝░╚═╝░░░░░╚═════╝░${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ║${RST} ${DIM}${CYN}║${RST}"+p "${DIM}${CYN} ╚══════════════════════════════════════════════════╝${RST}"++sleep 0.15++# --- Boot sequence ---+p ""+p " ${DIM}Initializing systems...${RST}"+p ""++# Animated progress bars+progress_step() {+ local label="$1" fill="$2"+ local bar=""+ local empty=""+ for ((i=0; i<fill; i++)); do bar+="#"; done+ for ((i=fill; i<16; i++)); do empty+="."; done+ printf ' %s[%s%s%s%s]%s %s\n' \+ "$DIM" "$GRN" "$bar" "$DIM" "$empty" "$RST" "$label"+ sleep 0.12+}++progress_step "${WHT}Scanning CLIs${RST}" 4+progress_step "${WHT}Detecting channels${RST}" 8+progress_step "${WHT}Loading integrations${RST}" 12+progress_step "${BGRN}Ready${RST}" 16++sleep 0.1++# --- Dynamic counts ---+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+SKILL_COUNT=$(ls -d "${PLUGIN_ROOT}/skills"/*/ 2>/dev/null | wc -l | tr -d ' ')+AGENT_COUNT=$(ls "${PLUGIN_ROOT}/agents"/*.md 2>/dev/null | wc -l | tr -d ' ')++# --- Summary line ---+p ""+p " ${BWHT}${SKILL_COUNT}${RST} skills loaded ${DIM}|${RST} ${BWHT}${AGENT_COUNT}${RST} agents standing by"+p ""++# --- Separator ---+p " ${DIM}${CYN}────────────────────────────────────────────────────${RST}"+p ""+p " Run ${BCYN}/ops:setup${RST} to configure your integrations"+p " or ${BCYN}/ops:go${RST} for your first morning briefing"+p ""diff --git a/claude-ops/docs/agents-reference.md b/claude-ops/docs/agents-reference.mdnew file mode 100644index 00000000..f1e7c11e--- /dev/null+++ b/claude-ops/docs/agents-reference.md@@ -0,0 +1,109 @@+# Agents Reference++All 12 agents in claude-ops v0.5.0. Agent files live in `agents/`.++Agents are spawned by skills — they are not invoked directly. Each has `memory` scope for cross-session learning and a defined `effort` level that controls token budget.++---++## Background Scanner Agents++These agents run in the background, feeding structured JSON data to the main skills.++### `comms-scanner` · `agents/comms-scanner.md`+- **Model**: claude-sonnet-4-5+- **Effort**: low · **maxTurns**: 10+- **Memory**: project scope+- **Tools**: Bash only (read-only)+- **Purpose**: Scans all communication channels (WhatsApp, Email, Slack, Telegram) for FULL inbox state. Classifies each conversation as `NEEDS_REPLY`, `WAITING`, or `HANDLED`. Returns structured JSON consumed by `ops-inbox` and `ops-go`.++### `infra-monitor` · `agents/infra-monitor.md`+- **Model**: claude-sonnet-4-5+- **Effort**: low · **maxTurns**: 15+- **Memory**: project scope+- **Tools**: Bash only+- **Purpose**: ECS, Vercel, and AWS health checker. Returns structured JSON with service health, recent deployments, and anomaly flags. Used by `ops-fires` and `ops-deploy`.++### `project-scanner` · `agents/project-scanner.md`+- **Model**: claude-sonnet-4-5+- **Effort**: low · **maxTurns**: 15+- **Memory**: project scope+- **Tools**: Bash only+- **Purpose**: Git, PR, and CI status scanner across all registered repos. Returns structured JSON with branch state, uncommitted files, open PRs, and CI status for each project.++### `revenue-tracker` · `agents/revenue-tracker.md`+- **Model**: claude-sonnet-4-5+- **Effort**: medium · **maxTurns**: 20+- **Memory**: project scope+- **Tools**: Bash only+- **Purpose**: Revenue, billing, and credits analysis. Queries AWS Cost Explorer, checks credit balances, cross-references project revenue stages. Returns structured financial snapshot for `ops-revenue` and `ops-go`.++---++## Fix Agents++These agents are dispatched when issues are found and need resolution.++### `triage-agent` · `agents/triage-agent.md`+- **Model**: claude-sonnet-4-5+- **Effort**: high · **maxTurns**: 40+- **Isolation**: worktree (sandboxed)+- **Purpose**: Investigates a specific issue from Sentry, Linear, or GitHub. Finds the root cause in code, checks if it's already fixed, and either confirms resolution or creates a fix branch with a PR. Runs in an isolated worktree to avoid polluting the main working tree.++---++## C-Suite Analysis Agents++All four run in parallel when `/ops:yolo` is invoked. Each uses Opus for maximum analytical depth.++### `yolo-ceo` · `agents/yolo-ceo.md`+- **Model**: claude-opus-4-6+- **Effort**: high · **maxTurns**: 20+- **Purpose**: Strategic priority analysis. Growth blockers, resource allocation, build vs. buy decisions, investor-readiness. No sugar-coating.++### `yolo-cto` · `agents/yolo-cto.md`+- **Model**: claude-opus-4-6+- **Effort**: high · **maxTurns**: 25+- **Purpose**: Technical health analysis. Architecture, tech debt, production risks, scalability limits, and cut corners. Brutally honest about what will break.++### `yolo-cfo` · `agents/yolo-cfo.md`+- **Model**: claude-opus-4-6+- **Effort**: high · **maxTurns**: 20+- **Purpose**: Financial analysis. AWS burn rate, runway, ROI on current work, credits expiry, cost anomalies. No optimism without data.++### `yolo-coo` · `agents/yolo-coo.md`+- **Model**: claude-opus-4-6+- **Effort**: high · **maxTurns**: 25+- **Purpose**: Operations execution analysis. Stale work, broken processes, missing automation, communication failures. What the CEO doesn't see.++---++## Daemon & System Agents++### `daemon-agent` · `agents/daemon-agent.md`+- **Model**: claude-sonnet-4-6+- **Effort**: low · **maxTurns**: 10+- **Memory**: project scope+- **Purpose**: Manages the ops background daemon — start, stop, restart services, check health. Spawned by `ops-doctor` and `ops-setup` when daemon configuration changes are needed.++### `doctor-agent` · `agents/doctor-agent.md`+- **Model**: claude-sonnet-4-6+- **Effort**: high · **maxTurns**: 30+- **Tools**: Bash, Read, Write, Edit, Grep, Glob (no Agent spawning)+- **Purpose**: Diagnoses and auto-fixes ops plugin configuration errors, manifest issues, broken permissions, invalid JSON, and stale cache copies. Spawned by `/ops:doctor`.++### `memory-extractor` · `agents/memory-extractor.md`+- **Model**: claude-haiku-4-5-20251001+- **Effort**: low · **maxTurns**: 10+- **Memory**: project scope+- **Purpose**: Background agent that extracts user profiles, contact cards, and behavioral patterns from chat history. Runs as a daemon service every 30 minutes. Writes structured markdown to `memories/`. Used by all communication skills for context-aware drafting.++---++## Agent Memory Scopes++| Scope | What persists |+|-------|--------------|+| `project` | Remembered across sessions within the same project context |+| `user` | Remembered across all projects for the same user |+| worktree isolation | Agent runs in a sandboxed worktree, changes don't bleed into main tree |diff --git a/claude-ops/docs/daemon-guide.md b/claude-ops/docs/daemon-guide.mdnew file mode 100644index 00000000..bb5752b7--- /dev/null+++ b/claude-ops/docs/daemon-guide.md@@ -0,0 +1,92 @@+# Daemon Guide++The ops-daemon is a unified background process manager that runs persistently via macOS launchd. It replaced per-service launchd agents (introduced in v0.5.0).++## What the Daemon Does++1. **Keeps WhatsApp connected** — runs `wacli follow` in persistent mode with auto-reconnect on disconnect+2. **Auto-backfills @lid chats** — detects empty chats from the `@lid` addressing format and backfills message history+3. **Triggers memory extraction** — every 30 minutes, spawns the `memory-extractor` agent to update `memories/`+4. **Writes a health file** — maintains `~/.wacli/.health` so skills can pre-flight check before attempting WhatsApp reads++## Setup++The daemon is configured automatically by the setup wizard:++```+/ops:setup+# Step 5b: Background daemon+```++Or start it manually:++```bash+# Start via launchd (recommended — survives reboots)+launchctl load ~/Library/LaunchAgents/com.claude-ops.daemon.plist++# Start foreground (debug mode)+~/.claude/plugins/cache/ops-marketplace/ops/<version>/scripts/ops-daemon.sh start++# Check status+~/.claude/plugins/cache/.../scripts/ops-daemon.sh status+```++The daemon script lives at `scripts/ops-daemon.sh`.++## Health File Contract++The daemon writes `~/.wacli/.health` on every successful wacli sync. Skills read this file before any WhatsApp operation.++```json+{+ "status": "ok",+ "last_sync": "2026-04-13T07:45:00Z",+ "wacli_pid": 12345,+ "message_count": 1420+}+```++| Field | Meaning |+|-------|---------|+| `status` | `ok`, `degraded`, or `down` |+| `last_sync` | ISO timestamp of last successful wacli poll |+| `wacli_pid` | PID of the running wacli process |+| `message_count` | Total messages in local DB |++If `last_sync` is more than 10 minutes ago, the PreToolUse hook surfaces a warning before any WhatsApp command.++## PreToolUse Hook++`hooks/whatsapp-health-check.sh` runs automatically before any `wacli` call. It checks the health file and either:+- Proceeds silently if `status === ok` and `last_sync` is recent+- Surfaces a warning with instructions to restart the daemon if degraded++The hook is registered in `.claude/settings.json` under `preToolUse`.++## Brain Layer++The daemon includes a lightweight brain layer (`bin/ops-brain`) that:+- Pre-fetches briefing data every 5 minutes and caches it to `~/.claude/plugins/data/.../daemon-cache.json`+- Detects urgent message patterns (mentions of your name, "urgent", "ASAP", "fire", "down")+- Writes urgent flags to the health file so `/ops:go` can surface them instantly++This makes `/ops:go` load in under 3 seconds instead of gathering data live.++## Troubleshooting++```bash+# View daemon logs+tail -f /tmp/com.claude-ops.daemon.log++# Force restart+launchctl unload ~/Library/LaunchAgents/com.claude-ops.daemon.plist+launchctl load ~/Library/LaunchAgents/com.claude-ops.daemon.plist++# Run doctor to auto-fix daemon issues+/ops:doctor+```++Common issues:+- **`wacli not connected`** — run `/ops:setup whatsapp` to re-authenticate+- **`health file stale`** — daemon may have crashed; check `/tmp/com.claude-ops.daemon.log`+- **`memory extractor not running`** — check that haiku API key is configured in preferences or Dopplerdiff --git a/claude-ops/docs/memories-system.md b/claude-ops/docs/memories-system.mdnew file mode 100644index 00000000..4affd16a--- /dev/null+++ b/claude-ops/docs/memories-system.md@@ -0,0 +1,115 @@+# Memories System++The memories system gives claude-ops persistent context about people, projects, and your communication patterns. Introduced in v0.5.0.++## How It Works++1. **Extraction** — the `memory-extractor` agent (`agents/memory-extractor.md`) runs every 30 minutes as a daemon service. It reads recent WhatsApp messages (via `wacli`) and email threads (via `gog`) and calls Claude Haiku to extract structured profiles.+2. **Storage** — profiles are written as markdown files to `~/.claude/plugins/data/ops-ops-marketplace/memories/`+3. **Consumption** — skills load the relevant memory files at runtime via the Runtime Context block at the top of each SKILL.md++## File Format++### Contact profiles (`memories/contacts/<name>.md`)++```markdown+# John Smith++## Contact Info+- WhatsApp: +15551234567+- Email: [email protected]+- Company: Acme Corp++## Communication Preferences+- Prefers WhatsApp over email+- Responds quickly in the morning (PST)+- Informal tone — uses first names, short messages++## Context+- CEO of Acme Corp — potential enterprise customer+- Last conversation: pricing discussion 2026-04-10+- Waiting on: proposal we sent 2026-04-11++## Topics+- my-app integration+- enterprise pricing+- Q2 budget approval+```++### User preferences (`memories/preferences.md`)++```markdown+# Communication Preferences++## Style+- Short, direct messages — no filler+- Never start with "Hope you're well"+- Sign off with first name only++## Defaults+- Primary channel: WhatsApp+- Calendar timezone: America/New_York+- Working hours: 8am–7pm ET+```++### Project context (`memories/projects/<alias>.md`)++```markdown+# my-app++## Status+- Phase 6.2 in progress — push notifications backend+- Dev branch: feature/push-notifications+- Last deploy: 2026-04-12 14:30 UTC++## Key Contacts+- Alice (QA): [email protected]+- Bob (backend): [email protected]+```++## How Skills Consume Memories++Every skill has a Runtime Context block that loads memories at execution time:++```markdown+```!+# Load memories+MEMORIES_DIR="$CLAUDE_PLUGIN_ROOT/../data/memories"+cat "$MEMORIES_DIR/preferences.md" 2>/dev/null || echo "No preferences found"+ls "$MEMORIES_DIR/contacts/" 2>/dev/null | head -20+```+```++The `ops-inbox` and `ops-comms` skills do a contact lookup before drafting any reply:++1. Check `memories/contacts/<name>.md` for communication style and history+2. Check `memories/projects/` for relevant project context+3. Draft reply matching the contact's expected tone and the conversation's topic++## Manual Memory Management++```bash+# View all contact profiles+ls ~/.claude/plugins/data/ops-ops-marketplace/memories/contacts/++# Edit a contact profile+# (use your editor — files are plain markdown)+vim ~/.claude/plugins/data/ops-ops-marketplace/memories/contacts/john-smith.md++# Force a memory extraction run now+# (daemon normally does this every 30 min)+/ops:doctor --run-memory-extractor+```++## Memory Extraction Trigger++The daemon triggers extraction when:+- 30 minutes have elapsed since the last run+- The message count in `~/.wacli/.health` has increased by more than 5+- `/ops:doctor` is run with `--run-memory-extractor`++The extractor uses `claude-haiku-4-5-20251001` (fast + cheap) for all extraction work. It merges new information into existing profiles rather than overwriting, so context accumulates over time.++## Privacy++Memory files live entirely on your local machine at `~/.claude/plugins/data/ops-ops-marketplace/memories/`. They are never sent anywhere — they are just files on disk that skills read. The extractor reads your local wacli database and local email cache, not cloud APIs.diff --git a/claude-ops/docs/skills-reference.md b/claude-ops/docs/skills-reference.mdnew file mode 100644index 00000000..30423043--- /dev/null+++ b/claude-ops/docs/skills-reference.md@@ -0,0 +1,175 @@+# Skills Reference++All 21 skills available in claude-ops v0.8.0. Skills live in `skills/<name>/SKILL.md`.++## AskUserQuestion Batching Pattern++All skills enforce a hard limit of **<=4 options per `AskUserQuestion` call** (plugin-root CLAUDE.md rule, enforced by the tool schema). When a menu has more than 4 entries, apply this strategy:++1. **Filter first** — remove already-configured, completed, or irrelevant items. Often brings count to <=4.+2. **Batch with "More..."** — split remaining items into sequential calls of <=4. Last option in each non-final batch is `[More options...]` to advance to the next batch.+3. **Paginate dynamic lists** — any runtime list (projects, configs) that may exceed 4 items must be paginated at 4 per page.++Examples in this release: setup section picker (11 items → 4+4+3), setup channel picker (7 items → 4+3), ops-comms / deploy / fires / go / inbox / linear / projects / revenue / speedup / triage / yolo all use "More..." bridges where needed. ops-dash hotkey menu was refactored to comply.++## Core Navigation++### `/ops` · `skills/ops/SKILL.md`+Business operations router. Routes to the right skill based on arguments, or launches the dashboard with no args.+- `/ops` — launch pixel-art dashboard+- `/ops inbox` — route to ops-inbox+- `/ops fires my-app` — route to ops-fires for a specific project++### `/ops:dash` · `skills/ops-dash/SKILL.md`+Interactive pixel-art command center. Visual HQ with live status indicators (fires, unread, PRs, GSD phases), hotkey navigation, C-suite report viewer, settings editor, and FAQ.+- `/ops:dash` — open dashboard+- `/ops:dash settings` — jump to settings+- `/ops:dash faq` — open help/FAQ++---++## Daily Operations++### `/ops:go` · `skills/ops-go/SKILL.md`+Token-efficient morning briefing. Pre-gathers all data via shell scripts (`bin/ops-infra`, `bin/ops-dash`) in parallel, then presents a unified dashboard in under 10 seconds.+- `/ops:go` — full briefing+- `/ops:go my-app` — briefing scoped to one project alias++### `/ops:next` · `skills/ops-next/SKILL.md`+Priority-ordered next action. Applies the priority stack: fires > urgent comms > ready-to-merge PRs > Linear sprint > GSD work.+- `/ops:next` — what should I do right now?+- `/ops:next focus on my-app` — scoped recommendation++### `/ops:inbox` · `skills/ops-inbox/SKILL.md`+Full inbox management. Reads complete conversation threads (20+ messages), builds contact profile cards, drafts replies matching your language/style. Never sends without understanding the full thread.+- `/ops:inbox` — all channels+- `/ops:inbox whatsapp` — WhatsApp only+- `/ops:inbox email` — Gmail only+- `/ops:inbox slack` / `/ops:inbox telegram`++### `/ops:comms` · `skills/ops-comms/SKILL.md`+Send and read messages across all channels. Full conversation context required before any send. WhatsApp health pre-flight via PreToolUse hook.+- `/ops:comms send "hey, can we chat?" to John Smith`+- `/ops:comms read whatsapp`+- `/ops:comms read slack #general`++---++## Project & Engineering++### `/ops:projects` · `skills/ops-projects/SKILL.md`+Portfolio dashboard. Shows all registered projects with GSD phase, branch state, uncommitted files, open PRs, and CI status.+- `/ops:projects` — all projects+- `/ops:projects my-app` — single project deep-dive++### `/ops:linear` · `skills/ops-linear/SKILL.md`+Linear sprint board and issue management. Uses Linear MCP for full sprint visibility and GSD sync.+- `/ops:linear sprint` — current sprint+- `/ops:linear create "Fix login bug"` — new issue+- `/ops:linear backlog` — backlog review++### `/ops:triage` · `skills/ops-triage/SKILL.md`+Cross-platform issue triage. Pulls from Sentry, Linear, and GitHub Issues. Cross-references against code to find already-fixed issues and auto-resolves them.+- `/ops:triage` — all platforms+- `/ops:triage sentry` — Sentry only+- `/ops:triage my-app` — project-scoped++### `/ops:fires` · `skills/ops-fires/SKILL.md`+Production incidents dashboard. Reads ECS health, Sentry errors, CI failures. Dispatches fix agents for active fires.+- `/ops:fires` — all projects+- `/ops:fires my-app` — specific project++### `/ops:deploy` · `skills/ops-deploy/SKILL.md`+Deploy status across all projects. Shows ECS service versions, Vercel deployments, pending deploys, and CI/CD pipeline state.+- `/ops:deploy` — full status+- `/ops:deploy my-app` — project-scoped+- `/ops:deploy ecs` — ECS only++### `/ops:merge` · `skills/ops-merge/SKILL.md`+Autonomous PR merge pipeline. Dispatches subagents to fix CI, resolve conflicts, address review comments, then merges. Optionally syncs dev↔main branches.+- `/ops:merge` — process all ready PRs+- `/ops:merge --main` — also sync dev→main+- `/ops:merge --dry-run` — preview only+- `/ops:merge --repo Lifecycle-Innovations-Limited/my-app`++---++## Business Intelligence++### `/ops:revenue` · `skills/ops-revenue/SKILL.md`+Revenue and costs dashboard. AWS spend via Cost Explorer, credits tracker, project revenue stages, burn rate, and runway estimate.+- `/ops:revenue` — full dashboard+- `/ops:revenue costs` — AWS spend breakdown+- `/ops:revenue runway` — burn rate + runway++### `/ops:yolo` · `skills/ops-yolo/SKILL.md`+C-suite analysis + autonomous mode. Spawns 4 parallel agents (CEO, CTO, CFO, COO) each with full data access. Produces unfiltered Hard Truths report. Type `YOLO` to hand over controls.+- `/ops:yolo` — run C-suite analysis+- `/ops:yolo YOLO` — autonomous mode++---++## E-Commerce & Marketing++### `/ops:ecom` · `skills/ops-ecom/SKILL.md`+Shopify store command center. Orders, inventory, fulfillment, analytics, and store health via Shopify Admin API.+- `/ops:ecom orders` — recent orders + fulfillment status+- `/ops:ecom inventory` — low stock alerts+- `/ops:ecom analytics` — revenue, AOV, conversion+- `/ops:ecom setup` — configure Shopify API credentials++### `/ops:marketing` · `skills/ops-marketing/SKILL.md`+Marketing analytics dashboard. Email campaigns (Klaviyo), paid ads (Meta/Google), analytics (GA4), SEO, and social media metrics.+- `/ops:marketing` — full dashboard+- `/ops:marketing email` — Klaviyo campaign performance+- `/ops:marketing ads` — Meta + Google Ads spend/ROAS+- `/ops:marketing seo` — SEO + GA4 organic traffic++### `/ops:voice` · `skills/ops-voice/SKILL.md`+Voice channel management. Make phone calls (Bland AI), text-to-speech (ElevenLabs), transcribe audio (Whisper/Groq).+- `/ops:voice call +15551234567 "Check in on the order"` — outbound call via Bland AI+- `/ops:voice tts "Your order is ready"` — generate speech via ElevenLabs+- `/ops:voice transcribe recording.mp3` — transcribe audio+- `/ops:voice setup` — configure API keys++---++## Orchestration & Automation++### `/ops:orchestrate` · `skills/ops-orchestrate/SKILL.md`+Autonomous multi-project orchestration engine. Audits all registered projects, structures work into dependency-wired tasks, dispatches parallel agents, audits completions, and ships PRs.+- `/ops:orchestrate` — full autonomous run (hybrid mode)+- `/ops:orchestrate --subagents` — use fire-and-forget subagents+- `/ops:orchestrate --teams` — use Agent Teams for coordination+- `/ops:orchestrate --dry-run` — preview task plan without executing+- `/ops:orchestrate --fires-only` — only fix production incidents+- `/ops:orchestrate --project my-app` — single project+- `/ops:orchestrate --max-waves 2` — limit parallelism++---++## Setup & Maintenance++### `/ops:setup` · `skills/setup/SKILL.md`+Interactive setup wizard. Installs CLIs, configures secrets (Doppler, 1Password, Bitwarden), connects integrations (Telegram, WhatsApp, Email, Slack, Linear, Sentry, Vercel), builds project registry.+- `/ops:setup` — full wizard+- `/ops:setup telegram` — Telegram only+- `/ops:setup doppler` — secrets manager config+- `/ops:setup registry` — project registry builder++### `/ops:doctor` · `skills/ops-doctor/SKILL.md`+Health check and auto-repair. Diagnoses manifest errors, broken permissions, invalid configs, stale caches, missing files — then spawns an agent to fix everything automatically.+- `/ops:doctor` — full health check + auto-fix+- `/ops:doctor --check-only` — diagnose only, no fixes+- `/ops:doctor --verbose` — detailed output++### `/ops:speedup` · `skills/ops-speedup/SKILL.md`+Cross-platform system optimizer. Detects macOS/Linux/WSL, scans for reclaimable disk space, memory pressure, runaway processes, startup bloat, network latency. Health score 0–100.+- `/ops:speedup scan` — diagnose only+- `/ops:speedup clean` — quick cleanup+- `/ops:speedup deep` — full deep clean++### `/ops:uninstall` · `skills/uninstall/SKILL.md`+Complete removal of the plugin, all credentials, cached files, shell exports, and MCP registrations. Confirms each step before deletion.+- `/ops:uninstall` — guided removal+- `/ops:uninstall --confirm` — skip confirmationsdiff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.jsonnew file mode 100644index 00000000..075f7037--- /dev/null+++ b/claude-ops/hooks/hooks.json@@ -0,0 +1,39 @@+{+ "hooks": {+ "SessionStart": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-welcome 2>/dev/null || true"+ },+ {+ "type": "command",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/setup.sh 2>/dev/null | grep '✗' | head -3 || true"+ }+ ]+ }+ ],+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-pretool-wacli-health \"$TOOL_INPUT\" 2>/dev/null || true"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-post-session-cleanup 2>/dev/null || true"+ }+ ]+ }+ ]+ }+}diff --git a/claude-ops/output-styles/ops-briefing.md b/claude-ops/output-styles/ops-briefing.mdnew file mode 100644index 00000000..35009872--- /dev/null+++ b/claude-ops/output-styles/ops-briefing.md@@ -0,0 +1,57 @@+---+name: ops-briefing+description: Consistent formatting for all ops plugin output — banners, tables, interactive options+---++# OPS Output Style++## Banners++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► {SECTION NAME}+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++Section names (uppercase): MORNING BRIEFING, INBOX, COMMS, FIRES, PROJECTS, LINEAR, TRIAGE, REVENUE, DEPLOY, NEXT, YOLO MODE++## Status Symbols++- ✓ Healthy / Complete / Resolved+- ✗ Down / Failed / Blocked+- ◆ In Progress / Active+- ○ Pending / Not Started+- ⚠ Warning / Degraded++## Interactive Options (MANDATORY at end of every skill)++```+──────────────────────────────────────────────────────+ What's next?+──────────────────────────────────────────────────────+ a) [Action 1] — [context]+ b) [Action 2] — [context]+ c) [Action 3] — [context]+ d) [Action 4] — [context]++ → Type a letter, project alias, or describe what you want+──────────────────────────────────────────────────────+```++## Fire Severity++- P0: Service down, data loss risk+- P1: Broken deploys, CI failures on main+- P2: Degraded performance, non-critical failures+- P3: Warnings, tech debt++## Tables++Use markdown tables with alignment. Keep compact — no empty columns.++## Anti-Patterns++- No emoji spam (only ✓ ✗ ◆ ○ ⚠ and section-specific ones)+- No "Let me..." or "I'll..." preamble+- No trailing summaries — the options ARE the summary+- No asking "Would you like me to..." — present options, user picksdiff --git a/claude-ops/package-lock.json b/claude-ops/package-lock.jsonnew file mode 100644index 00000000..a0b987a3--- /dev/null+++ b/claude-ops/package-lock.json@@ -0,0 +1,1003 @@+{+ "name": "claude-ops-bin",+ "version": "0.2.2",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "claude-ops-bin",+ "version": "0.2.2",+ "dependencies": {+ "classic-level": "^3.0.0",+ "input": "^1.0.1",+ "playwright": "^1.59.1",+ "telegram": "^2.26.22"+ }+ },+ "node_modules/@cryptography/aes": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/@cryptography/aes/-/aes-0.1.1.tgz",+ "integrity": "sha512-PcYz4FDGblO6tM2kSC+VzhhK62vml6k6/YAkiWtyPvrgJVfnDRoHGDtKn5UiaRRUrvUTTocBpvc2rRgTCqxjsg==",+ "license": "GPL-3.0-or-later"+ },+ "node_modules/abstract-level": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/abstract-level/-/abstract-level-3.1.1.tgz",+ "integrity": "sha512-CW2gKbJFTuX1feMvOrvsVMmijAOgI9kg2Ie9Dq3gOcMt/dVVoVmqNlLcEUCT13NxHFMEajcUcVBIplbyDroDiw==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^6.0.3",+ "is-buffer": "^2.0.5",+ "level-supports": "^6.2.0",+ "level-transcoder": "^1.0.1",+ "maybe-combine-errors": "^1.0.0",+ "module-error": "^1.0.1"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/ansi-escapes": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz",+ "integrity": "sha512-wiXutNjDUlNEDWHcYH3jtZUhd3c4/VojassD8zHdHCY13xbZy2XbW+NKQwA0tWGBVzDA9qEzYwfoSsWmviidhw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/ansi-regex": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",+ "integrity": "sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/ansi-styles": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",+ "integrity": "sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/async-mutex": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz",+ "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.3.1"+ }+ },+ "node_modules/babel-runtime": {+ "version": "6.26.0",+ "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz",+ "integrity": "sha512-ITKNuq2wKlW1fJg9sSW52eepoYgZBggvOAHC0u/CYu/qxQ9EVzThCgR69BnSXLHjy2f7SY5zaQ4yt7H9ZVxY2g==",+ "license": "MIT",+ "dependencies": {+ "core-js": "^2.4.0",+ "regenerator-runtime": "^0.11.0"+ }+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/big-integer": {+ "version": "1.6.52",+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",+ "license": "Unlicense",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/buffer": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.2.1"+ }+ },+ "node_modules/bufferutil": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.1.0.tgz",+ "integrity": "sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },+ "node_modules/chalk": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",+ "integrity": "sha512-U3lRVLMSlsCfjqYPbLyVv11M9CPW4I728d6TCKMAOJueEeB9/8o+eSsMnxPJD+Q+K909sdESg7C+tIkoH6on1A==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^2.2.1",+ "escape-string-regexp": "^1.0.2",+ "has-ansi": "^2.0.0",+ "strip-ansi": "^3.0.0",+ "supports-color": "^2.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/classic-level": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/classic-level/-/classic-level-3.0.0.tgz",+ "integrity": "sha512-yGy8j8LjPbN0Bh3+ygmyYvrmskVita92pD/zCoalfcC9XxZj6iDtZTAnz+ot7GG8p9KLTG+MZ84tSA4AhkgVZQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "abstract-level": "^3.1.0",+ "module-error": "^1.0.1",+ "napi-macros": "^2.2.2",+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/cli-cursor": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-1.0.2.tgz",+ "integrity": "sha512-25tABq090YNKkF6JH7lcwO0zFJTRke4Jcq9iX2nr/Sz0Cjjv4gckmwlW6Ty/aoyFd6z3ysR2hMGC2GFugmBo6A==",+ "license": "MIT",+ "dependencies": {+ "restore-cursor": "^1.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/cli-width": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.1.tgz",+ "integrity": "sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==",+ "license": "ISC"+ },+ "node_modules/code-point-at": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz",+ "integrity": "sha512-RpAVKQA5T63xEj6/giIbUEtZwJ4UFIc3ZtvEkiaUERylqe8xb5IvqcgOurZLahv93CLKfxcw5YI+DZcUBRyLXA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/core-js": {+ "version": "2.6.12",+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.12.tgz",+ "integrity": "sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ==",+ "deprecated": "core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.",+ "hasInstallScript": true,+ "license": "MIT"+ },+ "node_modules/d": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz",+ "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==",+ "license": "ISC",+ "dependencies": {+ "es5-ext": "^0.10.64",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/dom-serializer": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz",+ "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==",+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.0.1",+ "domhandler": "^4.2.0",+ "entities": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"+ }+ },+ "node_modules/domelementtype": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "BSD-2-Clause"+ },+ "node_modules/domhandler": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz",+ "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "domelementtype": "^2.2.0"+ },+ "engines": {+ "node": ">= 4"+ },+ "funding": {+ "url": "https://github.com/fb55/domhandler?sponsor=1"+ }+ },+ "node_modules/domutils": {+ "version": "2.8.0",+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",+ "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "dom-serializer": "^1.0.1",+ "domelementtype": "^2.2.0",+ "domhandler": "^4.2.0"+ },+ "funding": {+ "url": "https://github.com/fb55/domutils?sponsor=1"+ }+ },+ "node_modules/entities": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",+ "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==",+ "license": "BSD-2-Clause",+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/es5-ext": {+ "version": "0.10.64",+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz",+ "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==",+ "hasInstallScript": true,+ "license": "ISC",+ "dependencies": {+ "es6-iterator": "^2.0.3",+ "es6-symbol": "^3.1.3",+ "esniff": "^2.0.1",+ "next-tick": "^1.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/es6-iterator": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "^0.10.35",+ "es6-symbol": "^3.1.1"+ }+ },+ "node_modules/es6-symbol": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz",+ "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.2",+ "ext": "^1.7.0"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.0"+ }+ },+ "node_modules/esniff": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz",+ "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.1",+ "es5-ext": "^0.10.62",+ "event-emitter": "^0.3.5",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/event-emitter": {+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "~0.10.14"+ }+ },+ "node_modules/exit-hook": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-1.1.1.tgz",+ "integrity": "sha512-MsG3prOVw1WtLXAZbM3KiYtooKR1LvxHh3VHsVtIy0uiUu8usxgB/94DP2HxtD/661lLdB6yzQ09lGJSQr6nkg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/ext": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz",+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",+ "license": "ISC",+ "dependencies": {+ "type": "^2.7.2"+ }+ },+ "node_modules/figures": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz",+ "integrity": "sha512-UxKlfCRuCBxSXU4C6t9scbDyWZ4VlaFFdojKtzJuSkuOBQ5CNFum+zZXFwHjo+CxBC1t6zlYPgHIgFjL8ggoEQ==",+ "license": "MIT",+ "dependencies": {+ "escape-string-regexp": "^1.0.5",+ "object-assign": "^4.1.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "license": "ISC"+ },+ "node_modules/has-ansi": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",+ "integrity": "sha512-C8vBJ8DwUCx19vhm7urhTuUsr4/IyP6l4VzNQDv+ryHQObW3TTTp9yB68WpYgRe2bbaGuZ/se74IqFeVnMnLZg==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^2.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/htmlparser2": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",+ "integrity": "sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A==",+ "funding": [+ "https://github.com/fb55/htmlparser2?sponsor=1",+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.0.1",+ "domhandler": "^4.0.0",+ "domutils": "^2.5.2",+ "entities": "^2.0.0"+ }+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/input": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/input/-/input-1.0.1.tgz",+ "integrity": "sha512-5DKQKQ7Nm/CaPGYKF74uUvk5ftC3S04fLYWcDrNG2rOVhhRgB4E2J8JNb7AAh+RlQ/954ukas4bEbrRQ3/kPGA==",+ "license": "MIT",+ "dependencies": {+ "babel-runtime": "^6.6.1",+ "chalk": "^1.1.1",+ "inquirer": "^0.12.0",+ "lodash": "^4.6.1"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/inquirer": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-0.12.0.tgz",+ "integrity": "sha512-bOetEz5+/WpgaW4D1NYOk1aD+JCqRjqu/FwRFgnIfiP7FC/zinsrfyO1vlS3nyH/R7S0IH3BIHBu4DBIDSqiGQ==",+ "license": "MIT",+ "dependencies": {+ "ansi-escapes": "^1.1.0",+ "ansi-regex": "^2.0.0",+ "chalk": "^1.0.0",+ "cli-cursor": "^1.0.1",+ "cli-width": "^2.0.0",+ "figures": "^1.3.5",+ "lodash": "^4.3.0",+ "readline2": "^1.0.1",+ "run-async": "^0.1.0",+ "rx-lite": "^3.1.2",+ "string-width": "^1.0.1",+ "strip-ansi": "^3.0.0",+ "through": "^2.3.6"+ }+ },+ "node_modules/ip-address": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",+ "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/is-buffer": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",+ "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",+ "integrity": "sha512-1pqUqRjkhPJ9miNq9SwMfdvi6lBJcd6eFxvfaivQhaH3SgisfiuudvFntdKOmxuee/77l+FPjKrQjWvmPjWrRw==",+ "license": "MIT",+ "dependencies": {+ "number-is-nan": "^1.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-typedarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",+ "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",+ "license": "MIT"+ },+ "node_modules/level-supports": {+ "version": "6.2.0",+ "resolved": "https://registry.npmjs.org/level-supports/-/level-supports-6.2.0.tgz",+ "integrity": "sha512-QNxVXP0IRnBmMsJIh+sb2kwNCYcKciQZJEt+L1hPCHrKNELllXhvrlClVHXBYZVT+a7aTSM6StgNXdAldoab3w==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/level-transcoder": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/level-transcoder/-/level-transcoder-1.0.1.tgz",+ "integrity": "sha512-t7bFwFtsQeD8cl8NIoQ2iwxA0CL/9IFw7/9gAjOonH0PWTTiRfY7Hq+Ejbsxh86tXobDQ6IOiddjNYIfOBs06w==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^6.0.3",+ "module-error": "^1.0.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "license": "MIT"+ },+ "node_modules/maybe-combine-errors": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/maybe-combine-errors/-/maybe-combine-errors-1.0.0.tgz",+ "integrity": "sha512-eefp6IduNPT6fVdwPp+1NgD0PML1NU5P6j1Mj5nz1nidX8/sWY7119WL8vTAHgqfsY74TzW0w1XPgdYEKkGZ5A==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/mime": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=10.0.0"+ }+ },+ "node_modules/module-error": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/module-error/-/module-error-1.0.2.tgz",+ "integrity": "sha512-0yuvsqSCv8LbaOKhnsQ/T5JhyFlCYLPXK3U2sgV10zoKQwzs/MyfuQUOZQ1V/6OCOJsK/TRgNVrPuPDqtdMFtA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },+ "node_modules/mute-stream": {+ "version": "0.0.5",+ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.5.tgz",+ "integrity": "sha512-EbrziT4s8cWPmzr47eYVW3wimS4HsvlnV5ri1xw1aR6JQo/OrJX5rkl32K/QQHdxeabJETtfeaROGhd8W7uBgg==",+ "license": "ISC"+ },+ "node_modules/napi-macros": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/napi-macros/-/napi-macros-2.2.2.tgz",+ "integrity": "sha512-hmEVtAGYzVQpCKdbQea4skABsdXW4RUh5t5mJ2zzqowJS2OyXZTU1KhDVFhx+NlWZ4ap9mqR9TcDO3LTTttd+g==",+ "license": "MIT"+ },+ "node_modules/next-tick": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz",+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==",+ "license": "ISC"+ },+ "node_modules/node-gyp-build": {+ "version": "4.8.4",+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",+ "license": "MIT",+ "bin": {+ "node-gyp-build": "bin.js",+ "node-gyp-build-optional": "optional.js",+ "node-gyp-build-test": "build-test.js"+ }+ },+ "node_modules/node-localstorage": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-2.2.1.tgz",+ "integrity": "sha512-vv8fJuOUCCvSPjDjBLlMqYMHob4aGjkmrkaE42/mZr0VT+ZAU10jRF8oTnX9+pgU9/vYJ8P7YT3Vd6ajkmzSCw==",+ "license": "MIT",+ "dependencies": {+ "write-file-atomic": "^1.1.4"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/number-is-nan": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz",+ "integrity": "sha512-4jbtZXNAsfZbAHiiqjLPBiCl16dES1zI4Hpzzxw61Tk+loF+sBDBKx1ICKKKwIqQ7M0mFn1TmkN7euSncWgHiQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/onetime": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz",+ "integrity": "sha512-GZ+g4jayMqzCRMgB2sol7GiCLjKfS1PINkjmx8spcKce1LiVqcbQreXwqs2YAFXC6R03VIG28ZS31t8M866v6A==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/pako": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",+ "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",+ "license": "(MIT AND Zlib)"+ },+ "node_modules/path-browserify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",+ "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",+ "license": "MIT"+ },+ "node_modules/playwright": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",+ "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.59.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",+ "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/readline2": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/readline2/-/readline2-1.0.1.tgz",+ "integrity": "sha512-8/td4MmwUB6PkZUbV25uKz7dfrmjYWxsW8DVfibWdlHRk/l/DfHKn4pU+dfcoGLFgWOdyGCzINRQD7jn+Bv+/g==",+ "license": "MIT",+ "dependencies": {+ "code-point-at": "^1.0.0",+ "is-fullwidth-code-point": "^1.0.0",+ "mute-stream": "0.0.5"+ }+ },+ "node_modules/real-cancellable-promise": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/real-cancellable-promise/-/real-cancellable-promise-1.2.3.tgz",+ "integrity": "sha512-hBI5Gy/55VEeeMtImMgEirD7eq5UmqJf1J8dFZtbJZA/3rB0pYFZ7PayMGueb6v4UtUtpKpP+05L0VwyE1hI9Q==",+ "license": "MIT"+ },+ "node_modules/regenerator-runtime": {+ "version": "0.11.1",+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz",+ "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==",+ "license": "MIT"+ },+ "node_modules/restore-cursor": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz",+ "integrity": "sha512-reSjH4HuiFlxlaBaFCiS6O76ZGG2ygKoSlCsipKdaZuKSPx/+bt9mULkn4l0asVzbEfQQmXRg6Wp6gv6m0wElw==",+ "license": "MIT",+ "dependencies": {+ "exit-hook": "^1.0.0",+ "onetime": "^1.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/run-async": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/run-async/-/run-async-0.1.0.tgz",+ "integrity": "sha512-qOX+w+IxFgpUpJfkv2oGN0+ExPs68F4sZHfaRRx4dDexAQkG83atugKVEylyT5ARees3HBbfmuvnjbrd8j9Wjw==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.3.0"+ }+ },+ "node_modules/rx-lite": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-3.1.2.tgz",+ "integrity": "sha512-1I1+G2gteLB8Tkt8YI1sJvSIfa0lWuRtC8GjvtyPBcLSF5jBCCJJqKrpER5JU5r6Bhe+i9/pK3VMuUcXu0kdwQ=="+ },+ "node_modules/slide": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz",+ "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==",+ "license": "ISC",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/smart-buffer": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/socks": {+ "version": "2.8.7",+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",+ "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.0.1",+ "smart-buffer": "^4.2.0"+ },+ "engines": {+ "node": ">= 10.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/store2": {+ "version": "2.14.4",+ "resolved": "https://registry.npmjs.org/store2/-/store2-2.14.4.tgz",+ "integrity": "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw==",+ "license": "MIT"+ },+ "node_modules/string-width": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",+ "integrity": "sha512-0XsVpQLnVCXHJfyEs8tC0zpTVIr5PKKsQtkT29IwupnPTjtPmQ3xT/4yCREF9hYkV/3M3kzcUTSAZT6a6h81tw==",+ "license": "MIT",+ "dependencies": {+ "code-point-at": "^1.0.0",+ "is-fullwidth-code-point": "^1.0.0",+ "strip-ansi": "^3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/strip-ansi": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",+ "integrity": "sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^2.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/supports-color": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",+ "integrity": "sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.0"+ }+ },+ "node_modules/telegram": {+ "version": "2.26.22",+ "resolved": "https://registry.npmjs.org/telegram/-/telegram-2.26.22.tgz",+ "integrity": "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg==",+ "license": "MIT",+ "dependencies": {+ "@cryptography/aes": "^0.1.1",+ "async-mutex": "^0.3.0",+ "big-integer": "^1.6.48",+ "buffer": "^6.0.3",+ "htmlparser2": "^6.1.0",+ "mime": "^3.0.0",+ "node-localstorage": "^2.2.1",+ "pako": "^2.0.3",+ "path-browserify": "^1.0.1",+ "real-cancellable-promise": "^1.1.1",+ "socks": "^2.6.2",+ "store2": "^2.13.0",+ "ts-custom-error": "^3.2.0",+ "websocket": "^1.0.34"+ },+ "optionalDependencies": {+ "bufferutil": "^4.0.3",+ "utf-8-validate": "^5.0.5"+ }+ },+ "node_modules/through": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",+ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",+ "license": "MIT"+ },+ "node_modules/ts-custom-error": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",+ "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type": {+ "version": "2.7.3",+ "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz",+ "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==",+ "license": "ISC"+ },+ "node_modules/typedarray-to-buffer": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz",+ "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==",+ "license": "MIT",+ "dependencies": {+ "is-typedarray": "^1.0.0"+ }+ },+ "node_modules/utf-8-validate": {+ "version": "5.0.10",+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",+ "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },+ "node_modules/websocket": {+ "version": "1.0.35",+ "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz",+ "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "bufferutil": "^4.0.1",+ "debug": "^2.2.0",+ "es5-ext": "^0.10.63",+ "typedarray-to-buffer": "^3.1.5",+ "utf-8-validate": "^5.0.2",+ "yaeti": "^0.0.6"+ },+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/write-file-atomic": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz",+ "integrity": "sha512-SdrHoC/yVBPpV0Xq/mUZQIpW2sWXAShb/V4pomcJXh92RuaO+f3UTWItiR3Px+pLnV2PvC2/bfn5cwr5X6Vfxw==",+ "license": "ISC",+ "dependencies": {+ "graceful-fs": "^4.1.11",+ "imurmurhash": "^0.1.4",+ "slide": "^1.1.5"+ }+ },+ "node_modules/yaeti": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz",+ "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.32"+ }+ }+ }+}diff --git a/claude-ops/package.json b/claude-ops/package.jsonnew file mode 100644index 00000000..721a87ba--- /dev/null+++ b/claude-ops/package.json@@ -0,0 +1,13 @@+{+ "name": "claude-ops-bin",+ "version": "0.2.2",+ "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",+ "dependencies": {+ "classic-level": "^3.0.0",+ "input": "^1.0.1",+ "playwright": "^1.59.1",+ "telegram": "^2.26.22"+ }+}diff --git a/claude-ops/scripts/com.claude-ops.daemon.plist b/claude-ops/scripts/com.claude-ops.daemon.plistnew file mode 100644index 00000000..e0b0a1c1--- /dev/null+++ b/claude-ops/scripts/com.claude-ops.daemon.plist@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.claude-ops.daemon</string>++ <key>ProgramArguments</key>+ <array>+ <string>/bin/bash</string>+ <string>__DAEMON_SCRIPT_PATH__</string>+ </array>++ <key>KeepAlive</key>+ <true/>++ <key>ThrottleInterval</key>+ <integer>30</integer>++ <key>RunAtLoad</key>+ <true/>++ <key>StandardOutPath</key>+ <string>__LOG_DIR__/ops-daemon-stdout.log</string>++ <key>StandardErrorPath</key>+ <string>__LOG_DIR__/ops-daemon-stderr.log</string>++ <key>EnvironmentVariables</key>+ <dict>+ <key>PATH</key>+ <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>+ <key>HOME</key>+ <string>__HOME__</string>+ </dict>+</dict>+</plist>diff --git a/claude-ops/scripts/com.claude-ops.wacli-keepalive.plist b/claude-ops/scripts/com.claude-ops.wacli-keepalive.plistnew file mode 100644index 00000000..5ac3d8e1--- /dev/null+++ b/claude-ops/scripts/com.claude-ops.wacli-keepalive.plist@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.claude-ops.wacli-keepalive</string>++ <key>ProgramArguments</key>+ <array>+ <string>/bin/bash</string>+ <string>__KEEPALIVE_SCRIPT_PATH__</string>+ </array>++ <key>KeepAlive</key>+ <true/>++ <key>ThrottleInterval</key>+ <integer>60</integer>++ <key>RunAtLoad</key>+ <true/>++ <key>StandardOutPath</key>+ <string>__LOG_DIR__/wacli-launchd-stdout.log</string>++ <key>StandardErrorPath</key>+ <string>__LOG_DIR__/wacli-launchd-stderr.log</string>++ <key>EnvironmentVariables</key>+ <dict>+ <key>PATH</key>+ <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>+ <key>HOME</key>+ <string>__HOME__</string>+ </dict>+</dict>+</plist>diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonnew file mode 100644index 00000000..dfa00902--- /dev/null+++ b/claude-ops/scripts/daemon-services.default.json@@ -0,0 +1,18 @@+{+ "services": {+ "wacli-sync": {+ "enabled": true,+ "command": "__SCRIPTS_DIR__/wacli-keepalive.sh",+ "health_file": "~/.wacli/.health",+ "restart_delay": 60,+ "max_restarts": 10+ },+ "memory-extractor": {+ "enabled": true,+ "command": "__SCRIPTS_DIR__/ops-memory-extractor.sh",+ "health_file": "~/.claude/plugins/data/ops-ops-marketplace/memories/.health",+ "restart_delay": 3600,+ "cron": "*/30 * * * *"+ }+ }+}diff --git a/claude-ops/scripts/daemon-services.example.json b/claude-ops/scripts/daemon-services.example.jsonnew file mode 100644index 00000000..64e4cf37--- /dev/null+++ b/claude-ops/scripts/daemon-services.example.json@@ -0,0 +1,49 @@+{+ "_comment": "Copy this file to ~/.claude/plugins/data/ops-ops-marketplace/daemon-services.json and customize.",+ "_variables": {+ "CLAUDE_PLUGIN_ROOT": "Resolved at runtime to the claude-ops plugin install directory",+ "OPS_DATA_DIR": "Override default data dir (~/.claude/plugins/data/ops-ops-marketplace)"+ },+ "services": {+ "wacli-sync": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/wacli-keepalive.sh",+ "health_file": "~/.wacli/health.txt",+ "restart_delay": 60,+ "max_restarts": 10+ },+ "inbox-digest": {+ "enabled": false,+ "cron": "0 */4 * * *",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-inbox-digest.sh",+ "_note": "Requires: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID env vars. Uses gog for email."+ },+ "store-health": {+ "enabled": false,+ "cron": "0 9 * * *",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-store-health.sh",+ "_note": "Requires: SHOPIFY_STOREFRONT_TOKEN, SHOPIFY_STORE_DOMAIN, TELEGRAM_BOT_TOKEN"+ },+ "competitor-intel": {+ "enabled": false,+ "cron": "0 10 * * 1",+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-intel.sh",+ "_note": "Requires: TELEGRAM_BOT_TOKEN. Optional: TAVILY_API_KEY for better search results."+ },+ "message-listener": {+ "enabled": false,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-message-listener.sh",+ "health_file": "~/.claude/plugins/data/ops-ops-marketplace/listener-health.txt",+ "restart_delay": 30,+ "max_restarts": 20,+ "_note": "Requires: wacli installed. Optional: TELEGRAM_BOT_TOKEN, TELEGRAM_OWNER_ID."+ },+ "memory-extractor": {+ "enabled": false,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-memory-extractor.sh",+ "health_file": "~/.claude/plugins/data/ops-ops-marketplace/memories/.health",+ "restart_delay": 3600,+ "cron": "*/30 * * * *"+ }+ }+}diff --git a/claude-ops/scripts/ops-cron-competitor-intel.sh b/claude-ops/scripts/ops-cron-competitor-intel.shnew file mode 100755index 00000000..2cd4b496--- /dev/null+++ b/claude-ops/scripts/ops-cron-competitor-intel.sh@@ -0,0 +1,101 @@+#!/usr/bin/env bash+# ops-cron-competitor-intel.sh — Weekly Competitor Intel cron job+# Searches competitors and own brand reviews, reports to Telegram+# Configure via env vars: COMPETITOR_A_QUERY, COMPETITOR_B_QUERY, BRAND_QUERY, REPORT_TIMEZONE+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/competitor-intel.log"++mkdir -p "$LOG_DIR"+log() { printf '%s [competitor-intel] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++# ── Resolve credentials ───────────────────────────────────────────────────+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++YEAR=$(date +%Y)+FINDINGS=()++# ── Search function via Tavily (or fallback curl) ─────────────────────────+search_web() {+ local query="$1"+ local label="$2"+ local result=""++ if [[ -n "$TAVILY_KEY" ]]; then+ result=$(curl -s -X POST "https://api.tavily.com/search" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer ${TAVILY_KEY}" \+ -d "{\"query\": \"$query\", \"max_results\": 3, \"search_depth\": \"basic\"}" \+ 2>/dev/null | python3 -c "+import json, sys+data = json.load(sys.stdin)+results = data.get('results', [])+if not results:+ print('No results found')+else:+ snippets = [r.get('title','') + ': ' + r.get('content','')[:120] for r in results[:2]]+ print(' | '.join(snippets))+" 2>/dev/null || echo "search unavailable")+ else+ # Fallback: SerpAPI-compatible curl search via DuckDuckGo HTML (best-effort)+ result=$(curl -s -A "Mozilla/5.0" \+ "https://html.duckduckgo.com/html/?q=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote('$query'))")" \+ 2>/dev/null | python3 -c "+import sys, re+html = sys.stdin.read()+titles = re.findall(r'class=\"result__title\"[^>]*>.*?<a[^>]*>(.*?)</a>', html, re.DOTALL)+clean = [re.sub('<[^>]+>','',t).strip() for t in titles[:3]]+print(' | '.join(clean[:2]) if clean else 'No results')+" 2>/dev/null || echo "search unavailable")+ fi++ log "Search [$label]: ${result:0:100}..."+ echo "$result"+}++# ── Run searches ──────────────────────────────────────────────────────────+log "Running weekly competitor intelligence searches"++COMPETITOR_A_RESULT=$(search_web "${COMPETITOR_A_QUERY:-competitor-a reviews $YEAR}" "Competitor A")+COMPETITOR_B_RESULT=$(search_web "${COMPETITOR_B_QUERY:-competitor-b new products $YEAR}" "Competitor B")+BRAND_RESULT=$(search_web "${BRAND_QUERY:-your-brand reviews $YEAR}" "Brand mentions")++# ── Build report ──────────────────────────────────────────────────────────+DATE_LABEL=$(TZ="${REPORT_TIMEZONE:-UTC}" date "+%a %d %b %Y")+REPORT="*Weekly Competitor Intel* ($DATE_LABEL)++*Competitor A:*+$COMPETITOR_A_RESULT++*Competitor B:*+$COMPETITOR_B_RESULT++*Brand Mentions:*+$BRAND_RESULT"++log "Report built — sending to Telegram"++# ── Send to Telegram ──────────────────────────────────────────────────────+if [[ -n "$TELEGRAM_TOKEN" ]]; then+ curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \+ -H "Content-Type: application/json" \+ -d "{\"chat_id\": \"$TELEGRAM_CHAT\", \"text\": $(echo "$REPORT" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'), \"parse_mode\": \"Markdown\"}" \+ >> "$LOG" 2>&1+ log "Competitor intel sent to Telegram chat=$TELEGRAM_CHAT"+else+ log "WARN: TELEGRAM_BOT_TOKEN not set — printing report to stdout"+ echo "$REPORT"+fi++log "HEARTBEAT_OK"diff --git a/claude-ops/scripts/ops-cron-inbox-digest.sh b/claude-ops/scripts/ops-cron-inbox-digest.shnew file mode 100755index 00000000..af6a2eb8--- /dev/null+++ b/claude-ops/scripts/ops-cron-inbox-digest.sh@@ -0,0 +1,99 @@+#!/usr/bin/env bash+# ops-cron-inbox-digest.sh — 4h Inbox Digest cron job+# Scans unread WhatsApp messages + email, sends digest to Telegram+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/inbox-digest.log"+WACLI="${WACLI_BIN:-$(command -v wacli 2>/dev/null || echo /usr/local/bin/wacli)}"++mkdir -p "$LOG_DIR"+log() { printf '%s [inbox-digest] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++# ── Resolve Telegram token ────────────────────────────────────────────────+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++# ── Gather WhatsApp unread count ──────────────────────────────────────────+WA_SUMMARY="WhatsApp: unavailable"+if command -v wacli &>/dev/null || [[ -x "$WACLI" ]]; then+ SINCE=$(date -u -v-4H "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u -d "4 hours ago" "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u "+%Y-%m-%dT%H:%M:%SZ")+ WA_RAW=$("$WACLI" messages list --after="$SINCE" --limit 20 --json 2>/dev/null || echo "[]")+ WA_COUNT=$(echo "$WA_RAW" | python3 -c "+import json, sys+msgs = json.load(sys.stdin)+# Filter out messages from owner (from_me=true)+unread = [m for m in msgs if not m.get('from_me', False)]+print(len(unread))+" 2>/dev/null || echo "0")++ if [[ "$WA_COUNT" == "0" ]]; then+ WA_SUMMARY="WhatsApp: geen nieuwe berichten"+ else+ WA_SENDERS=$(echo "$WA_RAW" | python3 -c "+import json, sys+msgs = json.load(sys.stdin)+unread = [m for m in msgs if not m.get('from_me', False)]+senders = list({m.get('contact_name', m.get('from', 'unknown')) for m in unread})[:5]+print(', '.join(senders))+" 2>/dev/null || echo "unknown")+ WA_SUMMARY="WhatsApp: $WA_COUNT unread from $WA_SENDERS"+ fi+fi++# ── Gather email unread count via gog ────────────────────────────────────+EMAIL_SUMMARY="Email: unavailable"+GOG_RAW=$(command -v gog &>/dev/null && gog gmail search "is:unread after:$(date -u -v-4H +%Y/%m/%d 2>/dev/null || date -u -d '4 hours ago' +%Y/%m/%d 2>/dev/null || date -u +%Y/%m/%d)" --json 2>/dev/null || echo "[]")+EMAIL_COUNT=$(echo "$GOG_RAW" | python3 -c "+import json, sys+data = json.load(sys.stdin)+print(len(data) if isinstance(data, list) else 0)+" 2>/dev/null || echo "0")++if [[ "$EMAIL_COUNT" == "0" ]]; then+ EMAIL_SUMMARY="Email: geen nieuwe berichten"+else+ EMAIL_SUBJECTS=$(echo "$GOG_RAW" | python3 -c "+import json, sys+data = json.load(sys.stdin)+subjects = [m.get('subject', '')[:50] for m in (data if isinstance(data, list) else [])[:3]]+print('\n - '.join(subjects))+" 2>/dev/null || echo "")+ EMAIL_SUMMARY="Email: $EMAIL_COUNT unread"+ [[ -n "$EMAIL_SUBJECTS" ]] && EMAIL_SUMMARY="$EMAIL_SUMMARY+ - $EMAIL_SUBJECTS"+fi++# ── Build digest ──────────────────────────────────────────────────────────+TIMESTAMP=$(TZ="Europe/Amsterdam" date "+%H:%M %Z")+DIGEST="*4h Inbox Digest* ($TIMESTAMP)++$WA_SUMMARY+$EMAIL_SUMMARY"++# ── Check if anything actionable ─────────────────────────────────────────+if [[ "$WA_SUMMARY" == *"geen nieuwe berichten"* ]] && [[ "$EMAIL_SUMMARY" == *"geen nieuwe berichten"* ]]; then+ log "No new messages — skipping Telegram notification (HEARTBEAT_OK)"+ exit 0+fi++log "Sending digest: WA=$WA_COUNT email=$EMAIL_COUNT"++# ── Send to Telegram ──────────────────────────────────────────────────────+if [[ -n "$TELEGRAM_TOKEN" ]]; then+ curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \+ -H "Content-Type: application/json" \+ -d "{\"chat_id\": \"$TELEGRAM_CHAT\", \"text\": $(echo "$DIGEST" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'), \"parse_mode\": \"Markdown\"}" \+ >> "$LOG" 2>&1+ log "Digest sent to Telegram chat=$TELEGRAM_CHAT"+else+ log "WARN: TELEGRAM_BOT_TOKEN not set — digest not sent"+ echo "$DIGEST"+fi++log "HEARTBEAT_OK"diff --git a/claude-ops/scripts/ops-cron-store-health.sh b/claude-ops/scripts/ops-cron-store-health.shnew file mode 100755index 00000000..2e853b13--- /dev/null+++ b/claude-ops/scripts/ops-cron-store-health.sh@@ -0,0 +1,111 @@+#!/usr/bin/env bash+# ops-cron-store-health.sh — Daily Store Health cron job+# Queries Shopify API, reports inventory status to Telegram+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/store-health.log"+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/ops-marketplace/claude-ops}"++mkdir -p "$LOG_DIR"+log() { printf '%s [store-health] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++# ── Resolve credentials ───────────────────────────────────────────────────+SHOPIFY_STORE="${SHOPIFY_STORE_DOMAIN:-}"+SHOPIFY_TOKEN="${SHOPIFY_STOREFRONT_TOKEN:-}"+TELEGRAM_TOKEN="${TELEGRAM_BOT_TOKEN:-}"+TELEGRAM_CHAT="${TELEGRAM_CHAT_ID:-}"+LOW_STOCK_THRESHOLD="${LOW_STOCK_THRESHOLD:-20}"++if [[ -z "$SHOPIFY_TOKEN" ]]; then+ SHOPIFY_TOKEN=$(doppler secrets get SHOPIFY_STOREFRONT_TOKEN --plain 2>/dev/null || true)+fi+if [[ -z "$SHOPIFY_STORE" ]]; then+ SHOPIFY_STORE=$(doppler secrets get SHOPIFY_STORE_DOMAIN --plain 2>/dev/null || true)+fi+if [[ -z "$TELEGRAM_TOKEN" ]]; then+ TELEGRAM_TOKEN=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)+fi++# ── Try bin/ops-ecom-health first ─────────────────────────────────────────+ECOM_HEALTH_BIN="$PLUGIN_ROOT/bin/ops-ecom-health"+if [[ -x "$ECOM_HEALTH_BIN" ]]; then+ log "Running ops-ecom-health bin"+ HEALTH_OUTPUT=$("$ECOM_HEALTH_BIN" --json 2>/dev/null || "$ECOM_HEALTH_BIN" 2>/dev/null || true)+ if [[ -n "$HEALTH_OUTPUT" ]]; then+ log "ops-ecom-health output received"+ REPORT="$HEALTH_OUTPUT"+ fi+fi++# ── Fallback: direct Shopify Storefront API call ──────────────────────────+if [[ -z "${REPORT:-}" ]]; then+ if [[ -z "$SHOPIFY_TOKEN" ]]; then+ log "ERROR: SHOPIFY_STOREFRONT_TOKEN not set and ops-ecom-health unavailable"+ exit 1+ fi++ log "Querying Shopify Storefront API: $SHOPIFY_STORE"+ INVENTORY_JSON=$(curl -s -X POST \+ "https://${SHOPIFY_STORE}/api/2024-04/graphql.json" \+ -H "X-Shopify-Storefront-Access-Token: ${SHOPIFY_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{"query": "{ products(first: 10) { edges { node { title variants(first: 10) { edges { node { title quantityAvailable availableForSale } } } } } } }"}' \+ 2>/dev/null || echo '{"errors":[{"message":"request failed"}]}')++ REPORT=$(echo "$INVENTORY_JSON" | python3 -c "+import json, sys+data = json.load(sys.stdin)++if 'errors' in data:+ print('Store Health: ERROR — ' + data['errors'][0].get('message', 'unknown'))+ sys.exit(0)++products = data.get('data', {}).get('products', {}).get('edges', [])+threshold = int('${LOW_STOCK_THRESHOLD}')+lines = ['*Daily Store Health*', '']+low_stock = []+all_ok = []++for p in products:+ node = p['node']+ name = node['title']+ for v in node.get('variants', {}).get('edges', []):+ vn = v['node']+ qty = vn.get('quantityAvailable') or 0+ avail = vn.get('availableForSale', False)+ label = vn['title'] if vn['title'] != 'Default Title' else ''+ display = f'{name}' + (f' — {label}' if label else '')+ if qty < threshold or not avail:+ low_stock.append(f' LOW: {display} ({qty} units)')+ else:+ all_ok.append(f' OK: {display} ({qty} units)')++if low_stock:+ lines.append('*LOW STOCK ALERTS:*')+ lines.extend(low_stock)+ lines.append('')+lines.append('*In Stock:*')+lines.extend(all_ok[:5])+if len(all_ok) > 5:+ lines.append(f' ...and {len(all_ok)-5} more')+print('\n'.join(lines))+" 2>/dev/null || echo "Store Health: failed to parse inventory response")+fi++log "Report generated — sending to Telegram"++# ── Send to Telegram ──────────────────────────────────────────────────────+if [[ -n "$TELEGRAM_TOKEN" ]]; then+ curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage" \+ -H "Content-Type: application/json" \+ -d "{\"chat_id\": \"$TELEGRAM_CHAT\", \"text\": $(echo "$REPORT" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'), \"parse_mode\": \"Markdown\"}" \+ >> "$LOG" 2>&1+ log "Store health sent to Telegram chat=$TELEGRAM_CHAT"+else+ log "WARN: TELEGRAM_BOT_TOKEN not set — printing report to stdout"+ echo "$REPORT"+fi++log "HEARTBEAT_OK"diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.shnew file mode 100755index 00000000..3e07227f--- /dev/null+++ b/claude-ops/scripts/ops-daemon.sh@@ -0,0 +1,687 @@+#!/usr/bin/env bash+# ops-daemon.sh — Unified background process manager for claude-ops+# Manages: wacli sync, memory extraction, health monitors+# Runs via launchd as com.claude-ops.daemon+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/ops-daemon.log"+SERVICES_CONFIG="$DATA_DIR/daemon-services.json"+HEALTH_FILE="$DATA_DIR/daemon-health.json"+MAX_LOG_SIZE=2097152 # 2MB+DAEMON_START=$(date +%s)++mkdir -p "$LOG_DIR"+mkdir -p "$DATA_DIR/cache"++# ── Logging ──────────────────────────────────────────────────────────────+log() { printf '%s [ops-daemon] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"; }++rotate_log() {+ if [[ -f "$LOG" ]] && [[ $(stat -f%z "$LOG" 2>/dev/null || stat -c%s "$LOG" 2>/dev/null || echo 0) -gt $MAX_LOG_SIZE ]]; then+ mv "$LOG" "$LOG.old"+ log "LOG: rotated (exceeded 2MB)"+ fi+}++# ── State tracking ────────────────────────────────────────────────────────+declare -A SERVICE_PIDS # service name → pid+declare -A SERVICE_RESTARTS # service name → restart count+declare -A SERVICE_NEXT_RUN # service name → next run epoch (cron services)+declare -A SERVICE_LAST_RUN # service name → last run epoch (cron services)+declare -A SERVICE_STATUS # service name → status string+declare -A SERVICE_LAST_HEALTH # service name → last health string+ACTION_NEEDED="null"++# ── Config loading ────────────────────────────────────────────────────────+load_services_config() {+ if [[ ! -f "$SERVICES_CONFIG" ]]; then+ log "CONFIG: $SERVICES_CONFIG not found — nothing to manage"+ return 1+ fi+ log "CONFIG: loaded $SERVICES_CONFIG"+ return 0+}++# Parse a value from the JSON config for a given service + key.+# Uses python3 for reliable JSON parsing.+get_service_field() {+ local service="$1" field="$2"+ python3 -c "+import json, sys+data = json.load(open('$SERVICES_CONFIG'))+svc = data.get('services', {}).get('$service', {})+val = svc.get('$field', '')+print(val if val is not None else '')+" 2>/dev/null || true+}++get_enabled_services() {+ python3 -c "+import json+data = json.load(open('$SERVICES_CONFIG'))+for name, cfg in data.get('services', {}).items():+ if cfg.get('enabled', False):+ print(name)+" 2>/dev/null || true+}++# ── Cron helpers ─────────────────────────────────────────────────────────+# Parse a simple cron expression (*/N * * * *) and return next epoch.+# Only supports */N minute fields — sufficient for daemon use cases.+calc_next_run() {+ local cron="$1"+ local interval_min+ interval_min=$(echo "$cron" | python3 -c "+import sys, re+expr = sys.stdin.read().strip()+m = re.match(r'^\*/(\d+)\s+\*\s+\*\s+\*\s+\*$', expr)+if m:+ print(int(m.group(1)) * 60)+else:+ print(3600)+" 2>/dev/null || echo 3600)+ echo $(( $(date +%s) + interval_min ))+}++# ── Service lifecycle ─────────────────────────────────────────────────────+start_service() {+ local name="$1"+ local cmd+ cmd=$(get_service_field "$name" "command")+ if [[ -z "$cmd" ]]; then+ log "START: $name — no command configured, skipping"+ return 1+ fi++ log "START: launching $name — $cmd"+ # Export daemon identity so child scripts can detect they're managed+ export OPS_DAEMON_PID=$$+ export OPS_DAEMON_MANAGED=1++ bash "$cmd" >> "$LOG_DIR/${name}.log" 2>&1 &+ local pid=$!+ SERVICE_PIDS["$name"]=$pid+ SERVICE_STATUS["$name"]="running"+ SERVICE_LAST_HEALTH["$name"]="starting"+ log "START: $name launched pid=$pid"+}++stop_service() {+ local name="$1"+ local pid="${SERVICE_PIDS[$name]:-}"+ if [[ -z "$pid" ]] || ! kill -0 "$pid" 2>/dev/null; then+ SERVICE_PIDS["$name"]=""+ return 0+ fi+ log "STOP: sending SIGTERM to $name pid=$pid"+ kill -TERM "$pid" 2>/dev/null || true+ local waited=0+ while kill -0 "$pid" 2>/dev/null && [[ $waited -lt 5 ]]; do+ sleep 1+ (( waited++ )) || true+ done+ if kill -0 "$pid" 2>/dev/null; then+ log "STOP: $name pid=$pid did not exit — sending SIGKILL"+ kill -KILL "$pid" 2>/dev/null || true+ fi+ SERVICE_PIDS["$name"]=""+ SERVICE_STATUS["$name"]="stopped"+ log "STOP: $name stopped"+}++check_health() {+ local name="$1"+ local health_path+ health_path=$(get_service_field "$name" "health_file")+ health_path="${health_path/#\~/$HOME}"++ # Check if PID is alive+ local pid="${SERVICE_PIDS[$name]:-}"+ if [[ -n "$pid" ]] && ! kill -0 "$pid" 2>/dev/null; then+ log "HEALTH: $name pid=$pid is dead"+ SERVICE_STATUS["$name"]="dead"+ SERVICE_PIDS["$name"]=""+ return 1+ fi++ # Read health file if present+ if [[ -n "$health_path" ]] && [[ -f "$health_path" ]]; then+ local file_status+ file_status=$(grep -E '^status=' "$health_path" 2>/dev/null | cut -d= -f2- || echo "unknown")+ SERVICE_LAST_HEALTH["$name"]="$file_status"++ case "$file_status" in+ needs_reauth|needs_auth)+ ACTION_NEEDED="{\"service\": \"$name\", \"action\": \"reauth\"}"+ SERVICE_STATUS["$name"]="needs_reauth"+ log "HEALTH: $name needs reauth — action surfaced"+ return 1+ ;;+ connected|running|ok)+ SERVICE_STATUS["$name"]="running"+ ;;+ *)+ SERVICE_STATUS["$name"]="${file_status:-running}"+ ;;+ esac+ fi++ return 0+}++restart_service() {+ local name="$1"+ local restart_delay max_restarts+ restart_delay=$(get_service_field "$name" "restart_delay")+ restart_delay="${restart_delay:-60}"+ max_restarts=$(get_service_field "$name" "max_restarts")+ max_restarts="${max_restarts:-10}"++ local count="${SERVICE_RESTARTS[$name]:-0}"+ if [[ $count -ge $max_restarts ]]; then+ log "RESTART: $name hit max_restarts=$max_restarts — not restarting"+ SERVICE_STATUS["$name"]="max_restarts_exceeded"+ return+ fi++ SERVICE_RESTARTS["$name"]=$(( count + 1 ))+ log "RESTART: $name (attempt $((count+1))/$max_restarts) — waiting ${restart_delay}s"+ # Non-blocking: schedule restart by marking it, actual start happens in main loop+ # For simplicity, stop and re-start after the delay inline (daemon loop is 30s anyway)+ stop_service "$name"+ sleep "${restart_delay}" &+ # We record the sleep PID to avoid blocking; restart happens next health check after delay+ # Use a simpler approach: just restart immediately (launchd handles overall throttle)+ start_service "$name"+}++# ── Write aggregated health JSON ──────────────────────────────────────────+write_daemon_health() {+ local now+ now=$(date -u +%Y-%m-%dT%H:%M:%SZ)+ local uptime=$(( $(date +%s) - DAEMON_START ))++ # Build services JSON object+ local services_json="{"+ local first=1+ local name+ for name in "${!SERVICE_STATUS[@]}"; do+ local cron+ cron=$(get_service_field "$name" "cron")+ local status="${SERVICE_STATUS[$name]}"+ local pid="${SERVICE_PIDS[$name]:-null}"+ local restarts="${SERVICE_RESTARTS[$name]:-0}"+ local health="${SERVICE_LAST_HEALTH[$name]:-unknown}"++ [[ $first -eq 0 ]] && services_json+=","+ first=0++ if [[ -n "$cron" ]]; then+ local next_run="${SERVICE_NEXT_RUN[$name]:-}"+ local last_run="${SERVICE_LAST_RUN[$name]:-}"+ local next_iso="" last_iso=""+ [[ -n "$next_run" ]] && next_iso=$(date -u -r "$next_run" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d "@$next_run" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "")+ [[ -n "$last_run" ]] && last_iso=$(date -u -r "$last_run" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d "@$last_run" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "")+ services_json+="\"$name\": {\"status\": \"$status\", \"next_run\": \"$next_iso\", \"last_run\": \"$last_iso\"}"+ else+ local pid_val+ if [[ "$pid" == "null" ]] || [[ -z "$pid" ]]; then+ pid_val="null"+ else+ pid_val="$pid"+ fi+ services_json+="\"$name\": {\"status\": \"$status\", \"pid\": $pid_val, \"last_health\": \"$health\", \"restarts\": $restarts}"+ fi+ done+ services_json+="}"++ # Read brain cache metadata+ local brain_briefing_cached_at=""+ local brain_urgent_count=0+ local brain_last_memory_extraction=""++ if [[ -f "$DATA_DIR/cache/briefing.json" ]]; then+ brain_briefing_cached_at=$(python3 -c "+import json+try: print(json.load(open('$DATA_DIR/cache/briefing.json')).get('cached_at',''))+except: print('')+" 2>/dev/null || true)+ fi++ if [[ -f "$DATA_DIR/cache/urgent.json" ]]; then+ brain_urgent_count=$(python3 -c "+import json+try: print(json.load(open('$DATA_DIR/cache/urgent.json')).get('urgent_count',0))+except: print(0)+" 2>/dev/null || echo 0)+ fi++ if [[ -f "$DATA_DIR/memories/.health" ]]; then+ brain_last_memory_extraction=$(python3 -c "+import json+try: print(json.load(open('$DATA_DIR/memories/.health')).get('timestamp',''))+except: print('')+" 2>/dev/null || true)+ fi++ cat > "$HEALTH_FILE" <<EOF+{+ "timestamp": "$now",+ "pid": $$,+ "uptime_seconds": $uptime,+ "services": $services_json,+ "action_needed": $ACTION_NEEDED,+ "brain": {+ "briefing_cached_at": "$brain_briefing_cached_at",+ "urgent_count": $brain_urgent_count,+ "last_memory_extraction": "$brain_last_memory_extraction"+ }+}+EOF+}++# ── Cron service runner ───────────────────────────────────────────────────+run_cron_service() {+ local name="$1"+ local cmd+ cmd=$(get_service_field "$name" "command")+ if [[ -z "$cmd" ]]; then return; fi++ log "CRON: running $name"+ SERVICE_STATUS["$name"]="running"+ SERVICE_LAST_RUN["$name"]=$(date +%s)++ export OPS_DAEMON_PID=$$+ export OPS_DAEMON_MANAGED=1+ bash "$cmd" >> "$LOG_DIR/${name}.log" 2>&1 &+ local pid=$!+ wait "$pid" 2>/dev/null || true++ SERVICE_STATUS["$name"]="scheduled"+ local cron+ cron=$(get_service_field "$name" "cron")+ SERVICE_NEXT_RUN["$name"]=$(calc_next_run "$cron")+ log "CRON: $name completed — next run in $(( SERVICE_NEXT_RUN[$name] - $(date +%s) ))s"+}++# ── Intelligence functions (smart brain) ─────────────────────────────────++# Pre-compute morning briefing data so ops-go loads instantly.+prefetch_briefing_cache() {+ local CACHE_DIR="$DATA_DIR/cache"+ mkdir -p "$CACHE_DIR"+ local CACHE="$CACHE_DIR/briefing.json"+ local LAST_FETCH="$CACHE_DIR/.briefing_ts"++ # Throttle: only run every 5 min+ if [[ -f "$LAST_FETCH" ]]; then+ local last+ last=$(cat "$LAST_FETCH")+ local now+ now=$(date +%s)+ if (( now - last < 300 )); then return 0; fi+ fi++ log "BRAIN: refreshing briefing cache"++ local tmpdir+ tmpdir=$(mktemp -d)++ # Unread counts+ (command -v wacli &>/dev/null && wacli chats list --json 2>/dev/null | python3 -c "+import json,sys,datetime+data=json.load(sys.stdin).get('data',[]) or []+cutoff=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(days=7)).isoformat()+recent=[c for c in data if c.get('LastMessageTS','')>cutoff]+print(json.dumps({'total_chats':len(recent),'count':len(data)}))+" > "$tmpdir/wa.json" 2>/dev/null) &++ # Email count+ (command -v gog &>/dev/null && gog gmail search -j --results-only --no-input --max 10 "in:inbox is:unread" 2>/dev/null | python3 -c "+import json,sys+data=json.load(sys.stdin)+print(json.dumps({'unread_count':len(data)}))+" > "$tmpdir/email.json" 2>/dev/null) &++ # Open PRs+ (command -v gh &>/dev/null && gh pr list --json number,title,headRefName,createdAt --limit 20 2>/dev/null > "$tmpdir/prs.json") &++ # Projects placeholder with timestamp+ (python3 -c "+import json+print(json.dumps({'cached_at':'$(date -u +%Y-%m-%dT%H:%M:%SZ)'}))+" > "$tmpdir/projects.json" 2>/dev/null) &++ wait++ # Merge all into briefing cache+ python3 -c "+import json, os, glob+result = {}+for f in glob.glob('$tmpdir/*.json'):+ try:+ with open(f) as fh:+ result[os.path.basename(f).replace('.json','')] = json.load(fh)+ except: pass+result['cached_at'] = '$(date -u +%Y-%m-%dT%H:%M:%SZ)'+with open('$CACHE', 'w') as fh:+ json.dump(result, fh, indent=2)+" 2>/dev/null || true++ rm -rf "$tmpdir"+ date +%s > "$LAST_FETCH"+ log "BRAIN: briefing cache updated"+}++# Check for messages that might need immediate attention.+detect_urgent_messages() {+ local URGENT_FILE="$DATA_DIR/cache/urgent.json"+ local LAST_CHECK="$DATA_DIR/cache/.urgent_ts"++ # Throttle: every 5 min+ if [[ -f "$LAST_CHECK" ]]; then+ local last+ last=$(cat "$LAST_CHECK")+ local now+ now=$(date +%s)+ if (( now - last < 300 )); then return 0; fi+ fi++ # Check WhatsApp for messages with urgent keywords (skip if wacli unavailable)+ if command -v wacli &>/dev/null; then+ wacli messages search --query "urgent OR asap OR deadline OR emergency OR ASAP" --json 2>/dev/null | python3 -c "+import json,sys,datetime+data=json.load(sys.stdin)+msgs=data.get('data',{}).get('messages',[]) or []+cutoff=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(hours=4)).isoformat()+urgent=[m for m in msgs if m.get('Timestamp','')>cutoff and not m.get('FromMe',True)]+if urgent:+ with open('$URGENT_FILE','w') as f:+ json.dump({'urgent_count':len(urgent),'messages':[{'from':m.get('ChatName',''),'text':m.get('Text','')[:100],'ts':m.get('Timestamp','')} for m in urgent[:5]]},f,indent=2)+" 2>/dev/null || true+ fi++ date +%s > "$LAST_CHECK"+}++# Trigger memory extraction early when new high-value messages arrive.+trigger_smart_memory_extraction() {+ local MEMORY_TRIGGER="$DATA_DIR/cache/.memory_trigger_ts"+ local MEM_SCRIPT="${CLAUDE_PLUGIN_ROOT:-$(dirname "$0")}/scripts/ops-memory-extractor.sh"++ # Only check every 10 min+ if [[ -f "$MEMORY_TRIGGER" ]]; then+ local last+ last=$(cat "$MEMORY_TRIGGER")+ local now+ now=$(date +%s)+ if (( now - last < 600 )); then return 0; fi+ fi++ # Check if new messages arrived since last extraction+ local last_extraction="$DATA_DIR/memories/.health"+ if [[ -f "$last_extraction" ]]; then+ local last_ts+ last_ts=$(python3 -c "+import json+try:+ d=json.load(open('$last_extraction'))+ print(d.get('timestamp',''))+except: print('')+" 2>/dev/null)++ if command -v wacli &>/dev/null; then+ local new_count+ new_count=$(wacli messages list --after="${last_ts:-$(date -v-1d +%Y-%m-%d 2>/dev/null || date -d 'yesterday' +%Y-%m-%d 2>/dev/null || echo '')}" --limit=5 --json 2>/dev/null | python3 -c "+import json,sys+d=json.load(sys.stdin)+msgs=d.get('data',{}).get('messages',[]) or []+print(len(msgs))+" 2>/dev/null || echo 0)++ if [[ "$new_count" -gt 3 ]] && [[ -f "$MEM_SCRIPT" ]]; then+ log "BRAIN: $new_count new messages since last extraction — triggering memory update"+ bash "$MEM_SCRIPT" >> "$LOG_DIR/memory-extractor.log" 2>&1 &+ fi+ fi+ fi++ date +%s > "$MEMORY_TRIGGER"+}++# Cross-channel contact activity — track who's active across WA + email + Slack+build_contact_activity_index() {+ local CONTACT_INDEX="$DATA_DIR/cache/contacts_active.json"+ local LAST_BUILD="$DATA_DIR/cache/.contacts_ts"++ # Every 15 min+ if [[ -f "$LAST_BUILD" ]]; then+ local last; last=$(cat "$LAST_BUILD")+ if (( $(date +%s) - last < 900 )); then return 0; fi+ fi++ log "BRAIN: building cross-channel contact activity index"++ python3 - "$DATA_DIR" <<'PYEOF' 2>/dev/null || true+import json, subprocess, sys, datetime, os, collections++data_dir = sys.argv[1]+contacts = collections.defaultdict(lambda: {"channels": [], "last_seen": "", "msg_count": 0, "needs_reply": False})++# WhatsApp contacts+try:+ wa = json.loads(subprocess.check_output(["wacli", "chats", "list", "--json"], timeout=10, stderr=subprocess.DEVNULL))+ cutoff = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=7)).isoformat()+ for chat in (wa.get("data") or []):+ if chat.get("LastMessageTS", "") < cutoff: continue+ name = chat.get("Name", "Unknown")+ contacts[name]["channels"].append("whatsapp")+ contacts[name]["last_seen"] = max(contacts[name]["last_seen"], chat.get("LastMessageTS", ""))+ contacts[name]["jid"] = chat.get("JID", "")+except: pass++# Email contacts (recent senders)+try:+ em = json.loads(subprocess.check_output(+ ["gog", "gmail", "search", "-j", "--results-only", "--no-input", "--max", "20", "in:inbox newer_than:3d"],+ timeout=15, stderr=subprocess.DEVNULL+ ))+ for thread in (em or []):+ sender = thread.get("from", "")+ name = sender.split("<")[0].strip().strip('"')+ if name:+ contacts[name]["channels"].append("email")+ contacts[name]["email"] = sender+ contacts[name]["last_seen"] = max(contacts[name]["last_seen"], thread.get("date", ""))+except: pass++# Merge with existing memories+mem_dir = os.path.join(data_dir, "memories")+if os.path.isdir(mem_dir):+ for f in os.listdir(mem_dir):+ if f.startswith("contact_") and f.endswith(".md"):+ name = f.replace("contact_", "").replace(".md", "").replace("_", " ").title()+ if name in contacts:+ contacts[name]["has_memory"] = True++# Score: multi-channel contacts rank higher+scored = []+for name, info in contacts.items():+ info["name"] = name+ info["channels"] = list(set(info["channels"]))+ info["score"] = len(info["channels"]) * 2 + info["msg_count"]+ scored.append(info)++scored.sort(key=lambda x: (len(x["channels"]), x["last_seen"]), reverse=True)++with open(os.path.join(data_dir, "cache", "contacts_active.json"), "w") as f:+ json.dump({"updated": datetime.datetime.now(datetime.timezone.utc).isoformat(), "contacts": scored[:50]}, f, indent=2)+PYEOF++ date +%s > "$LAST_BUILD"+ log "BRAIN: contact activity index built"+}++# Calendar context — pre-fetch today's meetings so skills know what's coming+prefetch_calendar() {+ local CAL_CACHE="$DATA_DIR/cache/calendar_today.json"+ local LAST_FETCH="$DATA_DIR/cache/.calendar_ts"++ # Every 15 min+ if [[ -f "$LAST_FETCH" ]]; then+ local last; last=$(cat "$LAST_FETCH")+ if (( $(date +%s) - last < 900 )); then return 0; fi+ fi++ if command -v gog &>/dev/null; then+ log "BRAIN: refreshing calendar cache"+ gog cal list -j --no-input --days 1 > "$CAL_CACHE" 2>/dev/null || echo '[]' > "$CAL_CACHE"+ date +%s > "$LAST_FETCH"+ fi+}++# Project health snapshot — git status + CI for registered repos+prefetch_project_health() {+ local PROJ_CACHE="$DATA_DIR/cache/projects_health.json"+ local LAST_FETCH="$DATA_DIR/cache/.projects_ts"+ local REGISTRY="${CLAUDE_PLUGIN_ROOT:-$(dirname "$0")/../}/scripts/registry.json"++ # Every 10 min+ if [[ -f "$LAST_FETCH" ]]; then+ local last; last=$(cat "$LAST_FETCH")+ if (( $(date +%s) - last < 600 )); then return 0; fi+ fi++ if [[ ! -f "$REGISTRY" ]]; then return 0; fi++ log "BRAIN: refreshing project health cache"++ python3 - "$REGISTRY" "$PROJ_CACHE" <<'PYEOF' 2>/dev/null || true+import json, subprocess, sys, os++registry_path, output_path = sys.argv[1], sys.argv[2]+try:+ registry = json.load(open(registry_path))+except: registry = {"projects": []}++results = []+for proj in (registry.get("projects") or [])[:10]:+ path = os.path.expanduser(proj.get("path", ""))+ name = proj.get("alias", proj.get("name", "unknown"))+ if not os.path.isdir(path): continue++ info = {"name": name, "path": path}++ # Git status+ try:+ status = subprocess.check_output(["git", "-C", path, "status", "--porcelain"], timeout=5, stderr=subprocess.DEVNULL).decode()+ info["uncommitted"] = len([l for l in status.strip().split("\n") if l.strip()])+ except: info["uncommitted"] = -1++ # Branch+ try:+ info["branch"] = subprocess.check_output(["git", "-C", path, "branch", "--show-current"], timeout=5, stderr=subprocess.DEVNULL).decode().strip()+ except: info["branch"] = "unknown"++ # Commits ahead of remote+ try:+ ahead = subprocess.check_output(["git", "-C", path, "rev-list", "--count", "@{u}..HEAD"], timeout=5, stderr=subprocess.DEVNULL).decode().strip()+ info["commits_ahead"] = int(ahead)+ except: info["commits_ahead"] = 0++ results.append(info)++import datetime+with open(output_path, "w") as f:+ json.dump({"updated": datetime.datetime.now(datetime.timezone.utc).isoformat(), "projects": results}, f, indent=2)+PYEOF++ date +%s > "$LAST_FETCH"+ log "BRAIN: project health cache updated"+}++# ── Graceful shutdown ─────────────────────────────────────────────────────+cleanup() {+ log "SHUTDOWN: SIGTERM received — stopping all services"+ local name+ for name in "${!SERVICE_PIDS[@]}"; do+ stop_service "$name"+ done+ write_daemon_health+ log "SHUTDOWN: all services stopped — exiting"+ exit 0+}++trap cleanup SIGTERM SIGINT++# ── Main ──────────────────────────────────────────────────────────────────+log "START: ops-daemon pid=$$ starting"+rotate_log++if ! load_services_config; then+ log "FATAL: no services config — writing empty health and sleeping"+ cat > "$HEALTH_FILE" <<EOF+{"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)", "pid": $$, "uptime_seconds": 0, "services": {}, "action_needed": null}+EOF+ # Sleep forever until SIGTERM; launchd keeps us alive+ while true; do sleep 30; done+fi++# Initialize + start all enabled services+while IFS= read -r svc; do+ SERVICE_RESTARTS["$svc"]=0+ SERVICE_STATUS["$svc"]="starting"+ SERVICE_LAST_HEALTH["$svc"]="unknown"++ local_cron=$(get_service_field "$svc" "cron")+ if [[ -n "$local_cron" ]]; then+ SERVICE_STATUS["$svc"]="scheduled"+ SERVICE_NEXT_RUN["$svc"]=$(calc_next_run "$local_cron")+ log "INIT: $svc is cron-scheduled (${local_cron})"+ else+ start_service "$svc"+ fi+done < <(get_enabled_services)++write_daemon_health+log "LOOP: entering monitor loop (30s interval)"++# ── Monitor loop ──────────────────────────────────────────────────────────+while true; do+ rotate_log+ ACTION_NEEDED="null"++ while IFS= read -r svc; do+ local_cron=$(get_service_field "$svc" "cron")++ if [[ -n "$local_cron" ]]; then+ # Cron service: check if it's time to run+ local_next="${SERVICE_NEXT_RUN[$svc]:-0}"+ if [[ $(date +%s) -ge $local_next ]]; then+ run_cron_service "$svc"+ fi+ else+ # Persistent service: check health + restart if needed+ if ! check_health "$svc"; then+ local_status="${SERVICE_STATUS[$svc]}"+ if [[ "$local_status" != "needs_reauth" ]] && [[ "$local_status" != "max_restarts_exceeded" ]]; then+ restart_service "$svc"+ fi+ fi+ fi+ done < <(get_enabled_services)++ # ── Intelligence pass (smart brain) ──────────────────────────────────────+ # These run with their own internal throttles — safe to call every loop+ prefetch_briefing_cache # Every 5 min: WA/email/PR counts for ops-go+ detect_urgent_messages # Every 5 min: keyword scan for time-sensitive msgs+ trigger_smart_memory_extraction # Every 10 min: haiku extraction if new msgs arrived+ build_contact_activity_index # Every 15 min: cross-channel contact scoring+ prefetch_calendar # Every 15 min: today's meetings for context+ prefetch_project_health # Every 10 min: git/branch status per registered repo++ write_daemon_health+ sleep 30+donediff --git a/claude-ops/scripts/ops-memory-extractor.sh b/claude-ops/scripts/ops-memory-extractor.shnew file mode 100755index 00000000..e13839db--- /dev/null+++ b/claude-ops/scripts/ops-memory-extractor.sh@@ -0,0 +1,477 @@+#!/usr/bin/env bash+# ops-memory-extractor.sh — Extracts user preferences, contact profiles, and behavioral+# patterns from WhatsApp + email history and writes structured memory files.+# Runs every 30 min via ops-daemon cron service.+set -euo pipefail++# ── Config ────────────────────────────────────────────────────────────────────+MEMORIES_DIR="${HOME}/.claude/plugins/data/ops-ops-marketplace/memories"+HEALTH_FILE="${MEMORIES_DIR}/.health"+TMP_RAW="${TMPDIR:-/tmp}/ops-memory-raw-$$.json"+TMP_PROMPT="${TMPDIR:-/tmp}/ops-memory-prompt-$$.txt"+TMP_RESPONSE="${TMPDIR:-/tmp}/ops-memory-response-$$.json"+MAX_TOTAL_BYTES=51200 # 50KB ceiling across all memory files+MAX_FILE_BYTES=5120 # 5KB per file before auto-compression+LOG_PREFIX="[ops-memory-extractor]"++# ── Helpers ───────────────────────────────────────────────────────────────────+log() { echo "${LOG_PREFIX} $*" >&2; }+die() { log "FATAL: $*"; write_health "error" "$*"; exit 1; }+ts() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }++write_health() {+ local status="$1" msg="${2:-}"+ mkdir -p "${MEMORIES_DIR}"+ cat > "${HEALTH_FILE}" <<EOF+{+ "status": "${status}",+ "message": "${msg}",+ "last_run": "$(ts)",+ "memories_dir": "${MEMORIES_DIR}"+}+EOF+}++cleanup() {+ rm -f "${TMP_RAW}" "${TMP_PROMPT}" "${TMP_RESPONSE}"+}+trap cleanup EXIT++# ── Resolve ANTHROPIC_API_KEY ─────────────────────────────────────────────────+resolve_api_key() {+ if [[ -n "${ANTHROPIC_API_KEY:-}" ]]; then+ return 0+ fi+ if command -v doppler &>/dev/null; then+ local key+ key=$(doppler secrets get ANTHROPIC_API_KEY --plain 2>/dev/null || true)+ if [[ -n "${key}" ]]; then+ export ANTHROPIC_API_KEY="${key}"+ return 0+ fi+ fi+ die "ANTHROPIC_API_KEY not set and doppler unavailable"+}++# ── Collect raw data ──────────────────────────────────────────────────────────+collect_data() {+ local wacli_data="" email_data=""+ local yesterday+ yesterday=$(date -u -v-1d +"%Y-%m-%d" 2>/dev/null || date -u -d "yesterday" +"%Y-%m-%d")++ # WhatsApp via wacli+ if command -v wacli &>/dev/null; then+ local health_status=""+ if [[ -f "${HOME}/.wacli/.health" ]]; then+ health_status=$(cat "${HOME}/.wacli/.health" 2>/dev/null || true)+ fi+ if echo "${health_status}" | grep -qi "connected\|ok\|healthy" 2>/dev/null; then+ log "Collecting WhatsApp messages..."+ wacli_data=$(wacli messages list --after="${yesterday}" --limit=200 --json 2>/dev/null || true)+ if [[ -z "${wacli_data}" ]]; then+ log "wacli returned no data (skipping)"+ fi+ else+ log "wacli not connected (skipping WhatsApp)"+ fi+ else+ log "wacli not available (skipping WhatsApp)"+ fi++ # Email via gog+ if command -v gog &>/dev/null; then+ log "Collecting recent emails..."+ email_data=$(gog gmail search -j --results-only --no-input --max 20 "newer_than:1d" 2>/dev/null || true)+ if [[ -z "${email_data}" ]]; then+ log "gog returned no data (skipping)"+ fi+ else+ log "gog not available (skipping email)"+ fi++ if [[ -z "${wacli_data}" && -z "${email_data}" ]]; then+ log "No data sources available — nothing to extract"+ write_health "skipped" "no data sources"+ exit 0+ fi++ # Write combined raw payload+ cat > "${TMP_RAW}" <<EOF+{+ "whatsapp_messages": ${wacli_data:-null},+ "emails": ${email_data:-null},+ "collected_at": "$(ts)"+}+EOF+}++# ── Read existing memory for context ─────────────────────────────────────────+read_existing_memory() {+ local out=""+ for f in "${MEMORIES_DIR}"/contact_*.md "${MEMORIES_DIR}"/preferences.md \+ "${MEMORIES_DIR}"/topics_active.md "${MEMORIES_DIR}"/donts.md; do+ [[ -f "$f" ]] || continue+ out+="### $(basename "$f")\n"+ out+=$(cat "$f")+ out+="\n\n"+ done+ printf '%s' "${out}"+}++# ── Build extraction prompt ────────────────────────────────────────────────────+build_prompt() {+ local raw_data existing_memory+ raw_data=$(cat "${TMP_RAW}")+ existing_memory=$(read_existing_memory)++ cat > "${TMP_PROMPT}" <<'PROMPT_EOF'+You are a memory extraction assistant. Analyze the provided chat/email data and extract structured information.++Return a JSON object with exactly these keys:+- "contacts": array of contact objects+- "preferences": object with user behavior patterns+- "topics_active": array of ongoing conversation topics+- "donts": array of things to avoid++Each contact object:+{+ "name": string,+ "email": string or null,+ "phone": string or null,+ "company": string or null,+ "role": string or null,+ "relationship": "professional|personal|family|vendor|client",+ "communication_style": string (1-2 sentences),+ "language_preference": string (e.g. "English", "Hindi", "English + Hindi"),+ "channel_preference": "whatsapp|email|both|unknown",+ "recent_context": string (1-3 bullet points as plain text, newline-separated),+ "confidence": float 0.0-1.0+}++Preferences object:+{+ "response_style": string,+ "tone": string,+ "topics_of_interest": array of strings,+ "scheduling_patterns": string or null,+ "language": string,+ "notes": array of strings+}++Topics active array items:+{+ "topic": string,+ "contacts_involved": array of names,+ "summary": string,+ "pending_action": string or null,+ "deadline": string or null (ISO date)+}++Donts array items: plain strings describing things to avoid.++Rules:+- Only include contacts with at least 2 signals of identity+- Merge with existing memory (do not duplicate, update stale info)+- Confidence reflects how certain the extraction is (0.8+ = clear signal)+- Keep responses concise — no padding+- If no meaningful data to extract for a key, return empty array/object++PROMPT_EOF++ # Append existing memory context and raw data as separate user turn content+ printf '\nEXISTING MEMORY (merge with this, do not duplicate):\n%s\n\nRAW DATA TO ANALYZE:\n%s\n' \+ "${existing_memory}" "${raw_data}" >> "${TMP_PROMPT}"+}++# ── Call Claude Haiku ─────────────────────────────────────────────────────────+call_claude() {+ local system_prompt user_content+ system_prompt="You are a memory extraction assistant. Return only valid JSON, no markdown fences, no explanation."+ # Escape for JSON embedding+ user_content=$(cat "${TMP_PROMPT}" | python3 -c "+import sys, json+data = sys.stdin.read()+print(json.dumps(data))+" 2>/dev/null || python3 -c "+import sys, json+data = sys.stdin.read()+print(json.dumps(data))+")++ local payload+ payload=$(cat <<EOF+{+ "model": "claude-haiku-4-5-20251001",+ "max_tokens": 4096,+ "system": $(printf '%s' "${system_prompt}" | python3 -c "import sys, json; print(json.dumps(sys.stdin.read()))"),+ "messages": [+ {"role": "user", "content": ${user_content}}+ ]+}+EOF+)++ log "Calling Claude Haiku for extraction..."+ local http_status+ http_status=$(curl -s -o "${TMP_RESPONSE}" -w "%{http_code}" \+ https://api.anthropic.com/v1/messages \+ -H "content-type: application/json" \+ -H "x-api-key: ${ANTHROPIC_API_KEY}" \+ -H "anthropic-version: 2023-06-01" \+ -d "${payload}" 2>/dev/null)++ if [[ "${http_status}" != "200" ]]; then+ local err+ err=$(cat "${TMP_RESPONSE}" 2>/dev/null || echo "unknown error")+ die "Claude API returned HTTP ${http_status}: ${err}"+ fi++ # Extract text content from response+ python3 - <<'PYEOF' "${TMP_RESPONSE}"+import sys, json++resp_file = sys.argv[1]+with open(resp_file) as f:+ data = json.load(f)++content = data.get("content", [])+for block in content:+ if block.get("type") == "text":+ print(block["text"])+ sys.exit(0)++print("{}")+PYEOF+}++# ── Write memory files ────────────────────────────────────────────────────────+write_memory_files() {+ local extraction="$1"+ local now+ now=$(ts)++ mkdir -p "${MEMORIES_DIR}"++ python3 - <<PYEOF "${MEMORIES_DIR}" "${now}" "${extraction}"+import sys, json, os, re+from pathlib import Path++memories_dir = sys.argv[1]+now = sys.argv[2]+raw = sys.argv[3]++# Strip markdown fences if model added them+raw = re.sub(r'^```(?:json)?\s*', '', raw.strip())+raw = re.sub(r'\s*```$', '', raw.strip())++try:+ data = json.loads(raw)+except json.JSONDecodeError as e:+ print(f"[ops-memory-extractor] WARN: Failed to parse extraction JSON: {e}", file=sys.stderr)+ sys.exit(0)++def read_existing(path):+ if Path(path).exists():+ return Path(path).read_text(encoding="utf-8")+ return ""++def slugify(name):+ return re.sub(r'[^a-z0-9]+', '_', name.lower()).strip('_')++def build_frontmatter(fields):+ lines = ["---"]+ for k, v in fields.items():+ if v is not None:+ lines.append(f"{k}: {v}")+ lines.append("---")+ return "\n".join(lines)++def write_if_changed(path, content):+ existing = read_existing(path)+ if existing == content:+ return+ Path(path).write_text(content, encoding="utf-8")+ print(f"[ops-memory-extractor] wrote {path}", file=sys.stderr)++# ── Contacts ──────────────────────────────────────────────────────────────────+for contact in data.get("contacts", []):+ name = contact.get("name", "unknown")+ slug = slugify(name)+ path = os.path.join(memories_dir, f"contact_{slug}.md")++ fm = build_frontmatter({+ "type": "contact",+ "name": name,+ "email": contact.get("email"),+ "phone": contact.get("phone"),+ "company": contact.get("company"),+ "role": contact.get("role"),+ "last_updated": now,+ "confidence": contact.get("confidence", 0.7),+ })++ rel = contact.get("relationship", "unknown")+ style = contact.get("communication_style", "")+ lang = contact.get("language_preference", "")+ channel = contact.get("channel_preference", "unknown")+ ctx_raw = contact.get("recent_context", "")+ ctx_lines = [f"- {l.lstrip('- ').strip()}" for l in ctx_raw.split("\n") if l.strip()]+ ctx_block = "\n".join(ctx_lines) if ctx_lines else "- No recent context"++ body = f"""+## Relationship+- {rel.capitalize()} contact+- {style}++## Communication Style+- {style}+- Prefers {channel}+- {lang}++## Recent Context+{ctx_block}+""".lstrip()++ write_if_changed(path, f"{fm}\n\n{body}")++# ── Preferences ───────────────────────────────────────────────────────────────+prefs = data.get("preferences", {})+if prefs:+ path = os.path.join(memories_dir, "preferences.md")+ fm = build_frontmatter({+ "type": "preferences",+ "last_updated": now,+ })+ topics = "\n".join(f"- {t}" for t in prefs.get("topics_of_interest", []))+ notes = "\n".join(f"- {n}" for n in prefs.get("notes", []))++ body = f"""## Response Style+- {prefs.get("response_style", "Unknown")}+- Tone: {prefs.get("tone", "Unknown")}+- Language: {prefs.get("language", "English")}++## Topics of Interest+{topics or "- None identified"}++## Scheduling+- {prefs.get("scheduling_patterns") or "No patterns identified"}++## Notes+{notes or "- None"}+""".lstrip()++ write_if_changed(path, f"{fm}\n\n{body}")++# ── Active Topics ─────────────────────────────────────────────────────────────+topics = data.get("topics_active", [])+if topics:+ path = os.path.join(memories_dir, "topics_active.md")+ fm = build_frontmatter({"type": "topics", "last_updated": now})+ blocks = []+ for t in topics:+ contacts_str = ", ".join(t.get("contacts_involved", []))+ block = f"### {t.get('topic', 'Unnamed')}\n"+ block += f"- **Contacts**: {contacts_str or 'unknown'}\n"+ block += f"- **Summary**: {t.get('summary', '')}\n"+ if t.get("pending_action"):+ block += f"- **Action**: {t['pending_action']}\n"+ if t.get("deadline"):+ block += f"- **Deadline**: {t['deadline']}\n"+ blocks.append(block)+ body = "\n".join(blocks)+ write_if_changed(path, f"{fm}\n\n{body}")++# ── Donts ─────────────────────────────────────────────────────────────────────+donts = data.get("donts", [])+if donts:+ path = os.path.join(memories_dir, "donts.md")+ fm = build_frontmatter({"type": "donts", "last_updated": now})+ lines = "\n".join(f"- {d}" for d in donts)+ write_if_changed(path, f"{fm}\n\n## Things to Avoid\n{lines}\n")++print("[ops-memory-extractor] memory files updated", file=sys.stderr)+PYEOF+}++# ── Auto-compress oversized files ─────────────────────────────────────────────+auto_compress() {+ local total_bytes=0+ for f in "${MEMORIES_DIR}"/*.md; do+ [[ -f "$f" ]] || continue+ local fsize+ fsize=$(wc -c < "$f" 2>/dev/null || echo 0)+ total_bytes=$((total_bytes + fsize))+ done++ log "Total memory size: ${total_bytes} bytes"++ # Per-file compression: truncate overgrown files to most recent sections+ for f in "${MEMORIES_DIR}"/*.md; do+ [[ -f "$f" ]] || continue+ local fsize+ fsize=$(wc -c < "$f" 2>/dev/null || echo 0)+ if [[ "${fsize}" -gt "${MAX_FILE_BYTES}" ]]; then+ log "Compressing ${f} (${fsize} bytes > ${MAX_FILE_BYTES})"+ python3 - <<PYEOF "${f}"+import sys+from pathlib import Path+path = Path(sys.argv[1])+text = path.read_text(encoding="utf-8")++# Keep frontmatter + last 3KB of body+parts = text.split("---", 2)+if len(parts) >= 3:+ frontmatter = "---" + parts[1] + "---"+ body = parts[2]+ # Keep last 3000 chars of body+ if len(body) > 3000:+ body = "\n\n[...older content trimmed...]\n\n" + body[-3000:]+ path.write_text(frontmatter + body, encoding="utf-8")+ print(f"[ops-memory-extractor] compressed {path}", file=sys.stderr)+PYEOF+ fi+ done++ # Global ceiling: if still over 50KB, remove oldest contact files+ if [[ "${total_bytes}" -gt "${MAX_TOTAL_BYTES}" ]]; then+ log "WARN: Total memory exceeds ${MAX_TOTAL_BYTES} bytes — pruning oldest contacts"+ # Sort contact files by modification time (oldest first) and remove until under limit+ for f in $(ls -tr "${MEMORIES_DIR}"/contact_*.md 2>/dev/null); do+ [[ -f "$f" ]] || continue+ total_bytes=$(du -sb "${MEMORIES_DIR}"/*.md 2>/dev/null | awk '{s+=$1} END{print s}' || echo 0)+ if [[ "${total_bytes}" -le "${MAX_TOTAL_BYTES}" ]]; then+ break+ fi+ log "Removing oldest contact file: ${f}"+ rm -f "${f}"+ done+ fi+}++# ── Main ──────────────────────────────────────────────────────────────────────+main() {+ log "Starting memory extraction run at $(ts)"+ mkdir -p "${MEMORIES_DIR}"++ resolve_api_key+ collect_data++ build_prompt++ local extraction+ extraction=$(call_claude)++ if [[ -z "${extraction}" || "${extraction}" == "{}" ]]; then+ log "No extraction results from Claude — skipping write"+ write_health "ok" "no new memories extracted"+ exit 0+ fi++ write_memory_files "${extraction}"+ auto_compress++ write_health "ok" "extraction complete"+ log "Memory extraction complete at $(ts)"+}++main "$@"diff --git a/claude-ops/scripts/ops-message-listener.sh b/claude-ops/scripts/ops-message-listener.shnew file mode 100755index 00000000..f5a9ba74--- /dev/null+++ b/claude-ops/scripts/ops-message-listener.sh@@ -0,0 +1,231 @@+#!/usr/bin/env bash+# ops-message-listener.sh — Poll-based message listener (replaces OpenClaw WebSocket gateway)+# Supervised by ops-daemon. Polls WhatsApp (wacli) + Telegram every 60s.+# New non-owner messages → written to inbox-queue.json for /ops:inbox to consume.+# Health status written to listener-health.txt for daemon monitoring.+set -euo pipefail++DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+LOG="$LOG_DIR/message-listener.log"+QUEUE_FILE="$DATA_DIR/inbox-queue.json"+HEALTH_FILE="$DATA_DIR/listener-health.txt"+STATE_FILE="$DATA_DIR/listener-state.json"+WACLI="${WACLI_BIN:-$(command -v wacli 2>/dev/null || echo /usr/local/bin/wacli)}"+POLL_INTERVAL="${OPS_LISTENER_POLL_INTERVAL:-60}"++mkdir -p "$LOG_DIR" "$DATA_DIR"++log() { printf '%s [listener] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$LOG"; }++write_health() {+ local status="$1" detail="${2:-}"+ printf 'status=%s\ntimestamp=%s\ndetail=%s\n' \+ "$status" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$detail" > "$HEALTH_FILE"+}++# ── Initialize queue file ─────────────────────────────────────────────────+if [[ ! -f "$QUEUE_FILE" ]]; then+ echo '{"messages": [], "last_updated": null}' > "$QUEUE_FILE"+fi++# ── Load last-seen state ──────────────────────────────────────────────────+load_state() {+ python3 -c "+import json, os+f = '$STATE_FILE'+if os.path.exists(f):+ data = json.load(open(f))+else:+ data = {'wa_last_seen': None, 'tg_last_seen': None}+print(data.get('wa_last_seen') or '')+print(data.get('tg_last_seen') or '')+" 2>/dev/null || printf '\n\n'+}++save_state() {+ local wa_ts="$1" tg_ts="$2"+ python3 -c "+import json+data = {'wa_last_seen': '$wa_ts', 'tg_last_seen': '$tg_ts'}+json.dump(data, open('$STATE_FILE', 'w'))+" 2>/dev/null || true+}++# ── Append messages to queue ──────────────────────────────────────────────+append_to_queue() {+ local new_msgs_json="$1"+ python3 -c "+import json, sys+from datetime import datetime, timezone++queue_file = '$QUEUE_FILE'+try:+ queue = json.load(open(queue_file))+except:+ queue = {'messages': [], 'last_updated': None}++new_msgs = json.loads('''$new_msgs_json''')+# Dedup by message id+existing_ids = {m.get('id') for m in queue['messages']}+added = 0+for msg in new_msgs:+ if msg.get('id') not in existing_ids:+ queue['messages'].append(msg)+ existing_ids.add(msg.get('id'))+ added += 1++# Keep last 200 messages max+queue['messages'] = queue['messages'][-200:]+queue['last_updated'] = datetime.now(timezone.utc).isoformat()++json.dump(queue, open(queue_file, 'w'), indent=2)+print(added)+" 2>/dev/null || echo 0+}++# ── Poll WhatsApp ─────────────────────────────────────────────────────────+poll_whatsapp() {+ local since="$1"+ if ! command -v wacli &>/dev/null && [[ ! -x "$WACLI" ]]; then+ echo "[]"+ return+ fi++ local since_flag=""+ [[ -n "$since" ]] && since_flag="--after=$since"++ local raw+ raw=$("$WACLI" messages list $since_flag --limit 20 --json 2>/dev/null || echo "[]")++ # Filter: only non-owner (from_me=false) messages+ echo "$raw" | python3 -c "+import json, sys+msgs = json.load(sys.stdin)+filtered = []+for m in msgs:+ if not m.get('from_me', False):+ filtered.append({+ 'id': m.get('id', ''),+ 'channel': 'whatsapp',+ 'from': m.get('contact_name', m.get('from', '')),+ 'text': m.get('body', m.get('text', '')),+ 'timestamp': m.get('timestamp', ''),+ 'raw': m+ })+print(json.dumps(filtered))+" 2>/dev/null || echo "[]"+}++# ── Poll Telegram ─────────────────────────────────────────────────────────+poll_telegram() {+ local since_update_id="${1:-0}"+ local tg_token="${TELEGRAM_BOT_TOKEN:-}"++ if [[ -z "$tg_token" ]]; then+ tg_token=$(doppler secrets get TELEGRAM_BOT_TOKEN --plain 2>/dev/null || true)+ fi+ [[ -z "$tg_token" ]] && echo "[]" && return++ local offset=$(( since_update_id + 1 ))+ local raw+ raw=$(curl -s "https://api.telegram.org/bot${tg_token}/getUpdates?offset=${offset}&limit=20&timeout=5" 2>/dev/null || echo '{"ok":false}')++ echo "$raw" | python3 -c "+import json, sys+data = json.load(sys.stdin)+if not data.get('ok'):+ print('[]')+ sys.exit(0)+filtered = []+for upd in data.get('result', []):+ msg = upd.get('message', {})+ sender = msg.get('from', {})+ # Skip owner's own messages (add TELEGRAM_OWNER_ID to env to filter by user_id)+ owner_id = '${TELEGRAM_OWNER_ID:-}'+ if owner_id and str(sender.get('id', '')) == owner_id:+ continue+ if msg:+ filtered.append({+ 'id': str(upd.get('update_id', '')),+ 'channel': 'telegram',+ 'from': sender.get('username', sender.get('first_name', 'unknown')),+ 'text': msg.get('text', ''),+ 'timestamp': str(msg.get('date', '')),+ 'update_id': upd.get('update_id', 0),+ 'raw': msg+ })+print(json.dumps(filtered))+" 2>/dev/null || echo "[]"+}++# ── Trap for clean shutdown ───────────────────────────────────────────────+cleanup() {+ log "SHUTDOWN received — writing final health"+ write_health "stopped" "SIGTERM received"+ exit 0+}+trap cleanup SIGTERM SIGINT++# ── Main poll loop ────────────────────────────────────────────────────────+log "START: ops-message-listener polling every ${POLL_INTERVAL}s"+write_health "polling" "starting"++# Load initial state+read -r WA_LAST_SEEN TG_LAST_UPDATE_ID <<< "$(load_state | tr '\n' ' ')"+WA_LAST_SEEN="${WA_LAST_SEEN:-}"+TG_LAST_UPDATE_ID="${TG_LAST_UPDATE_ID:-0}"++# Bootstrap WA since: use 2 minutes ago on first run+if [[ -z "$WA_LAST_SEEN" ]]; then+ WA_LAST_SEEN=$(date -u -v-2M "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u -d "2 minutes ago" "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u "+%Y-%m-%dT%H:%M:%SZ")+fi++POLL_COUNT=0+while true; do+ POLL_COUNT=$(( POLL_COUNT + 1 ))+ POLL_TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)++ # ── WhatsApp poll ──────────────────────────────────────────────────────+ WA_MSGS=$(poll_whatsapp "$WA_LAST_SEEN")+ WA_COUNT=$(echo "$WA_MSGS" | python3 -c "import json,sys; print(len(json.load(sys.stdin)))" 2>/dev/null || echo 0)++ if [[ "$WA_COUNT" -gt 0 ]]; then+ ADDED=$(append_to_queue "$WA_MSGS")+ log "WhatsApp: $WA_COUNT new messages (queued $ADDED)"+ # Update last seen to most recent timestamp+ WA_LAST_SEEN=$(echo "$WA_MSGS" | python3 -c "+import json, sys+msgs = json.load(sys.stdin)+ts = [m.get('timestamp','') for m in msgs if m.get('timestamp','')]+print(max(ts) if ts else '$WA_LAST_SEEN')+" 2>/dev/null || echo "$WA_LAST_SEEN")+ fi++ # ── Telegram poll ──────────────────────────────────────────────────────+ TG_MSGS=$(poll_telegram "$TG_LAST_UPDATE_ID")+ TG_COUNT=$(echo "$TG_MSGS" | python3 -c "import json,sys; print(len(json.load(sys.stdin)))" 2>/dev/null || echo 0)++ if [[ "$TG_COUNT" -gt 0 ]]; then+ ADDED=$(append_to_queue "$TG_MSGS")+ log "Telegram: $TG_COUNT new messages (queued $ADDED)"+ TG_LAST_UPDATE_ID=$(echo "$TG_MSGS" | python3 -c "+import json, sys+msgs = json.load(sys.stdin)+ids = [m.get('update_id', 0) for m in msgs]+print(max(ids) if ids else $TG_LAST_UPDATE_ID)+" 2>/dev/null || echo "$TG_LAST_UPDATE_ID")+ fi++ # ── Save state ──────────────────────────────────────────────────────────+ save_state "$WA_LAST_SEEN" "$TG_LAST_UPDATE_ID"++ # ── Write health ──────────────────────────────────────────────────────+ write_health "polling" "poll=$POLL_COUNT wa_new=$WA_COUNT tg_new=$TG_COUNT ts=$POLL_TS"++ if [[ $(( POLL_COUNT % 10 )) -eq 0 ]]; then+ log "Heartbeat: poll #$POLL_COUNT — wa_seen=$WA_LAST_SEEN tg_offset=$TG_LAST_UPDATE_ID"+ fi++ sleep "$POLL_INTERVAL"+donediff --git a/claude-ops/scripts/registry.example.json b/claude-ops/scripts/registry.example.jsonnew file mode 100644index 00000000..a12efef5--- /dev/null+++ b/claude-ops/scripts/registry.example.json@@ -0,0 +1,48 @@+{+ "version": "1.0",+ "owner": "Your Name",+ "projects": [+ {+ "alias": "example-project",+ "paths": ["~/Projects/example-project"],+ "repos": ["your-github-org/example-project"],+ "org": "your-github-org",+ "type": "monorepo",+ "infra": {+ "platform": "vercel"+ },+ "revenue": {+ "model": "saas",+ "stage": "pre-launch",+ "target_date": "2026-12-31"+ },+ "gsd": true,+ "priority": 1+ },+ {+ "alias": "example-multi-repo",+ "paths": [+ "~/Projects/example-api",+ "~/Projects/example-web",+ "~/Projects/example-mobile"+ ],+ "repos": [+ "your-github-org/example-api",+ "your-github-org/example-web",+ "your-github-org/example-mobile"+ ],+ "org": "your-github-org",+ "type": "multi-repo",+ "infra": {+ "ecs_clusters": ["example-production", "example-staging"],+ "platform": "aws"+ },+ "revenue": {+ "model": "subscription",+ "stage": "growth"+ },+ "gsd": true,+ "priority": 2+ }+ ]+}diff --git a/claude-ops/scripts/setup.sh b/claude-ops/scripts/setup.shnew file mode 100755index 00000000..984da9c6--- /dev/null+++ b/claude-ops/scripts/setup.sh@@ -0,0 +1,61 @@+#!/usr/bin/env bash+# ops setup — Auto-install missing tools + validate readiness+# Called by SessionStart hook and /ops:setup+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PLUGIN_ROOT="$(dirname "$SCRIPT_DIR")"+MISSING=()+INSTALLED=()++# ─── Auto-install core tools ────────────────────────────────────────+auto_install() {+ local tool="$1"+ local brew_pkg="$2"+ if ! command -v "$tool" &>/dev/null; then+ if command -v brew &>/dev/null; then+ timeout 30 brew install "$brew_pkg" &>/dev/null && INSTALLED+=("$tool") && return 0+ fi+ MISSING+=("$tool")+ return 1+ fi+ return 0+}++# Core (auto-installed silently)+auto_install jq jq+auto_install gh gh+auto_install git git++# Infrastructure (auto-installed if brew available)+auto_install aws awscli+auto_install node node++# Telegram MCP server deps+if [ -f "$PLUGIN_ROOT/telegram-server/package.json" ] && command -v node &>/dev/null; then+ if [ ! -d "$PLUGIN_ROOT/telegram-server/node_modules" ]; then+ (cd "$PLUGIN_ROOT/telegram-server" && npm install --silent &>/dev/null) && INSTALLED+=("telegram-deps")+ fi+fi++# Plugin bin deps+if [ -f "$PLUGIN_ROOT/package.json" ] && command -v node &>/dev/null; then+ if [ ! -d "$PLUGIN_ROOT/node_modules" ]; then+ (cd "$PLUGIN_ROOT" && npm install --silent &>/dev/null) && INSTALLED+=("plugin-deps")+ fi+fi++# ─── Report only problems ───────────────────────────────────────────+if [ ${#INSTALLED[@]} -gt 0 ]; then+ echo " ops: auto-installed ${INSTALLED[*]}"+fi++for tool in "${MISSING[@]}"; do+ echo " ✗ ops: $tool not found — run /ops:setup to configure"+done++# Check registry+REGISTRY="$SCRIPT_DIR/registry.json"+if [ ! -f "$REGISTRY" ]; then+ echo " ✗ ops: no project registry — run /ops:setup to create one"+fidiff --git a/claude-ops/scripts/wacli-keepalive.sh b/claude-ops/scripts/wacli-keepalive.shnew file mode 100755index 00000000..14b64bed--- /dev/null+++ b/claude-ops/scripts/wacli-keepalive.sh@@ -0,0 +1,207 @@+#!/usr/bin/env bash+# wacli-keepalive.sh — Persistent WhatsApp connection with auto-healing+# Installed by ops:setup → Step 3b.7. Runs via launchd as com.claude-ops.wacli-keepalive.+#+# Responsibilities:+# 1. Kill orphaned wacli processes and clear stale locks+# 2. Verify authentication — write health file for ops skills to read+# 3. Run `wacli sync --follow` for persistent message streaming+# 4. If auth fails or keys desync, write needs_reauth so ops:inbox can prompt QR+#+# LaunchD restarts this automatically on exit (KeepAlive=true, throttle 60s).+#+# When run as a child of ops-daemon (OPS_DAEMON_MANAGED=1 / OPS_DAEMON_PID set),+# launchd-specific self-management is skipped — the daemon handles restarts.+set -euo pipefail++# ── Daemon-managed mode detection ────────────────────────────────────────+# If ops-daemon is managing us, we skip registering our own launchd agent.+# The daemon reads our health file and handles restart/backoff logic.+export OPS_DAEMON_MANAGED="${OPS_DAEMON_MANAGED:-0}"+if [[ -n "${OPS_DAEMON_PID:-}" ]] && [[ "$OPS_DAEMON_MANAGED" == "1" ]]; then+ : # Running as ops-daemon child — launchd self-management skipped+fi++WACLI="${WACLI_BIN:-/usr/local/bin/wacli}"+STORE="${WACLI_STORE:-$HOME/.wacli}"+LOG_DIR="${WACLI_LOG_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace/logs}"+LOG="$LOG_DIR/wacli-keepalive.log"+HEALTH_FILE="$STORE/.health"+MAX_LOG_SIZE=1048576 # 1MB+SYNC_PROBE_TIMEOUT=20++mkdir -p "$LOG_DIR" "$STORE"++log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"; }++# Rotate log if too large+if [[ -f "$LOG" ]] && [[ $(stat -f%z "$LOG" 2>/dev/null || stat -c%s "$LOG" 2>/dev/null || echo 0) -gt $MAX_LOG_SIZE ]]; then+ mv "$LOG" "$LOG.old"+fi++log "START: keepalive pid=$$ starting"++# ── Step 1: Kill orphaned wacli sync processes ──────────────────────────+cleanup_stale() {+ local stale_pids+ stale_pids=$(pgrep -f "wacli sync" 2>/dev/null || true)+ for pid in $stale_pids; do+ if [[ "$pid" != "$$" ]]; then+ kill "$pid" 2>/dev/null && log "DOCTOR: killed stale wacli sync pid=$pid" || true+ fi+ done++ # Check for stale lock+ local doctor_json+ doctor_json=$("$WACLI" doctor --json 2>/dev/null || echo '{}')+ local locked+ locked=$(echo "$doctor_json" | grep -o '"locked":true' || true)+ if [[ -n "$locked" ]]; then+ log "DOCTOR: store locked — waiting 5s for natural release"+ sleep 5+ doctor_json=$("$WACLI" doctor --json 2>/dev/null || echo '{}')+ locked=$(echo "$doctor_json" | grep -o '"locked":true' || true)+ if [[ -n "$locked" ]]; then+ pkill -f wacli 2>/dev/null || true+ sleep 2+ log "DOCTOR: force-cleared stale lock"+ fi+ fi+}++# ── Step 2: Check auth + connectivity, write health file ────────────────+write_health() {+ local status="$1" detail="${2:-}"+ cat > "$HEALTH_FILE" <<EOF+timestamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)+status=$status+detail=$detail+pid=$$+EOF+ log "HEALTH: status=$status detail=$detail"+}++check_auth() {+ local doctor_out+ doctor_out=$("$WACLI" doctor 2>&1) || true+ local authenticated+ authenticated=$(echo "$doctor_out" | awk '/AUTHENTICATED/{print $2}')++ if [[ "$authenticated" != "true" ]]; then+ write_health "needs_auth" "not authenticated — QR scan required"+ return 1+ fi+ return 0+}++# ── Step 3: Probe sync for key desync ───────────────────────────────────+probe_sync() {+ local probe_log="/tmp/wacli-sync-probe-$$.log"+ timeout "$SYNC_PROBE_TIMEOUT" "$WACLI" sync --once --idle-exit=10s 2>&1 > "$probe_log" || true++ if grep -qE "didn't find app state key|failed to decode app state|Failed to do initial fetch" "$probe_log" 2>/dev/null; then+ write_health "needs_reauth" "app-state keys desynced — logout + re-pair required"+ rm -f "$probe_log"+ return 1+ fi++ rm -f "$probe_log"+ return 0+}++# ── Step 4: On-demand backfill (before going persistent) ────────────────+# If BACKFILL_JIDS file exists, backfill those chats then delete the file.+# This allows ops:setup or ops:inbox to request backfill by writing JIDs to this file+# and restarting the daemon.+run_backfill() {+ local backfill_file="$STORE/.backfill_jids"+ if [[ ! -f "$backfill_file" ]]; then return 0; fi++ log "BACKFILL: found backfill request"+ local jid+ while IFS= read -r jid; do+ [[ -z "$jid" ]] && continue+ log "BACKFILL: backfilling $jid"+ "$WACLI" history backfill --chat="$jid" --count=50 --requests=2 --wait=30s --idle-exit=5s 2>&1 | while IFS= read -r line; do+ log "BACKFILL: $line"+ done || true+ done < "$backfill_file"++ rm -f "$backfill_file"+ log "BACKFILL: complete"+}++# ── Main flow ───────────────────────────────────────────────────────────+cleanup_stale++if ! check_auth; then+ log "FATAL: not authenticated — exiting (launchd restarts in 60s)"+ exit 1+fi++if ! probe_sync; then+ log "FATAL: key desync detected — exiting (needs manual re-pair)"+ exit 1+fi++# Bootstrap: run a one-shot sync to populate DB with chat metadata + recent messages.+# Without this, @lid chats have 0 rows and backfill/messages list returns nothing.+# NOTE: Do NOT pipe through `while read` — the pipe kills the sync prematurely.+log "SYNC: running bootstrap sync (--once) to populate DB"+BOOTSTRAP_LOG="/tmp/wacli-bootstrap-$$.log"+"$WACLI" sync --once --idle-exit=20s --refresh-contacts --refresh-groups > "$BOOTSTRAP_LOG" 2>&1 || true+BOOTSTRAP_MSGS=$(grep -o "Messages stored: [0-9]*" "$BOOTSTRAP_LOG" | grep -o "[0-9]*" || echo "0")+log "SYNC: bootstrap complete — $BOOTSTRAP_MSGS messages stored"+# Log non-noise lines+grep -vE "app state key|Failed to sync app state|Failed to do initial fetch" "$BOOTSTRAP_LOG" >> "$LOG" 2>/dev/null || true+rm -f "$BOOTSTRAP_LOG"++# Now backfill — DB should have chat metadata from bootstrap.+# Also auto-detect @lid chats with 0 messages and queue them for backfill.+auto_detect_empty_chats() {+ local chats_json+ chats_json=$("$WACLI" chats list --json 2>/dev/null) || return 0+ local backfill_file="$STORE/.backfill_jids"++ echo "$chats_json" | python3 -c "+import sys, json, subprocess, datetime+data = json.load(sys.stdin)+chats = data.get('data', []) or []+cutoff = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=7)).isoformat()+jids = []+for c in chats:+ if not c.get('JID','').endswith('@lid'): continue+ if c.get('LastMessageTS','') < cutoff: continue+ jids.append(c['JID'])+if jids:+ print('\n'.join(jids))+" > "$backfill_file" 2>/dev/null || true++ if [[ -s "$backfill_file" ]]; then+ local count+ count=$(wc -l < "$backfill_file" | tr -d ' ')+ log "AUTO-BACKFILL: detected $count recent @lid chats to backfill"+ else+ rm -f "$backfill_file"+ fi+}++auto_detect_empty_chats+run_backfill++write_health "connected" "persistent sync starting"++# Persistent sync for real-time messages. If it exits, launchd restarts us.+log "SYNC: starting persistent sync --follow"+"$WACLI" sync --follow --refresh-contacts --refresh-groups 2>&1 | while IFS= read -r line; do+ # Filter noise+ case "$line" in+ *"app state key"*|*"Failed to sync app state"*|*"Failed to do initial fetch"*) ;;+ *"ERROR"*) log "SYNC-ERR: $line" ;;+ *"Synced"*|*"Connected"*|*"Stopping"*) log "SYNC: $line" ;;+ esac+done++write_health "disconnected" "sync exited"+log "EXIT: sync process ended — launchd will restart"+exit 0diff --git a/claude-ops/skills/ops-comms/SKILL.md b/claude-ops/skills/ops-comms/SKILL.mdnew file mode 100644index 00000000..873f6db0--- /dev/null+++ b/claude-ops/skills/ops-comms/SKILL.md@@ -0,0 +1,196 @@+---+name: ops-comms+description: Send and read messages across all channels. Routes based on arguments — whatsapp, email, slack, telegram, or natural language like "send [msg] to [contact]".+argument-hint: "[channel] | send [message] to [contact] | read [channel]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - AskUserQuestion+ - mcp__claude_ai_Gmail__search_threads+ - mcp__claude_ai_Gmail__get_thread+ - mcp__claude_ai_Gmail__create_draft+ - mcp__claude_ai_Slack__slack_send_message+ - mcp__claude_ai_Slack__slack_read_channel+ - mcp__claude_ai_Slack__slack_search_users+ - mcp__claude_ai_Slack__slack_search_public_and_private+ - mcp__claude_ops_telegram__send_message+ - mcp__claude_ops_telegram__get_updates+ - mcp__claude_ops_telegram__list_chats+effort: medium+maxTurns: 40+---++# OPS ► COMMS++## Runtime Context++Before executing, load available context:++1. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/daemon-health.json`+ - Check `wacli-sync` status before any WhatsApp operation+ - Also check `~/.wacli/.health` — if not `status=connected`, surface auth issue before proceeding++2. **Ops memories**: Before drafting any message, check `${CLAUDE_PLUGIN_DATA_DIR}/memories/`:+ - `contact_*.md` — load profile for the recipient+ - `preferences.md` — match user's communication style, language, and tone+ - `donts.md` — restrictions that must not appear in any draft++3. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` for `default_channels` to determine which channel to prefer when multiple are available for a contact.++## CLI/API Reference++### wacli (WhatsApp)++**Health file** — check `~/.wacli/.health` BEFORE any wacli command:+- `status=connected` → proceed+- `status=needs_auth` or `status=needs_reauth` → prompt user for QR scan, do NOT run wacli commands++| Command | Usage | Output |+|---------|-------|--------|+| `wacli doctor --json` | Check auth/connected/lock/FTS | `{data: {authenticated, connected, lock_held, fts_enabled}}` |+| `wacli chats list --json` | All chats | `{data: [{JID, Name, Kind, LastMessageTS}]}` |+| `wacli messages list --chat "<JID>" --limit N --json` | Messages for chat | `{data: {messages: [{FromMe, Text, Timestamp, SenderName, ChatName}]}}` |+| `wacli messages search --query "<text>" --json` | FTS search | Same as above |+| `wacli contacts --search "<name>" --json` | Contact lookup | Contact objects |+| `wacli send --to "<JID>" --message "<msg>"` | Send text | Success/error |++### gog CLI (Gmail/Calendar)++| Command | Usage | Output |+|---------|-------|--------|+| `gog gmail search -j --results-only --no-input --max 30 "in:inbox"` | Search inbox | JSON array of threads |+| `gog gmail read -j --no-input "<thread_id>"` | Read thread | Full message JSON |+| `gog gmail send -j --to "<email>" --subject "<subj>" --body "<body>"` | Send email | Send result |+| `gog gmail labels modify --remove INBOX <thread_ids>` | Archive | Label change |++---++Parse `$ARGUMENTS` and route immediately:++## Routing table++| Pattern | Action |+| ------------- | ------------------------------------------------------- |+| `whatsapp` | Show WhatsApp recent chats — offer to read or send |+| `email` | Show recent email threads via Gmail MCP |+| `slack` | Show recent Slack activity |+| `telegram` | Show Telegram recent chats |+| `send * to *` | Parse message and contact, determine best channel, send |+| `read *` | Read the specified channel or contact's messages |+| (empty) | Show channel picker menu |++---++## Send flow: `send [message] to [contact]`++1. Parse contact name and message from `$ARGUMENTS`.+2. Determine channel by contact lookup:+ - Check WhatsApp: `wacli contacts --search "[contact]" --json 2>/dev/null`+ - Check Slack: `mcp__claude_ai_Slack__slack_search_users` with `query: "[contact]"`+ - Check email: known from context or ask+3. If multiple channels found, use `AskUserQuestion`: `[WhatsApp]` / `[Slack]` / `[Email]`+4. **Always preview before sending.** Use `AskUserQuestion` to confirm:++```+Ready to send via [channel]:+ To: [contact name] ([identifier])+ Message: "[full message text]"++ [Send now] [Edit message] [Cancel]+```++If user picks "Edit message", use `AskUserQuestion` with free-text to get the revised message, then re-preview.++5. Send via the chosen channel. Confirm with: `Sent to [contact] via [channel] ✓`++### WhatsApp send++**CRITICAL — READ BEFORE SENDING:** Before drafting ANY WhatsApp reply, you MUST:+1. Read the full conversation: `wacli messages list --chat "<JID>" --limit 20 --json`+2. Understand which messages are from the user (`FromMe: true`) vs the contact+3. Summarize what the conversation is about and what the contact is asking+4. Only THEN draft a reply that addresses what the contact actually said++**Never send a reply based on a single message.** A message like "can you pull it from Klaviyo?" means nothing without knowing what "it" refers to from prior messages.++**Pre-flight:** Before any wacli command, check `~/.wacli/.health`. If `status=needs_auth` or `status=needs_reauth`, prompt the user: "WhatsApp needs re-authentication. Run `wacli auth` in a separate terminal and scan the QR code, then type 'done'." Use `AskUserQuestion`: `[Done — re-paired]`, `[Skip WhatsApp]`. On Done, restart daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive`, wait 5s.++```bash+wacli send --to "[contact]" --message "[message]"+```++### Slack send++Use `mcp__claude_ai_Slack__slack_send_message` with resolved channel/user ID.++### Email send (draft)++Use `mcp__claude_ai_Gmail__create_draft` — always create draft first. Then use `AskUserQuestion`:+```+Draft created for [recipient]:+ Subject: [subject]+ Body: [preview]++ [Send now] [Keep as draft] [Edit]+```++---++## Read flow: `read [channel]`++**WhatsApp:**++```bash+wacli chats --limit 10 --json 2>/dev/null+```++Show last 10 chats with sender, preview, timestamp.++**Email:**+Use `mcp__claude_ai_Gmail__search_threads` with `query: "is:unread"`, show thread list.++**Slack:**+Use `mcp__claude_ai_Slack__slack_search_public_and_private` with `query: "is:unread"`.++**Telegram:**+Use `mcp__claude_ops_telegram__get_updates` (limit: 20) and `mcp__claude_ops_telegram__list_chats`.+Fall back to: `telegram-cli --exec "dialog_list" 2>/dev/null || echo "Telegram MCP not configured"`++### Telegram send++Use `mcp__claude_ops_telegram__send_message` with `chat_id` (from list_chats) and `text`.++---++## Empty arguments — channel picker++Display the header, then use **batched AskUserQuestion calls** (max 4 options each):++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► COMMS+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++**Before presenting options**, read `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` and check which channels are configured. Only show configured channels. If <=4 total options (configured channels + "Send a message"), present in a single call. If >4, batch:++AskUserQuestion call 1 — Read channels:+```+ [Read WhatsApp]+ [Read Email]+ [Read Slack]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Read Telegram]+ [Send a message]+```++If all channels are configured, that's 5 options — always batch. If only 3 channels are configured, "Read X" + "Read Y" + "Read Z" + "Send a message" = 4, fits in one call.++Execute the selected action.diff --git a/claude-ops/skills/ops-dash/SKILL.md b/claude-ops/skills/ops-dash/SKILL.mdnew file mode 100644index 00000000..addbc8ce--- /dev/null+++ b/claude-ops/skills/ops-dash/SKILL.md@@ -0,0 +1,355 @@+---+name: ops-dash+description: Interactive pixel-art command center dashboard. Visual business HQ with instant hotkey navigation to all ops commands, live status indicators, fire alerts, C-suite reports, settings, sharing, and FAQ.+argument-hint: "[back|settings|share|faq]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - CronCreate+ - CronList+ - CronDelete+effort: low+maxTurns: 15+disallowedTools:+ - Edit+ - Write+ - NotebookEdit+---++# OPS > DASH — Interactive Command Center++## Runtime Context++Before rendering, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `owner` — personalize the dashboard header greeting+ - `timezone` — display timestamps correctly in status indicators++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - If `action_needed` is not null → show a warning banner at the top of the dashboard before the menu++## CLI/API Reference++### bin/ops-dash++| Command | Usage | Output |+|---------|-------|--------|+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-dash` | Render full pixel-art dashboard | Formatted ASCII dashboard |+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-dash 2>/dev/null \|\| echo "DASH_RENDER_FAILED"` | Render with failure detection | Dashboard or `DASH_RENDER_FAILED` sentinel |++The bin script reads `preferences.json` and `daemon-health.json` internally. The skill reads these files separately to check for warnings before invoking the script.++---++## Render dashboard instantly++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-dash 2>/dev/null || echo "DASH_RENDER_FAILED"+```++## Your task++The dashboard has already rendered above via the shell script. Your job is to **route user input** to the right skill.++**Present the dashboard output as-is** (it's already formatted). Then immediately use AskUserQuestion:++```+ Type a number (1-9, 0), letter (a-j), or describe what you need+```++## Routing table++| Input | Route | Description |+|-------|-------|-------------|+| `1`, `go`, `morning`, `briefing` | `/ops:ops-go` | Morning briefing |+| `2`, `inbox`, `unread`, `messages` | `/ops:ops-inbox` | Inbox zero |+| `3`, `fires`, `incidents`, `down` | `/ops:ops-fires` | Fire check |+| `4`, `projects`, `portfolio` | `/ops:ops-projects` | Project dashboard |+| `5`, `next`, `priority`, `what` | `/ops:ops-next` | What's next |+| `6`, `revenue`, `costs`, `money` | `/ops:ops-revenue` | Revenue & costs |+| `7`, `linear`, `sprint`, `board` | `/ops:ops-linear` | Linear sprint |+| `8`, `deploy`, `ship` | `/ops:ops-deploy` | Deploy status |+| `9`, `triage`, `issues` | `/ops:ops-triage` | Triage issues |+| `0`, `speedup`, `clean`, `optimize` | `/ops:ops-speedup` | System speedup |+| `a`, `yolo` | `/ops:ops-yolo` | YOLO mode |+| `b`, `merge`, `prs` | `/ops:ops-merge` | Auto-merge PRs |+| `c`, `setup`, `configure` | `/ops:setup` | Setup wizard |+| `d`, `send`, `comms` | `/ops:ops-comms` | Send message |+| `e`, `report`, `csuite` | Read latest YOLO report | C-suite report |+| `f`, `settings`, `prefs`, `config` | Settings sub-menu | Interactive config |+| `g`, `share` | Share sub-menu | Share your setup |+| `h`, `faq`, `help`, `wiki`, `?` | FAQ sub-menu | Help & FAQ |+| `back`, `dash`, `home` | Re-render dashboard | Return to dash |++---++## C-suite report access (option e)++When user selects `e`:++1. Find latest YOLO session: `ls -td /tmp/yolo-*/ 2>/dev/null | head -1`+2. If found, show a sub-menu:++Display the C-suite header, then use **batched AskUserQuestion** (max 4 options per call):++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > C-SUITE REPORTS+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++AskUserQuestion call 1:+```+ [CEO — Strategic analysis]+ [CTO — Technical health]+ [CFO — Financial analysis]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [COO — Operations review]+ [All — Full Hard Truths report]+ [Back to dashboard]+```++Read the selected file and display it. After display, offer `[Back to dashboard]`.++3. If no YOLO reports exist:++```+No C-suite reports yet. Run /ops:ops-yolo to generate one.++ b) Back to dashboard+```++---++## Settings sub-menu (option f)++When user selects `f`, read current preferences and present an interactive config editor.++```bash+PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+cat "$PREFS" 2>/dev/null || echo '{}'+```++```bash+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null || echo '{}'+```++Display the full settings menu as text (for reference), then use **batched AskUserQuestion calls** (max 4 options each) to let the user pick a category:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > SETTINGS+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ PROFILE: Owner=[value] | TZ=[value] | Style=[value]+ CHANNELS: Email=[✓/✗] | WA=[✓/✗] | Slack=[✓/✗] | Telegram=[✓/✗]+ INTEGRATIONS: AWS=[value] | Sentry=[value] | Linear=[value]+ PROJECTS: [N] registered+ PLUGIN: v[version]+──────────────────────────────────────────────────────+```++Use AskUserQuestion (max 4 options):+```+What would you like to configure?+ [Profile (name/timezone/style)]+ [Channels (email/WA/slack/telegram)]+ [Integrations & Projects]+ [Back to dashboard]+```++On "Profile": use AskUserQuestion with `[Owner name]`, `[Timezone]`, `[Briefing style]`, `[Back]`.+On "Channels": use AskUserQuestion with the 4 channel names (fits in one call).+On "Integrations & Projects": use AskUserQuestion with `[AWS/Sentry/Linear]`, `[View registry]`, `[Add/remove project]`, `[Update plugin / Re-run setup]`.++For each option, use AskUserQuestion to get the new value, then write to preferences.json or registry.json.++**Writing preferences:**+```bash+PREFS="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+# Read existing, merge update, write back+jq --arg key "owner" --arg val "$NEW_VALUE" '.[$key] = $val' "$PREFS" > "${PREFS}.tmp" && mv "${PREFS}.tmp" "$PREFS"+```++After each change, confirm success and return to the settings menu. User can keep making changes or press `b` to go back.++---++## Share sub-menu (option g)++When user selects `g`, generate a shareable summary of their ops setup:++Display the share header, then use **batched AskUserQuestion** (max 4 options per call):++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > SHARE YOUR SETUP+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++AskUserQuestion call 1:+```+ [Share on X (Twitter)]+ [Share via Slack]+ [Share via Email]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Copy to clipboard]+ [Export setup guide (markdown)]+ [Back to dashboard]+```++### Share content generation++Generate a share-ready message. **Never include secrets, tokens, or private project names.** Only share:+- Plugin version+- Number of integrations configured+- Number of projects managed+- OS and system info+- Feature highlights used++**Template:**++```+I'm running my business from Claude Code with claude-ops v0.3.1++Setup: [N] projects | [N] channels | [OS]+Features: Morning briefing, inbox zero, fire alerts, C-suite AI analysis, system optimizer++Try it: /plugin marketplace add ops-marketplace++#ClaudeCode #DevOps #AI+```++### Share actions++| Option | Action |+|--------|--------|+| X/Twitter | Copy text to clipboard + open `https://twitter.com/intent/tweet?text=...` via `open` (macOS) or `xdg-open` (Linux) |+| Slack | Send via `/ops:ops-comms slack` with generated message |+| Email | Draft via `gog gmail send` or copy to clipboard |+| Clipboard | `pbcopy` (macOS) / `xclip -selection clipboard` (Linux) / `clip.exe` (WSL) |+| Export | Write a `~/.claude-ops-setup.md` file with full (sanitized) setup guide for sharing with teammates |++---++## FAQ sub-menu (option h)++When user selects `h`:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > HELP & FAQ+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ QUICK START+ 1) What is claude-ops?+ 2) How do I set up channels?+ 3) How does YOLO mode work?+ 4) What data does ops collect?++ COMMANDS+ 5) Full command reference+ 6) Keyboard shortcuts++ TROUBLESHOOTING+ 7) MCP server disconnected+ 8) WhatsApp not connecting+ 9) Telegram auth issues+ 10) Channel not showing unread++ LINKS+ w) Wiki — github.com/Lifecycle-Innovations-Limited/claude-ops/wiki+ r) README — github.com/Lifecycle-Innovations-Limited/claude-ops+ i) Issues — github.com/Lifecycle-Innovations-Limited/claude-ops/issues+ c) Changelog++──────────────────────────────────────────────────────+ b) Back to dashboard+──────────────────────────────────────────────────────+```++### FAQ answers++| # | Question | Answer |+|---|----------|--------|+| 1 | What is claude-ops? | Business operations OS for Claude Code. Manages inbox, fires, deploys, PRs, revenue, and can run your business autonomously via YOLO mode. |+| 2 | Channel setup | Run `/ops:setup` — interactive wizard detects installed CLIs and walks you through each channel. |+| 3 | YOLO mode | Spawns 4 AI agents (CEO, CTO, CFO, COO) to analyze your business. Type YOLO to hand over controls — it processes inbox, fixes fires, merges PRs, and advances GSD phases. |+| 4 | Data collection | All data stays local. No telemetry. Registry and preferences are gitignored. Tokens stored in macOS keychain or env vars. |+| 5 | Command reference | List all `/ops:*` commands with descriptions |+| 6 | Shortcuts | `1-9, 0` for actions, `a-h` for power/comms/settings, `b` always goes back, `q` exits |+| 7 | MCP disconnected | Wait 5s and retry (auto-reconnect hook). After 3 fails, falls back to CLI tools. |+| 8 | WhatsApp | First check `~/.wacli/.health` — if `status` is not `connected`, surface the auth warning before running `wacli doctor`. Check `wacli doctor`. If 405 error: rebuild from source. If store locked: `kill $(pgrep wacli)`. |+| 9 | Telegram | Needs user-auth (not bot). Run `/ops:setup` → Telegram section. API ID + hash from my.telegram.org. |+| 10 | Unread | Channel must be configured in `/ops:setup`. Check `ops-unread` script output for errors. |++For links (w, r, i): open in browser via `open` (macOS) or `xdg-open` (Linux).++For changelog (c): read and display `${CLAUDE_PLUGIN_ROOT}/CHANGELOG.md`.++After each FAQ answer, offer `b) Back to dashboard` or `h) Back to FAQ`.++---++## Return-to-dash loop++After ANY skill completes and returns control, **re-render the dashboard** by running the bin script again and re-entering the routing loop. This creates the "app within an app" experience — the user always comes back to the command center.++To re-render:+```bash+${CLAUDE_PLUGIN_ROOT}/bin/ops-dash 2>/dev/null+```++Then AskUserQuestion again for the next action.++**Exception**: If user types `q`, `quit`, or `exit`, end the session gracefully:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > SESSION ENDED+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++## If `$ARGUMENTS` is `back`++Re-render the dashboard and enter routing loop.++## If `$ARGUMENTS` is `settings`++Jump directly to settings sub-menu (skip dashboard render).++## If `$ARGUMENTS` is `share`++Jump directly to share sub-menu.++## If `$ARGUMENTS` is `faq`++Jump directly to FAQ sub-menu.++## Setup gate++If the dashboard script outputs `DASH_RENDER_FAILED` or the preferences file doesn't exist, show:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > SETUP REQUIRED+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ Run /ops:setup to configure your integrations first.+```++Then invoke `/ops:setup` directly.diff --git a/claude-ops/skills/ops-deploy/SKILL.md b/claude-ops/skills/ops-deploy/SKILL.mdnew file mode 100644index 00000000..4798187c--- /dev/null+++ b/claude-ops/skills/ops-deploy/SKILL.md@@ -0,0 +1,201 @@+---+name: ops-deploy+description: Deploy status across all projects. Shows ECS service versions, Vercel deployments, recent deploys, pending deploys, and CI/CD pipeline state.+argument-hint: "[project-alias|ecs|vercel|all]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TaskCreate+ - TaskUpdate+ - Monitor+ - WebFetch+ - mcp__claude_ai_Vercel__list_deployments+ - mcp__claude_ai_Vercel__list_projects+ - mcp__claude_ai_Vercel__get_deployment+ - mcp__claude_ai_Vercel__get_runtime_logs+ - mcp__claude_ai_Vercel__get_deployment_build_logs+effort: low+maxTurns: 20+disallowedTools:+ - Edit+ - Write+ - NotebookEdit+---++# OPS ► DEPLOY STATUS++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `timezone` — display all deploy timestamps in the correct timezone++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - Check `infra-monitor` status — if not running, note that ECS data may be stale++3. **Secrets**: AWS and Vercel credentials required.+ ### Secret Resolution+ - AWS: check `$AWS_PROFILE` / `$AWS_ACCESS_KEY_ID` → `doppler secrets get AWS_ACCESS_KEY_ID --plain` → vault query cmd from prefs+ - Vercel token: check `$VERCEL_TOKEN` → `doppler secrets get VERCEL_TOKEN --plain` → vault++## CLI/API Reference++### aws CLI++| Command | Usage | Output |+|---------|-------|--------|+| `aws ecs list-clusters --output json` | All ECS clusters | `{clusterArns: [...]}` |+| `aws ecs list-services --cluster <name> --output json` | Services in cluster | `{serviceArns: [...]}` |+| `aws ecs describe-services --cluster <name> --services <arn> --output json` | Service health | `{services: [{serviceName, status, runningCount, desiredCount, pendingCount}]}` |+| `aws logs tail /ecs/<service> --since 1h --format short` | ECS logs | Log lines |++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh run list --repo <owner/repo> --limit 5 --json status,conclusion,name,headBranch,createdAt,databaseId` | CI runs | JSON array |+| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |+| `gh run watch <run-id> --repo <repo>` | Stream CI run | Live output (use with Monitor) |++---++## Phase 1 — Gather deploy data in parallel++### ECS services (all clusters)++```bash+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || \+aws ecs list-clusters --output json 2>/dev/null+```++### ECS service details++```bash+for cluster in $(aws ecs list-clusters --output json 2>/dev/null | jq -r '.clusterArns[]'); do+ cluster_name=$(basename "$cluster")+ aws ecs list-services --cluster "$cluster_name" --output json 2>/dev/null | \+ jq -r '.serviceArns[]' | while read svc; do+ aws ecs describe-services --cluster "$cluster_name" --services "$svc" \+ --output json 2>/dev/null | jq '.services[] | {name: .serviceName, desired: .desiredCount, running: .runningCount, pending: .pendingCount, image: (.taskDefinition // "unknown"), status: .status}'+ done+done+```++### Recent GitHub Actions runs (registry-driven)++```bash+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+[ -f "$REGISTRY" ] || REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.example.json"+for repo in $(jq -r '.projects[] | select(.gsd == true) | .repos[]' "$REGISTRY" 2>/dev/null); do+ echo "=== $repo ==="+ gh run list --repo "$repo" --limit 5 --json status,conclusion,name,headBranch,createdAt,databaseId 2>/dev/null+done+```++### Vercel deployments++Use `mcp__claude_ai_Vercel__list_projects` then `mcp__claude_ai_Vercel__list_deployments` for each project (limit 5 per project).++---++## Phase 2 — Render dashboard++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► DEPLOY STATUS — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ECS SERVICES+ CLUSTER SERVICE D/R/P STATUS LAST DEPLOY+ ─────────────────────────────────────────────────────+ [cluster] [service] [x/x/x] ACTIVE [time ago]+ ...++VERCEL DEPLOYMENTS+ PROJECT ENV STATUS COMMIT DEPLOYED+ ─────────────────────────────────────────────────────+ [project] production READY [sha] [time ago]+ ...++CI/CD PIPELINE+ REPO BRANCH WORKFLOW STATUS AGE+ ─────────────────────────────────────────────────────+ example-api main Deploy API ✓ success 2h+ example-web dev Build ✗ failure 1h+ ...++PENDING DEPLOYS (branch ready, not yet deployed)+ [repo] [branch] [PR#] [CI status] → needs merge to trigger++──────────────────────────────────────────────────────+```++After rendering, use **batched AskUserQuestion calls** (max 4 options each). Only show actions relevant to the current state (e.g., skip "View logs for failing service" if nothing is failing). If <=4 relevant actions, use a single call. If >4, batch:++AskUserQuestion call 1:+```+ [View logs for [failing service]]+ [Trigger manual deploy for [project]]+ [View build logs for [failing CI run]]+ [More actions...]+```++AskUserQuestion call 2 (only if "More actions..."):+```+ [Check Vercel [project] runtime logs]+ [Open GitHub Actions for [repo]]+ [Back to dashboard]+```++---++## Deep-dive by project++If `$ARGUMENTS` has a project alias, show only that project's deploy info + last 10 CI runs + option to view logs.++For failing deploys: offer to view logs via `mcp__claude_ai_Vercel__get_deployment_build_logs` or ECS CloudWatch logs.++**If user selects manual deploy (option b)**, confirm with `AskUserQuestion` before triggering:++```+Trigger deploy for [project]:+ Environment: [production/staging]+ Branch: [branch]+ Last commit: [sha] — [message]++ [Deploy now] [View diff since last deploy first] [Cancel]+```++**If user selects to view logs**, show the logs and use `AskUserQuestion`:+```+ [Dispatch fix agent for this failure] [Redeploy] [Back to dashboard]+```++---++## Native tool usage++### Monitor — live deploy streaming++When watching a deploy in progress, use `Monitor` to stream logs:+```+Monitor(command: "gh run watch <run-id> --repo <repo>")+```+For ECS deploys: `Monitor(command: "aws ecs wait services-stable --cluster <cluster> --services <service>")`++### Tasks — deploy tracking++Use `TaskCreate` per project being deployed. Update with `TaskUpdate` as deploys succeed/fail.++### WebFetch — Vercel fallback++When Vercel MCP tools are unavailable, use `WebFetch` with the Vercel API directly:+```+WebFetch(url: "https://api.vercel.com/v6/deployments?projectId=<id>&limit=5", headers: {"Authorization": "Bearer $VERCEL_TOKEN"})+```diff --git a/claude-ops/skills/ops-doctor/SKILL.md b/claude-ops/skills/ops-doctor/SKILL.mdnew file mode 100644index 00000000..0ae67020--- /dev/null+++ b/claude-ops/skills/ops-doctor/SKILL.md@@ -0,0 +1,128 @@+---+name: ops-doctor+description: Health check and auto-repair for the ops plugin. Diagnoses manifest errors, broken permissions, invalid configs, stale caches, and missing files — then spawns an agent to fix everything automatically.+argument-hint: "[--check-only|--verbose]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Agent+ - AskUserQuestion+ - WebSearch+ - WebFetch+effort: medium+maxTurns: 30+---++## Runtime Context++Before diagnosing, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — check all configured channels and services+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — primary diagnostic input+3. **Secrets**: Verify secret resolution chain works: env → Doppler → password manager+++# OPS ► DOCTOR++## CLI/API Reference++### ops-doctor bin script++| Command | Usage | Output |+|---------|-------|--------|+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-doctor` | Run full health diagnostics | JSON with `errors`, `warnings`, `tools`, `env_vars`, `registry` |+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-doctor 2>/dev/null \|\| echo '{"errors":["diagnostic_script_failed"]}'` | Run with fallback | JSON or error sentinel |++### Key files read by diagnostics++| File | Purpose |+|------|---------|+| `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` | Primary daemon health input |+| `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` | Configured channels and services |+| `${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json` | Plugin manifest validation |+| `${CLAUDE_PLUGIN_ROOT}/scripts/registry.json` | Project registry validation |++---++## Phase 1 — Run diagnostics++Run the diagnostic script to get a full health report:++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-doctor 2>/dev/null || echo '{"errors":["diagnostic_script_failed"],"warnings":[]}'+```++Parse the JSON output. Display a summary:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► DOCTOR — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ Plugin: [version] at [plugin_root]+ Skills: [count] defined+ Agents: [count] defined+ Bin scripts:[count] available++ ERRORS [count]+ [list each error with description]++ WARNINGS [count]+ [list each warning with description]++ TOOLS+ [table of CLI tool availability]++ ENV VARS+ [table of env var status]++ Registry: [status] ([project_count] projects)+ Preferences:[status]+ Cache: [versions list]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++## Phase 2 — Decision++If `$ARGUMENTS` contains `--check-only`: stop here, display results only.++If there are **errors or warnings**:++Display: "Found [N] issues. Spawning doctor agent to auto-fix..."++Then spawn the doctor agent:++```+Agent({+ subagent_type: "ops:doctor-agent",+ prompt: "Fix the following ops plugin issues.\n\nDIAGNOSTIC_JSON: [paste full JSON]\nPLUGIN_ROOT: ${CLAUDE_PLUGIN_ROOT}\nCACHE_DIR: ~/.claude/plugins/cache/ops-marketplace/ops\n\nFix all errors and warnings. Re-run diagnostics after to verify.",+ description: "Fix ops plugin issues"+})+```++If there are **no errors and no warnings**:++Display: "All checks passed. Plugin is healthy."++## Phase 3 — Post-fix verification++After the agent completes, re-run diagnostics:++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-doctor 2>/dev/null+```++Display updated results. If errors remain, report them to the user with manual fix instructions.++---++## Native tool usage++### WebSearch — known issue lookup++When diagnostics find errors, use `WebSearch` to check if the issue is a known Claude Code plugin bug, MCP server issue, or configuration problem. Include links to relevant GitHub issues or docs.++### WebFetch — MCP health check++For MCP servers that appear disconnected, use `WebFetch` to test their underlying APIs directly (e.g., `https://api.linear.app/graphql` with a simple query) to distinguish between "MCP broken" and "API down".diff --git a/claude-ops/skills/ops-ecom/SKILL.md b/claude-ops/skills/ops-ecom/SKILL.mdnew file mode 100644index 00000000..6daf9e54--- /dev/null+++ b/claude-ops/skills/ops-ecom/SKILL.md@@ -0,0 +1,526 @@+---+name: ops-ecom+description: Shopify store command center. Orders, inventory, fulfillment, analytics, and store health. Works with any Shopify store via Admin API.+argument-hint: "[orders|inventory|fulfillment|health|products|customers|analytics|setup]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Grep+ - Glob+ - Agent+ - AskUserQuestion+ - WebFetch+ - WebSearch+effort: medium+maxTurns: 40+---++# OPS ► ECOM — Shopify Store Command Center++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `timezone` — display all timestamps correctly+ - `shopify_store_url`, `shopify_admin_token` — check userConfig keys before env vars++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - If `action_needed` is not null → surface it before running any store operations++3. **Secrets**: Resolve Shopify credentials via userConfig → env vars → Doppler (see Phase 1 below)++## CLI/API Reference++### Shopify Admin REST API++| Endpoint | Method | Description |+|----------|--------|-------------|+| `/admin/api/2024-10/shop.json` | GET | Store info and plan |+| `/admin/api/2024-10/orders.json?status=any&limit=50` | GET | Recent orders |+| `/admin/api/2024-10/products.json?limit=250` | GET | Product catalog |+| `/admin/api/2024-10/customers.json?limit=50` | GET | Customer list |+| `/admin/api/2024-10/themes.json` | GET | Theme list |+| `/admin/api/2024-10/variants/${ID}.json` | PUT | Update variant price |++**Auth header**: `X-Shopify-Access-Token: ${SHOPIFY_TOKEN}`++### ShipBob API (optional)++| Endpoint | Method | Description |+|----------|--------|-------------|+| `https://api.shipbob.com/1.0/shipment?Status=Processing&PageSize=20` | GET | Pending shipments |++**Auth header**: `Authorization: Bearer ${SHIPBOB_TOKEN}`++## Phase 1 — Resolve credentials++Resolve Shopify credentials in this order:++```bash+# 1. Plugin userConfig+SHOPIFY_STORE="${user_config.shopify_store_url}"+SHOPIFY_TOKEN="${user_config.shopify_admin_token}"+SHIPBOB_TOKEN="${user_config.shipbob_access_token}"++# 2. Environment variables (override userConfig if set)+[ -n "$SHOPIFY_STORE_URL" ] && SHOPIFY_STORE="$SHOPIFY_STORE_URL"+[ -n "$SHOPIFY_ACCESS_TOKEN" ] && SHOPIFY_TOKEN="$SHOPIFY_ACCESS_TOKEN"+[ -n "$SHIPBOB_ACCESS_TOKEN" ] && SHIPBOB_TOKEN="$SHIPBOB_ACCESS_TOKEN"++# 3. Doppler fallback+if [ -z "$SHOPIFY_TOKEN" ] && command -v doppler &>/dev/null; then+ SHOPIFY_TOKEN=$(doppler secrets get SHOPIFY_ACCESS_TOKEN --plain 2>/dev/null)+fi+if [ -z "$SHOPIFY_STORE" ] && command -v doppler &>/dev/null; then+ SHOPIFY_STORE=$(doppler secrets get SHOPIFY_STORE_URL --plain 2>/dev/null)+fi+if [ -z "$SHIPBOB_TOKEN" ] && command -v doppler &>/dev/null; then+ SHIPBOB_TOKEN=$(doppler secrets get SHIPBOB_ACCESS_TOKEN --plain 2>/dev/null)+fi+```++If `$SHOPIFY_STORE` or `$SHOPIFY_TOKEN` is still empty after all resolution steps, route to **setup flow** below.++Set base URLs:+```bash+SHOPIFY_BASE="https://${SHOPIFY_STORE}/admin/api/2024-10"+SHOPIFY_GQL="https://${SHOPIFY_STORE}/admin/api/2024-10/graphql.json"+SHOPIFY_AUTH="X-Shopify-Access-Token: ${SHOPIFY_TOKEN}"+```++---++## Phase 2 — Route by $ARGUMENTS++| Input | Action |+| ------------------------------------------ | ------------------- |+| (empty) | Show store summary |+| orders, order | Orders dashboard |+| inventory, stock, inv | Inventory levels |+| fulfillment, fulfill, shipbob, shipping | Fulfillment status |+| health, check, status | Store health check |+| products, product, catalog | Products manager |+| customers, customer, crm | Customer stats |+| analytics, revenue, stats, metrics | Analytics dashboard |+| setup, configure, init, token | Setup flow |++---++## ORDERS++Fetch recent orders and compute revenue:++```bash+TODAY=$(date -u +"%Y-%m-%dT00:00:00Z")+WEEK_AGO=$(date -u -v-7d +"%Y-%m-%dT00:00:00Z" 2>/dev/null || date -u -d "7 days ago" +"%Y-%m-%dT00:00:00Z")+MONTH_AGO=$(date -u -v-30d +"%Y-%m-%dT00:00:00Z" 2>/dev/null || date -u -d "30 days ago" +"%Y-%m-%dT00:00:00Z")++# Recent orders (last 50)+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/orders.json?status=any&limit=50&order=created_at+desc" | \+ jq '{+ total: .orders | length,+ today: [.orders[] | select(.created_at >= "'"$TODAY"'")],+ orders: [.orders[:10] | .[] | {+ id: .order_number,+ name: .name,+ status: .financial_status,+ fulfillment: .fulfillment_status,+ total: .total_price,+ currency: .currency,+ customer: (.customer.first_name + " " + .customer.last_name),+ created: .created_at+ }]+ }'+```++Render:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM ► ORDERS — [store] — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++REVENUE+ Today [N orders] $[amount]+ 7 days [N orders] $[amount]+ 30 days [N orders] $[amount]++RECENT ORDERS+ #[id] [customer] $[total] [status] / [fulfillment] [age]+ ...++──────────────────────────────────────────────────────+ Actions:+ a) View order details for #[id]+ b) Mark order as fulfilled+ c) Export orders CSV+ d) Filter by status (unfulfilled/refunded/paid)+──────────────────────────────────────────────────────+```++Use `AskUserQuestion` for action selection.++---++## INVENTORY++Fetch all products and variant inventory:++```bash+# Get all products with variants+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/products.json?limit=250&fields=id,title,status,variants" | \+ jq '[.products[] | {+ id: .id,+ title: .title,+ status: .status,+ variants: [.variants[] | {+ id: .id,+ title: .title,+ sku: .sku,+ inventory_quantity: .inventory_quantity,+ inventory_policy: .inventory_policy+ }]+ }]'+```++Flag low stock (inventory_quantity < 10) and out-of-stock (inventory_quantity <= 0).++Render:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM ► INVENTORY — [store] — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++OUT OF STOCK+ [product] — [variant] — SKU: [sku]++LOW STOCK (< 10 units)+ [product] — [variant] — [N] units — SKU: [sku]++ALL PRODUCTS+ [product]+ [variant] [N] units SKU: [sku]+ ...++──────────────────────────────────────────────────────+ Actions:+ a) Update inventory for [product]+ b) Export inventory CSV+ c) Set reorder alerts+──────────────────────────────────────────────────────+```++Use `AskUserQuestion` for action selection.++---++## FULFILLMENT++Fetch unfulfilled orders and ShipBob status (if token available):++```bash+# Unfulfilled orders+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/orders.json?fulfillment_status=unfulfilled&status=open&limit=50" | \+ jq '[.orders[] | {+ id: .order_number,+ name: .name,+ customer: (.customer.first_name + " " + .customer.last_name),+ total: .total_price,+ created: .created_at,+ items: [.line_items[] | {title: .title, qty: .quantity}]+ }]'++# Shipments with tracking (fulfilled)+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/orders.json?fulfillment_status=fulfilled&status=any&limit=20&order=updated_at+desc" | \+ jq '[.orders[] | .fulfillments[] | {+ order: .order_id,+ tracking_number: .tracking_number,+ tracking_url: .tracking_url,+ shipment_status: .shipment_status,+ carrier: .tracking_company,+ updated: .updated_at+ }]'+```++If `$SHIPBOB_TOKEN` is set, also query ShipBob:++```bash+# ShipBob pending shipments+curl -s -H "Authorization: Bearer ${SHIPBOB_TOKEN}" \+ "https://api.shipbob.com/1.0/shipment?Status=Processing&PageSize=20" | \+ jq '[.[] | {+ id: .id,+ status: .status,+ order_id: .reference_id,+ tracking: .tracking_number,+ created: .created_date+ }]'+```++Render fulfillment dashboard with pending/in-transit/delivered counts.++Use `AskUserQuestion` for action selection (mark fulfilled, update tracking, etc.).++---++## HEALTH++Run the health check script, then augment with API checks:++```bash+${CLAUDE_PLUGIN_ROOT}/bin/ops-ecom-health 2>/dev/null || echo '{"error":"health script unavailable"}'+```++Also check:++```bash+# Active theme+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/themes.json" | \+ jq '[.themes[] | select(.role == "main") | {id: .id, name: .name, updated: .updated_at}]'++# Store info+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/shop.json" | \+ jq '.shop | {name: .name, domain: .domain, country: .country_name, plan: .plan_display_name, currency: .currency, timezone: .timezone}'+```++Render:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM ► HEALTH — [store] — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++STORE+ Name: [name]+ Plan: [plan]+ Currency: [currency]+ Timezone: [tz]++API CONNECTIVITY [OK / FAIL]+ACTIVE THEME [theme name]+PRODUCT COUNT [N] active+ORDERS (24h) [N] orders++ISSUES+ [any warnings from health check]++──────────────────────────────────────────────────────+ Actions:+ a) Check theme assets for errors+ b) Run full SEO audit+ c) View API rate limit status+──────────────────────────────────────────────────────+```++Use `AskUserQuestion` for action selection.++---++## PRODUCTS++List, search, and manage products:++```bash+# All products+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/products.json?limit=250&order=updated_at+desc" | \+ jq '[.products[] | {+ id: .id,+ title: .title,+ status: .status,+ handle: .handle,+ price: (.variants[0].price // "N/A"),+ inventory: ([.variants[].inventory_quantity] | add // 0),+ variants: (.variants | length),+ updated: .updated_at+ }]'+```++If `$ARGUMENTS` contains a search term (e.g., `products shoes`), filter by title.++For price updates, use:++```bash+# Update variant price+curl -s -X PUT -H "$SHOPIFY_AUTH" -H "Content-Type: application/json" \+ "${SHOPIFY_BASE}/variants/${VARIANT_ID}.json" \+ -d '{"variant":{"id":'${VARIANT_ID}',"price":"'${NEW_PRICE}'"}}'+```++Use `AskUserQuestion` before making any product updates. Show before/after prices.++---++## CUSTOMERS++Fetch customer stats:++```bash+# Customer count and recent+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/customers.json?limit=50&order=created_at+desc" | \+ jq '{+ total_shown: (.customers | length),+ recent: [.customers[:10] | .[] | {+ id: .id,+ name: (.first_name + " " + .last_name),+ email: .email,+ orders: .orders_count,+ total_spent: .total_spent,+ currency: .currency,+ created: .created_at+ }]+ }'++# Top customers by spend+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/customers.json?limit=10&order=total_spent+desc" | \+ jq '[.customers[] | {name: (.first_name + " " + .last_name), orders: .orders_count, spent: .total_spent}]'+```++Render customer overview with LTV stats and top spenders.++---++## ANALYTICS++Pull revenue and order data for dashboard:++```bash+TODAY=$(date -u +"%Y-%m-%dT00:00:00Z")+WEEK_AGO=$(date -u -v-7d +"%Y-%m-%dT00:00:00Z" 2>/dev/null || date -u -d "7 days ago" +"%Y-%m-%dT00:00:00Z")+MONTH_AGO=$(date -u -v-30d +"%Y-%m-%dT00:00:00Z" 2>/dev/null || date -u -d "30 days ago" +"%Y-%m-%dT00:00:00Z")++# Orders for revenue calculation+curl -s -H "$SHOPIFY_AUTH" \+ "${SHOPIFY_BASE}/orders.json?status=any&financial_status=paid&created_at_min=${MONTH_AGO}&limit=250" | \+ jq '{+ month_orders: (.orders | length),+ month_revenue: ([.orders[].total_price | tonumber] | add // 0),+ week_orders: ([.orders[] | select(.created_at >= "'"$WEEK_AGO"'")] | length),+ week_revenue: ([.orders[] | select(.created_at >= "'"$WEEK_AGO"'") | .total_price | tonumber] | add // 0),+ today_orders: ([.orders[] | select(.created_at >= "'"$TODAY"'")] | length),+ today_revenue: ([.orders[] | select(.created_at >= "'"$TODAY"'") | .total_price | tonumber] | add // 0),+ avg_order_value: ([.orders[].total_price | tonumber] | (add // 0) / (length // 1)),+ top_products: ([.orders[].line_items[] | {title: .title, qty: .quantity}] | group_by(.title) | map({title: .[0].title, total_qty: map(.qty) | add}) | sort_by(-.total_qty)[:5])+ }'+```++Render:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM ► ANALYTICS — [store] — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++REVENUE+ Today $[amount] ([N] orders)+ 7 days $[amount] ([N] orders)+ 30 days $[amount] ([N] orders)++AVERAGES+ AOV (30d) $[amount]++TOP PRODUCTS (30d)+ 1. [product] [N] sold+ 2. [product] [N] sold+ ...++──────────────────────────────────────────────────────+ Actions:+ a) Export revenue report (CSV)+ b) View by product breakdown+ c) Compare to previous period+──────────────────────────────────────────────────────+```++Use `AskUserQuestion` for action selection.++---++## SETUP FLOW++Guide the user through configuring Shopify credentials:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM ► SETUP+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++To connect your Shopify store, you need:++1. Store URL (e.g., mystore.myshopify.com)+2. Admin API access token (shpat_...)++To get your Admin API token:+ 1. Go to your Shopify Admin > Settings > Apps and sales channels+ 2. Click "Develop apps" > "Create an app"+ 3. Under "Configuration", enable Admin API scopes:+ read_orders, write_orders, read_products, write_products,+ read_customers, read_inventory, write_inventory,+ read_fulfillments, write_fulfillments, read_analytics+ 4. Click "Install app" to generate the access token+ 5. Copy the token (starts with shpat_)++Store the credentials via one of:+ a) Plugin userConfig: set shopify_store_url + shopify_admin_token+ b) Environment: export SHOPIFY_STORE_URL=... SHOPIFY_ACCESS_TOKEN=...+ c) Doppler: doppler secrets set SHOPIFY_STORE_URL SHOPIFY_ACCESS_TOKEN++ShipBob (optional):+ Get your Personal Access Token from app.shipbob.com > Developer > API+ Store as shipbob_access_token in userConfig or $SHIPBOB_ACCESS_TOKEN+```++Use `AskUserQuestion` to collect store URL, then verify connectivity:++```bash+curl -s -H "X-Shopify-Access-Token: ${PROVIDED_TOKEN}" \+ "https://${PROVIDED_STORE}/admin/api/2024-10/shop.json" | \+ jq '.shop | {name, domain, plan: .plan_display_name}'+```++If the connectivity check returns valid shop data, confirm success. If it fails with 401/403, explain the token is invalid and re-prompt.++---++## STORE SUMMARY (empty $ARGUMENTS)++When called with no arguments, show a compact store overview:++Run orders, inventory, and health checks in parallel (separate Bash calls), then render:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ECOM — [store] — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++STORE [name] ([plan])+CURRENCY [currency]++TODAY $[revenue] [N] orders+7 DAYS $[revenue] [N] orders+30 DAYS $[revenue] [N] orders++INVENTORY [N] products | [N] low stock | [N] out of stock+FULFILLMENT [N] unfulfilled orders pending++──────────────────────────────────────────────────────+ /ops:ops-ecom orders — order management+ /ops:ops-ecom inventory — stock levels+ /ops:ops-ecom products — product catalog+ /ops:ops-ecom customers — customer stats+ /ops:ops-ecom analytics — revenue dashboard+ /ops:ops-ecom health — store health check+ /ops:ops-ecom setup — configure credentials+──────────────────────────────────────────────────────+```diff --git a/claude-ops/skills/ops-fires/SKILL.md b/claude-ops/skills/ops-fires/SKILL.mdnew file mode 100644index 00000000..2ae4b5c7--- /dev/null+++ b/claude-ops/skills/ops-fires/SKILL.md@@ -0,0 +1,217 @@+---+name: ops-fires+description: Production incidents dashboard. Reads ECS health, Sentry errors, CI failures. Offers to dispatch fix agents for active fires.+argument-hint: "[project-alias|all]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - TaskCreate+ - TaskUpdate+ - Monitor+ - WebFetch+ - WebSearch+ - mcp__sentry__search_issues+ - mcp__sentry__get_issue_details+effort: medium+maxTurns: 30+---++# OPS ► FIRES++## Runtime Context++Before executing, load available context:++1. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/daemon-health.json`+ - Check `infra-monitor` service status — if not running, pre-gathered infra data may be stale+ - If `action_needed` is not null → surface it immediately as a potential fire++2. **Secrets**: AWS credentials are required for ECS/CloudWatch queries.+ ### Secret Resolution+ - First: check `$AWS_ACCESS_KEY_ID` / `$AWS_PROFILE` env vars+ - Then: `doppler secrets get AWS_ACCESS_KEY_ID --plain` (if `doppler` configured in prefs)+ - Then: use `password_manager_config.query_cmd` from preferences+ - Sentry token: `$SENTRY_AUTH_TOKEN` → Doppler `SENTRY_AUTH_TOKEN` → vault++3. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` for `secrets_manager` config to know which vault to query.++## CLI/API Reference++### aws CLI++| Command | Usage | Output |+|---------|-------|--------|+| `aws ecs list-services --cluster <name> --query 'serviceArns'` | ECS services | ARN list |+| `aws ecs describe-services --cluster <name> --services <arn> --query 'services[0].{status:status,running:runningCount,desired:desiredCount}'` | Service health | JSON |+| `aws logs tail /ecs/<service> --since 1h --format short` | ECS logs | Log lines (use with Monitor for live) |++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh run list --limit 20 --json status,conclusion,name,headBranch,createdAt` | Recent CI runs | JSON array |+| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |++### sentry-cli / Sentry API++| Command | Usage | Output |+|---------|-------|--------|+| `sentry-cli issues list --project <slug> --status unresolved` | Unresolved issues | Issue list |+| `curl -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" "https://sentry.io/api/0/projects/<org>/<proj>/issues/?query=is:unresolved"` | API fallback when MCP unavailable | JSON array |++---++## Agent Teams support++If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** when dispatching multiple fix agents simultaneously. This enables:+- Fix agents share findings (e.g., API agent discovers DB is the root cause → infra agent pivots to DB fix)+- You can prioritize: "CRITICAL ECS issue first, then CI failures"+- Real-time progress: agents report as they find root causes, you can merge fixes in optimal order++**Team setup** (only when flag is enabled, dispatch phase):+```+TeamCreate("fire-fixers")+Agent(team_name="fire-fixers", name="fix-[service]", ...)+```++If the flag is NOT set, use standard parallel subagents.++## Pre-gathered infrastructure data++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || echo '{"clusters":[],"error":"infra check failed"}'+```++## CI failures (last 24h)++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-ci 2>/dev/null || echo '[]'+```++## Your task++Analyze the pre-gathered data. Then run parallel checks:++1. **ECS health** — parse infra data for unhealthy services, stopped tasks, failed deployments.+2. **Sentry** — if Sentry MCP is connected, query recent unresolved errors. Otherwise note it's unavailable.+3. **CI** — parse CI data for failing pipelines, broken main/dev branches.+4. **GitHub Actions** — `gh run list --limit 20 --json status,conclusion,name,headBranch,createdAt 2>/dev/null`++Classify each issue by severity:++| Severity | Criteria |+| -------- | ------------------------------------------------- |+| CRITICAL | Service down, DB unreachable, auth broken |+| HIGH | Elevated error rate, deploy stuck, CI main broken |+| MEDIUM | Non-critical service degraded, flaky tests |+| LOW | Warning-level, non-urgent |++---++## Output format++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► FIRES DASHBOARD — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++CRITICAL+[service] — [issue] — [since]++HIGH+[service] — [issue] — [since]++MEDIUM+[service] — [issue] — [since]++ECS HEALTH+[cluster] [service] [desired/running] [status]++CI STATUS+[repo] [branch] [workflow] [status] [last run]++SENTRY (top errors, 24h)+[error] [count] [first seen] [project]++──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each). Only show relevant actions (e.g., skip dispatch options if no issues found):++AskUserQuestion call 1:+```+ [Dispatch fix agent for [top critical issue]]+ [Dispatch fix agent for [second issue]]+ [View logs for [service]]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Open Sentry dashboard]+ [Open GitHub Actions]+ [All clear — nothing to do]+```++If no fires: show "ALL SYSTEMS OPERATIONAL" with last-checked timestamps.++---++## Dispatch fix agent++When user selects to fix an issue, use `AskUserQuestion` to confirm the scope before dispatching:++```+Dispatch fix agent for: [issue title]+ Severity: [CRITICAL/HIGH/MEDIUM]+ Repo: [repo]+ Error: [brief description]++ The agent will:+ - Investigate root cause in [repo]+ - Create feature branch with fix+ - Open PR for review++ [Dispatch agent] [Show me the logs first] [Skip — I'll fix manually]+```++On confirmation, spawn an Agent with:++- The error details and logs+- Access to the relevant repo+- Instruction to create a feature branch, fix, and open a PR+- Report back when done or blocked++Use the `agents/infra-monitor.md` agent definition for infra issues.++If `$ARGUMENTS` contains a project alias, filter to that project's services only.++---++## Native tool usage++### Monitor — live service health++Use `Monitor` to stream ECS task logs or GitHub Actions runs when investigating fires:+```+Monitor(command: "aws logs tail /ecs/<service> --follow --since 5m")+```++### Tasks — incident tracking++Use `TaskCreate` for each active fire. Update with `TaskUpdate` as fires are investigated/fixed/escalated.++### WebFetch — status pages++When diagnosing fires, use `WebFetch` to check AWS status page (`https://health.aws.amazon.com/health/status`), Vercel status, or third-party API status pages.++### WebSearch — known outage patterns++Use `WebSearch` to find if the error pattern matches a known AWS/infrastructure issue (e.g., "ECS task stopped CannotPullContainerError" → known ECR throttling).diff --git a/claude-ops/skills/ops-go/SKILL.md b/claude-ops/skills/ops-go/SKILL.mdnew file mode 100644index 00000000..5ceb33ae--- /dev/null+++ b/claude-ops/skills/ops-go/SKILL.md@@ -0,0 +1,177 @@+---+name: ops-go+description: Token-efficient morning briefing. Pre-gathers all data via shell scripts, then presents a unified business dashboard with prioritized actions.+argument-hint: "[project-alias]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TaskCreate+ - TaskUpdate+ - TaskList+ - CronCreate+ - CronList+ - WebFetch+effort: medium+maxTurns: 40+---++# OPS ► MORNING BRIEFING++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `owner` — use in the greeting header ("Good morning, [owner]")+ - `timezone` — display all timestamps in this timezone+ - `default_channels` — which channels to include in unread summary++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - If `action_needed` is not null → surface it before the briefing+ - Check `wacli-sync` status before including WhatsApp unread counts+ - Also check `~/.wacli/.health` for live auth status++3. **WhatsApp pre-check**: Only include WhatsApp data if `~/.wacli/.health` shows `status=connected`.++## CLI/API Reference++### wacli (WhatsApp)++**Health file** — check `~/.wacli/.health` BEFORE any wacli command:+- `status=connected` → proceed+- `status=needs_auth` or `status=needs_reauth` → prompt user for QR scan++| Command | Usage | Output |+|---------|-------|--------|+| `wacli doctor --json` | Check auth/connected/lock/FTS | `{data: {authenticated, connected, lock_held, fts_enabled}}` |+| `wacli chats list --json` | All chats | `{data: [{JID, Name, Kind, LastMessageTS}]}` |++### gog CLI (Gmail/Calendar)++| Command | Usage | Output |+|---------|-------|--------|+| `gog calendar list --date "$(date +%Y-%m-%d)"` | Today's calendar events | Calendar events |+| `gog gmail search -j --results-only --no-input --max 30 "in:inbox"` | Search inbox | JSON array of threads |++---++## Pre-gathered data++All data below was collected by shell scripts in <10 seconds:++### Infrastructure++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || echo '{"clusters":[],"error":"infra check failed"}'+```++### Git Status (all projects)++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-git 2>/dev/null || echo '[]'+```++### Open PRs++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-prs 2>/dev/null || echo '[]'+```++### CI Failures (last 24h)++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-ci 2>/dev/null || echo '[]'+```++### Unread Messages++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-unread 2>/dev/null || echo '{}'+```++### GSD State (active roadmaps)++```!+for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ if [ -f "$expanded/.planning/STATE.md" ]; then+ alias=$(basename "$expanded")+ phase=$(grep -m1 'current_phase' "$expanded/.planning/STATE.md" 2>/dev/null | head -1 || echo "unknown")+ progress=$(grep -m1 'progress' "$expanded/.planning/STATE.md" 2>/dev/null | head -1 || echo "unknown")+ echo "$alias: $phase | $progress"+ fi+done+```++### Calendar (today)++```!+gog calendar list --date "$(date +%Y-%m-%d)" 2>/dev/null | head -20 || echo "calendar unavailable"+```++## Your task++Analyze ALL the pre-gathered data above and present it as a morning briefing. Follow the ops-briefing output style.++**Format:**++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► MORNING BRIEFING — [DATE]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++FIRES (fix now)+[table of production issues, CI failures, broken deploys]++PRs NEEDING ACTION+[table: repo, PR#, title, status, action needed]++PORTFOLIO DASHBOARD+[table: project, phase, branch, uncommitted, CI, next action]++UNREAD+[WhatsApp: N, Email: N, Slack: check MCP, Calendar: N events today]++TODAY'S PRIORITIES (ranked by revenue impact + urgency)+1. [action] — [project] — [why]+2. ...+3. ...++──────────────────────────────────────────────────────+```++**Priority ranking**: fires > degraded infra > CI failures > unread comms > ready-to-merge PRs > revenue-generating GSD work > stale projects.++If `$ARGUMENTS` contains a project alias, focus the briefing on that project only.++After the briefing, use **batched AskUserQuestion calls** (max 4 options each) for the "What's next?" prompt. Show the top 3 priority actions + `[More...]` in the first call, then remaining actions + `[/ops-yolo — let me run your business today]` in the second call. Route to the appropriate ops skill or project.++For Slack unread counts: if the pre-gathered data shows `"count": -1`, use `mcp__claude_ai_Slack__slack_search_public_and_private` with query `is:unread` to get actual counts. Do this as a parallel tool call while analyzing other data.++---++## Native tool usage++### Tasks — briefing action tracking++After presenting the briefing, create a `TaskCreate` for each recommended priority action. As the user works through them (or delegates via skill routing), update with `TaskUpdate`. This gives continuity across the session.++### Cron — scheduled briefings++After the first briefing, offer to schedule recurring briefings via `AskUserQuestion`:+```+ [Schedule daily at 9am] [Schedule weekday mornings] [No schedule]+```+Use `CronCreate` to set up the schedule. Show existing schedules with `CronList`.++### WebFetch — calendar enrichment++When `gog cal` fails, use `WebFetch` with the Google Calendar API as fallback:+```+WebFetch(url: "https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=<today>T00:00:00Z&timeMax=<today>T23:59:59Z")+```diff --git a/claude-ops/skills/ops-inbox/CHANNELS.md b/claude-ops/skills/ops-inbox/CHANNELS.mdnew file mode 100644index 00000000..ae5f0b4a--- /dev/null+++ b/claude-ops/skills/ops-inbox/CHANNELS.md@@ -0,0 +1,185 @@+# Channel Configuration Guide++This document explains how to configure each communication channel for the `/ops:ops-inbox` skill. All credentials come from environment variables or CLI auth — **no secrets are committed to this repo**.++## WhatsApp (wacli)++**Status:** CLI-based (wacli), no MCP needed.++**Setup:**++```bash+# Install latest version from source (brew version may be outdated)+git clone https://github.com/steipete/wacli.git /tmp/wacli-src+cd /tmp/wacli-src+go build -o wacli ./cmd/wacli/+cp wacli /usr/local/bin/++# Authenticate (scans QR code with phone)+wacli auth++# Verify+wacli doctor+# Expected: AUTHENTICATED true, CONNECTED false (until sync runs)++# Initial sync (takes a minute for 142+ conversations)+wacli sync+```++**Troubleshooting:**++- `Client outdated (405)`: Rebuild from source above+- `store is locked`: Kill stale process: `kill $(pgrep wacli)`+- After version upgrade: `wacli auth logout && wacli auth`++**History limitations:**+wacli only captures messages **received while connected**. It cannot reliably backfill historical messages after the fact:++- `wacli history backfill --chat <jid>` requires ≥1 existing local message per chat and often times out on the WhatsApp on-demand sync response.+- Chats in the new `@lid` (Linked Device) format frequently return empty message queries because their history was never captured during an active sync session.+- For ongoing inbox management, run `wacli sync --follow` in a persistent terminal (outside Claude Code) so new messages land in the local DB in real-time.++**Env vars (optional):**++- `WACLI_STORE` — default `~/.wacli`++**Run sync persistently (recommended):**++```bash+# In a dedicated terminal tab — keeps wacli connected so new messages are captured+wacli sync --follow+```++---++## Email (gog)++**Status:** CLI-based (gog), optional MCP fallback.++**Setup:**++```bash+# Install gog+brew install Lifecycle-Innovations-Limited/tap/gog++# Authenticate+gog gmail auth+```++**Env vars (optional):**++- `GMAIL_ACCOUNT` — Gmail account (auto-detected if unset)++---++## Slack++**Status:** ⚠️ Not configured. Requires Slack MCP server.++**Requirements:**++- Slack MCP server installed and configured in `~/.claude/settings.json` under `mcpServers`+- Bot token with `channels:history`, `im:history`, `chat:write`, `search:read` scopes++**Setup:**++1. Install a Slack MCP server:+ ```bash+ # Option A: Official reference+ npm install -g @modelcontextprotocol/server-slack+ ```+2. Add to `~/.claude/settings.json`:+ ```json+ {+ "mcpServers": {+ "slack": {+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-slack"],+ "env": {+ "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",+ "SLACK_TEAM_ID": "${SLACK_TEAM_ID}"+ }+ }+ }+ }+ ```+3. Export env vars (from Doppler, 1Password, or direnv — never commit):+ ```bash+ export SLACK_BOT_TOKEN="xoxb-..."+ export SLACK_TEAM_ID="T..."+ export SLACK_MCP_ENABLED=true+ ```+4. Restart Claude Code to load the MCP server++**Env vars:**++- `SLACK_BOT_TOKEN` — Bot token (starts with `xoxb-`)+- `SLACK_TEAM_ID` — Workspace ID+- `SLACK_MCP_ENABLED` — Set `true` to enable in ops-unread++---++## Telegram++**Status:** ⚠️ Not configured. Requires USER-AUTH MCP server (NOT a bot).++**CRITICAL:** Do NOT use BotFather bots. The inbox skill must read the owner's **personal** conversations, which bots cannot access. Required: tdlib or MTProto user-auth integration.++**Requirements:**++- Telegram API ID and hash from https://my.telegram.org/apps+- User-auth MCP server (e.g., `mcp-telegram-user` or custom tdlib wrapper)++**Setup:**++1. Get API credentials from https://my.telegram.org/apps (for personal app, not bot)+2. Install a user-auth Telegram MCP server (tdlib-based):+ ```bash+ # Example: custom tdlib MCP wrapper+ npm install -g mcp-telegram-user+ ```+3. Add to `~/.claude/settings.json`:+ ```json+ {+ "mcpServers": {+ "telegram": {+ "command": "mcp-telegram-user",+ "env": {+ "TELEGRAM_API_ID": "${TELEGRAM_API_ID}",+ "TELEGRAM_API_HASH": "${TELEGRAM_API_HASH}",+ "TELEGRAM_PHONE": "${TELEGRAM_PHONE}",+ "TELEGRAM_SESSION_PATH": "${HOME}/.telegram-mcp-session"+ }+ }+ }+ }+ ```+4. Authenticate on first run (prompts for SMS code)+5. Export env vars and enable:+ ```bash+ export TELEGRAM_API_ID="..."+ export TELEGRAM_API_HASH="..."+ export TELEGRAM_PHONE="+1..."+ export TELEGRAM_ENABLED=true+ ```++**Env vars:**++- `TELEGRAM_API_ID` — from my.telegram.org/apps+- `TELEGRAM_API_HASH` — from my.telegram.org/apps+- `TELEGRAM_PHONE` — phone number for auth+- `TELEGRAM_ENABLED` — Set `true` to enable in ops-unread++**⚠️ The existing `telegram-server/index.js` in this repo uses a bot token and is NOT suitable for personal inbox management. It needs replacement with a tdlib-based user-auth implementation.**++---++## Verification++After configuring any channel, verify with:++```bash+${CLAUDE_PLUGIN_ROOT}/bin/ops-unread+```++Expected output shows each channel's `available: true/false` status.diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.mdnew file mode 100644index 00000000..1064c0bd--- /dev/null+++ b/claude-ops/skills/ops-inbox/SKILL.md@@ -0,0 +1,479 @@+---+name: ops-inbox+description: Full inbox management across all channels — WhatsApp (wacli), Email (Gmail MCP), Slack (MCP), Telegram (user-auth MCP). Scans FULL inbox (not just unread), identifies messages needing replies, archives handled conversations.+argument-hint: "[channel: whatsapp|email|slack|telegram|all]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - TaskCreate+ - TaskUpdate+ - TaskList+ - CronCreate+ - CronList+ - mcp__gog__gmail_search+ - mcp__gog__gmail_read_thread+ - mcp__gog__gmail_send+ - mcp__gog__gmail_labels+ # Slack: MCP tools added when configured+ # Telegram: user-auth MCP tools added when configured+effort: high+maxTurns: 60+---++# OPS ► INBOX ZERO++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `default_channels` — which channels to scan by default+ - `secrets_manager` / `doppler` — how to resolve channel credentials if not in env++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - Check `wacli-sync` status — if not running or auth needed, skip WhatsApp and surface the issue+ - Also check `~/.wacli/.health` for live auth status before any wacli command++3. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/` before drafting any reply:+ - `contact_*.md` — load profile for the contact you're about to reply to+ - `preferences.md` — apply user's communication style and language preferences+ - `topics_active.md` — check for active threads or deadlines related to this contact+ - `donts.md` — never violate these restrictions in drafts++## CLI/API Reference++### wacli (WhatsApp)++**Health file** — check `~/.wacli/.health` BEFORE any wacli command:+- `status=connected` → proceed normally+- `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR"+- `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair"+- File missing → fall back to `wacli doctor --json`++| Command | Usage | Output |+|---------|-------|--------|+| `wacli doctor --json` | Check auth/connected/lock/FTS | `{data: {authenticated, connected, lock_held, fts_enabled}}` |+| `wacli chats list --json` | All chats | `{data: [{JID, Name, Kind, LastMessageTS}]}` |+| `wacli messages list --chat "<JID>" --limit N --json` | Messages for chat | `{data: {messages: [{FromMe, Text, Timestamp, SenderName, ChatName}]}}` |+| `wacli messages search --query "<text>" --json` | FTS search | Same as above |+| `wacli contacts --search "<name>" --json` | Contact lookup | Contact objects |+| `wacli send --to "<JID>" --message "<msg>"` | Send text | Success/error |+| `wacli history backfill --chat="<JID>" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages | Backfill result |++### gog CLI (Gmail/Calendar)++| Command | Usage | Output |+|---------|-------|--------|+| `gog gmail search -j --results-only --no-input --max 30 "in:inbox"` | Full inbox scan | JSON array of threads |+| `gog gmail read -j --no-input "<thread_id>"` | Read thread | Full message JSON |+| `gog gmail send -j --to "<email>" --subject "<subj>" --body "<body>"` | Send email | Send result |+| `gog gmail labels modify --remove INBOX <thread_ids>` | Archive threads | Label change |++---+++## Agent Teams support++If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** when processing "all channels" mode. This enables:+- Channel agents run in parallel but can share context (e.g., WhatsApp agent finds a message referencing an email thread → email agent can prioritize it)+- You can steer agents: "skip WhatsApp for now, focus on email first"+- Agents report completion per-channel so you can process replies as they come in++**Team setup** (only when flag is enabled, "all channels" mode):+```+TeamCreate("inbox-channels")+Agent(team_name="inbox-channels", name="whatsapp-scanner", ...)+Agent(team_name="inbox-channels", name="email-scanner", ...)+Agent(team_name="inbox-channels", name="slack-scanner", ...)+Agent(team_name="inbox-channels", name="telegram-scanner", ...)+```++Each agent scans its channel and reports back classified results. You then process NEEDS_REPLY items across all channels in priority order.++If the flag is NOT set, process channels sequentially or use fire-and-forget subagents.++## Pre-gathered data++```!+${CLAUDE_PLUGIN_ROOT}/../../bin/ops-unread 2>/dev/null || echo '{}'+```++## Environment variables++All channel credentials come from env vars or CLI auth — no hardcoded secrets.++| Variable | Default | Purpose |+| ------------------- | ----------- | ---------------------------------------------------- |+| `GMAIL_ACCOUNT` | auto-detect | Gmail account for `gog` CLI |+| `SLACK_MCP_ENABLED` | `false` | Set `true` when Slack MCP server is configured |+| `TELEGRAM_ENABLED` | `false` | Set `true` when Telegram user-auth MCP is configured |+| `WACLI_STORE` | `~/.wacli` | wacli store directory |++## Core principle: FULL INBOX SCAN++Do NOT just check unread. Scan the FULL recent inbox for each channel and classify every conversation:++## Core principle: FULL CONTEXT — NEVER ASSUME++**CRITICAL SAFETY RULE — NEVER SEND WITHOUT UNDERSTANDING:**+Before drafting or sending ANY reply on ANY channel, you MUST have read the FULL conversation history (20+ messages) and PROVEN you understand it by summarizing:+1. What the conversation is about+2. What each party said (distinguish user messages from contact messages)+3. What the contact is actually asking/saying in their last message+4. What a sensible reply would address++**Failure mode this prevents:** An agent reads only the last message "je kan het toch uit Klaviyo halen?" and replies "Welke data heb je nodig?" — completely wrong because the contact was telling the user to pull data themselves (they have 2FA), not asking for data. Without the full thread, the reply was nonsensical and confused the contact.++**Hard rule: if you cannot summarize the conversation arc in 2 sentences, you have not read enough messages. Go back and read more.**++The user does NOT remember every thread. For EVERY message you present, you MUST build full context BEFORE showing it. Never show just a subject line and ask "what do you want to do?" — the user needs to understand what it's about first.++**For every NEEDS REPLY item, gather this context automatically:**++1. **Full thread body** — read the ENTIRE thread (`gog gmail read` / `wacli messages list --limit 20`), not just the last message. Summarize the full conversation arc.+2. **Contact profile** — search across channels to build a card:+ - `gog gmail search "from:<contact_email>" --max 10` — recent email history+ - `wacli contacts --search "<name>" --json` — WhatsApp presence+ - `wacli messages search --query "<name>" --json --limit 5` — recent WhatsApp mentions+ - If Linear configured: search for issues assigned to or mentioning this contact+ - Present: who they are, role/company, last N interactions, relationship context+3. **Topic context** — identify the subject matter and search for related threads:+ - `gog gmail search "subject:<keywords>" --max 5` — related email threads+ - `wacli messages search --query "<topic keywords>" --json --limit 5` — related WA messages+ - Summarize: what this topic is about, any deadlines, any pending decisions+4. **ops-memories** (if available) — check `~/.claude/plugins/data/ops-ops-marketplace/memories/` for any stored context about this contact or topic++**When presenting a NEEDS REPLY item:**+```+━━━ [Contact Name] — [Subject] ━━━+ Who: [role, company, relationship — from contact search]+ History: [last 3 interactions across channels]+ Thread: [2-3 sentence summary of full conversation arc]+ Last msg: [full body of their last message]+ Context: [related threads/decisions/deadlines found]++ Draft reply: "[contextually aware draft based on all above]"++ [Send] [Edit] [Read full thread] [Skip]+```++**When drafting replies:**+- Use the full thread history to maintain conversation continuity+- Reference specific points from their message+- Match the contact's communication style (formal/casual, language)+- If ops-memories has preferences for this contact, apply them+- Never generate a generic reply — every draft must show you read the full thread++- **NEEDS REPLY** — other party sent last message, awaiting your response+- **WAITING** — you sent last message, waiting for them (no action needed)+- **HANDLED** — conversation concluded, can be archived+- **FYI** — newsletters, notifications, automated messages (bulk archive)++## Channel availability + fallback++For each channel, detect availability at runtime:++1. **Email**: Try `gog` CLI first. If `gog` unavailable, try `mcp__gog__gmail_*` MCP tools. If neither, report unavailable.+2. **WhatsApp**: First check `~/.wacli/.health` for keepalive daemon status. If `status=needs_auth` or `status=needs_reauth`, do NOT attempt wacli commands — instead prompt the user: "WhatsApp needs re-authentication. Run `wacli auth` in a separate terminal and scan the QR code, then type 'done'." Use `AskUserQuestion`: `[Done — re-paired]`, `[Skip WhatsApp]`. On Done, restart the daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive`, wait 5s, re-check health. If no health file exists, fall back to `wacli doctor` for auth/connection status. If outdated (405 error), advise rebuilding from source.+3. **Slack**: Only via MCP tools (`mcp__claude_ai_Slack__*`). Check `SLACK_MCP_ENABLED` env var.+4. **Telegram**: Only via user-auth MCP (tdlib/MTProto). Check `TELEGRAM_ENABLED` env var. Never use BotFather bots.++## Your task++1. **Parse pre-gathered data** for initial counts (unread is just a starting signal).++2. **For each channel, run a FULL scan** (not just unread):+ - **Email**: Search `in:inbox` (not `is:unread`) via `gog gmail search -a $GMAIL_ACCOUNT -j --results-only --no-input --max 30 "in:inbox"`. For each thread, read the last message to determine who sent it last. Check for DRAFT or SENT labels. **Before suggesting to send a draft, verify no reply was already sent in the thread.**+ - **WhatsApp**: Run `wacli chats list --json` to get all chats. Filter to non-archived chats with `LastMessageTS` in the last 7 days. For each, fetch the FULL conversation via `wacli messages list --chat <JID> --limit 20 --json` (20 messages, not 5 — you need the full thread). Parse `data.messages[]` with fields `FromMe`, `Text`, `Timestamp`, `ChatName`. Understand which messages are from the user (`FromMe: true`) vs the contact (`FromMe: false`). Classify by last message `FromMe` field.+ - **Slack**: Search via Slack MCP tools. Check who sent last message in each thread.+ - **Telegram**: Use user-auth MCP (NOT bot API) to read recent conversations.++3. **Display the full inbox:**++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► INBOX MANAGER+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ 📱 WhatsApp [N need reply] | [N waiting] | [N archive]+ 📧 Email [N need reply] | [N waiting] | [N FYI]+ 💬 Slack [N need reply] | [N waiting]+ ✈️ Telegram [N need reply] | [N waiting]++──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each). Only show channels that are configured and have messages. If <=4 total options, use a single call.++AskUserQuestion call 1:+```+ [All channels (fastest — one pass)]+ [WhatsApp only]+ [Email only]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Slack only]+ [Telegram only]+ [Skip — already done]+```++If only 3 channels are configured, "All channels" + 3 channel options = 4, fits in one call. Then process the selected channel(s).++---++## Processing each channel++### WhatsApp (FULL SCAN + DEEP CONTEXT)++**Phase 1 — Classify:**+1. Get all chats: `wacli chats list --json`+2. Filter to chats with `LastMessageTS` in the last 7 days+3. For each, fetch the FULL recent conversation: `wacli messages list --chat "<JID>" --limit 20 --json` — get 20 messages, NOT 5. You need the full conversation thread to understand context.+4. Parse `data.messages[]` — fields: `FromMe`, `Text`, `Timestamp`, `ChatName`, `SenderName`+5. For EVERY chat, understand the conversation:+ - Read ALL messages in order. Know which are `FromMe: true` (user sent) vs `FromMe: false` (contact sent)+ - Understand what the conversation is about, what was discussed, what's pending+ - Identify the user's tone and style in their sent messages+6. Classify each chat:+ - **NEEDS REPLY**: Last message has `FromMe: false` (they sent last)+ - **WAITING**: Last message has `FromMe: true` (you sent last)+ - **ARCHIVE**: Old conversation, no recent activity, or concluded++**Phase 2 — Build context for NEEDS REPLY chats (run in parallel):**+For each NEEDS REPLY chat:+1. **Full conversation summary** — read all 20 messages, summarize the arc: what was discussed, key decisions, open questions+2. **Contact profile** — search for this person:+ - `wacli messages search --query "<contact_name>" --json --limit 10` — mentions in other chats+ - `gog gmail search -j --results-only --no-input --max 5 "from:<name> OR to:<name>"` — email history+ - Check `~/.claude/plugins/data/ops-ops-marketplace/memories/contact_*.md` for stored profile+ - Build: who they are, relationship, communication history across channels+3. **Topic context** — extract keywords from the conversation and search:+ - `wacli messages search --query "<topic keywords>" --json --limit 5` — related WA messages+ - `gog gmail search -j --results-only --no-input --max 3 "<topic keywords>"` — related emails+4. **User's messaging style** — from the `FromMe: true` messages in this chat, note: language (NL/EN), formality, emoji usage, typical response length++**Phase 3 — Present with full context:**++```+📱 WHATSAPP — NEEDS REPLY (with context)++━━━ 1. [Contact Name] ━━━+ Who: [role, company, relationship — from contact search]+ History: [last 3 interactions across channels]+ Conversation: [2-3 sentence summary of the full chat thread]+ Their message: [full text of their last message(s)]+ Your last msg: [what you said before they replied]+ Context: [related threads/topics found]+ Language: [NL/EN — match the user's previous messages in this chat]++ Draft reply: "[context-aware draft matching user's style + language]"++ [Send] [Edit] [Read full thread] [More...]++If "More...":+ [Archive] [Skip]++📱 WHATSAPP — WAITING (no action needed)+ N. [Contact] — you said: "[your last message]" — [time ago]+ Thread: [1-line summary of what you're waiting for]+```++Use `AskUserQuestion` for each NEEDS REPLY chat.++**When drafting WhatsApp replies:**+- Match the user's language (if they wrote Dutch to this contact, draft in Dutch)+- Match the user's style (casual/formal, emoji usage, message length)+- Reference specific points from the contact's message+- If ops-memories has preferences for this contact, apply them+- Never generate a generic reply — every draft must show you understood the full conversation++Reply via: `wacli send --to "<JID>" --message "<msg>"`++**wacli CLI reference (v0.5.0):**++| Command | Usage | Notes |+|---------|-------|-------|+| `wacli doctor` | `wacli doctor --json` | Check auth/connected/lock/FTS status |+| `wacli auth` | `wacli auth` | QR pairing (interactive — shows QR in terminal) |+| `wacli sync` | `wacli sync --follow --refresh-contacts --refresh-groups` | Persistent sync (managed by launchd keepalive) |+| `wacli sync --once` | `wacli sync --once --idle-exit=10s` | One-shot sync, exits when idle |+| `wacli chats list` | `wacli chats list --json` | All chats with JID, Name, Kind, LastMessageTS |+| `wacli messages list` | `wacli messages list --chat "<JID>" --limit 5 --json` | Messages: ChatJID, FromMe, Text, Timestamp, SenderName |+| `wacli messages search` | `wacli messages search --query "<text>" --json` | FTS5 search across all messages |+| `wacli contacts` | `wacli contacts --search "<name>" --json` | Contact lookup by name |+| `wacli send` | `wacli send --to "<JID>" --message "<msg>"` | Send text message |+| `wacli history backfill` | `wacli history backfill --chat="<JID>" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages from phone (needs store lock) |++**Health file contract (`~/.wacli/.health`):**++Before ANY wacli command, read `~/.wacli/.health`:+- `status=connected` → proceed normally+- `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR"+- `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair"+- File missing → fall back to `wacli doctor --json`++**Requesting backfill for @lid chats with empty messages:**++The keepalive daemon holds the store lock, so you can't run backfill directly. Instead:+1. Write JIDs to `~/.wacli/.backfill_jids` (one per line)+2. Restart the daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive`+3. The daemon runs backfill before starting persistent sync++**wacli troubleshooting:**++- `@lid` JIDs (linked device format) may return empty messages → request backfill via the daemon (see above)+- "Client outdated (405)" → rebuild from source: `cd /tmp && git clone https://github.com/Lifecycle-Innovations-Limited/wacli.git && cd wacli && go build -o /usr/local/bin/wacli ./cmd/wacli/`+- "store is locked" → the keepalive daemon holds the lock; to release: `launchctl bootout gui/$(id -u)/com.claude-ops.wacli-keepalive`+- Auth expired → daemon writes `needs_auth` to health file; prompt user for QR scan+- Key desync (0 messages synced) → daemon writes `needs_reauth`; user needs `wacli auth` re-pair++### Email (FULL SCAN + DEEP CONTEXT)++**Phase 1 — Classify:**+1. Search `in:inbox` (NOT `is:unread`) via `gog gmail search -a $GMAIL_ACCOUNT -j --results-only --no-input --max 30 "in:inbox"`+2. For each thread, read the FULL thread via `gog gmail read -a $GMAIL_ACCOUNT -j --no-input "<thread_id>"` — read ALL messages, not just the last one+3. Check the last message's `From` header and `labelIds` (SENT, DRAFT)+4. Classify:+ - **NEEDS REPLY**: Last sender is NOT you AND no unsent draft exists → action needed+ - **WAITING**: Last sender IS you (SENT label) → waiting for response+ - **DRAFT**: Unsent draft exists → verify no reply already sent, then offer to send+ - **FYI**: Newsletters, automated notifications, receipts → bulk archive++**Phase 2 — Build context for NEEDS REPLY items (run in parallel):**+For each NEEDS REPLY thread, gather:+1. **Full thread summary** — read every message in the thread, summarize the conversation arc (who said what, key decisions, open questions)+2. **Contact profile** — for the sender:+ - `gog gmail search -j --results-only --no-input --max 10 "from:<sender_email>"` — their recent emails to you+ - `wacli contacts --search "<sender_name>" --json` — WhatsApp contact+ - `wacli messages search --query "<sender_name>" --json --limit 5` — recent WhatsApp mentions+ - Build: name, role/company, relationship history, last N interactions+3. **Topic search** — extract key terms from subject + body, then:+ - `gog gmail search -j --results-only --no-input --max 5 "subject:<keywords>"` — related threads+ - Identify: pending decisions, deadlines, action items from related threads++**Phase 3 — Present with full context:**++```+📧 EMAIL — NEEDS REPLY (with context)++━━━ 1. [Sender] — [Subject] ━━━+ Who: [sender's role, company — from contact search]+ History: [last 3 email exchanges with this person]+ Thread summary: [2-3 sentences covering the full conversation arc]+ Their message: [full body of their last message — NOT truncated]+ Related: [any related threads or pending decisions found]++ Draft reply: "[context-aware draft using full thread + contact history]"++ [Send draft] [Edit draft] [Read full thread] [More...]++If "More...":+ [Archive] [Skip]++📧 EMAIL — DRAFTS (unsent)+ N. [Recipient] — [Subject] (draft ready to send)++📧 EMAIL — FYI / ARCHIVE+ N. [Sender] — [Subject] (newsletter/notification)++ For each NEEDS REPLY:+ a) Read full thread + draft reply+ b) Archive (no reply needed)+ c) Skip++ For FYI section:+ x) Archive all FYI at once+```++Use `AskUserQuestion` for each NEEDS REPLY email with options `[Read + Reply]` / `[Archive]` / `[Skip]`.++When replying, draft the reply and use `AskUserQuestion` to confirm:+```+Reply to [Sender] — [Subject]:+ "[drafted reply]"++ [Send] [Edit] [Skip]+```++For FYI bulk archive, use `AskUserQuestion`:+```+Archive N FYI/newsletter emails?+ [list of subjects]++ [Archive all N] [Review each] [Skip]+```++Draft replies via `gog gmail send`. Archive via `gog gmail labels modify --remove INBOX <thread_ids>`.++### Slack++Use Slack MCP tools with `query: "is:unread"` for mentions.+For each result, show channel, sender, preview. Read thread for context.++```+ a) Read thread+ b) Reply+ c) Mark read / skip+```++### Telegram (FULL SCAN — User Account, NOT Bot)++Telegram integration must authenticate as the user's personal account (user-auth via tdlib/MTProto), NOT a BotFather bot. The goal is to manage real conversations just like WhatsApp via wacli.++Use the Telegram user-auth MCP server if available.++1. List recent dialogs/conversations (last 7 days)+2. For each, check who sent the last message+3. Classify: NEEDS REPLY / WAITING / HANDLED++```+✈️ TELEGRAM — NEEDS REPLY+ 1. [Contact] — [preview] — [time ago]++ a) Read thread + reply+ b) Archive+ c) Skip+```++If no Telegram user-auth tool is available, report: "Telegram not configured — needs user-auth MCP server (tdlib/MTProto)".++---++## Completion++After all selected channels are processed, print:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ INBOX ZERO ✓ — [timestamp]+ Processed: [N] messages | Replied: [N] | Archived: [N]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++If `$ARGUMENTS` specifies a channel (e.g. `whatsapp`), skip the menu and go directly to that channel.++---++## Native tool usage++### Tasks — inbox progress++Use `TaskCreate` for each channel being processed. Update with `TaskUpdate` as messages are replied/archived/skipped. Gives the user a live inbox-zero progress bar.++### Cron — scheduled inbox checks++After processing, offer to schedule recurring inbox checks via `AskUserQuestion`:+```+ [Schedule inbox check every 2 hours] [Schedule morning + evening] [No schedule]+```+Use `CronCreate` if selected. Show existing schedules with `CronList`.diff --git a/claude-ops/skills/ops-linear/SKILL.md b/claude-ops/skills/ops-linear/SKILL.mdnew file mode 100644index 00000000..22dd4820--- /dev/null+++ b/claude-ops/skills/ops-linear/SKILL.md@@ -0,0 +1,159 @@+---+name: ops-linear+description: Linear command center. Shows current sprint, creates/updates issues, manages priorities, syncs with GSD phases.+argument-hint: "[sprint|create|update|sync|backlog|issue-id]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - AskUserQuestion+ - TaskCreate+ - TaskUpdate+ - WebFetch+ - mcp__linear__list_issues+ - mcp__linear__list_teams+ - mcp__linear__list_projects+ - mcp__linear__get_issue+ - mcp__linear__update_issue+ - mcp__linear__create_issue+ - mcp__linear__create_comment+ - mcp__linear__search_issues+effort: medium+maxTurns: 30+---++# OPS ► LINEAR COMMAND CENTER++## Runtime Context++Before executing, load available context:++1. **Secrets**: Linear API key required for MCP fallback queries.+ ### Secret Resolution+ - Check `$LINEAR_API_KEY` env var+ - Then: `doppler secrets get LINEAR_API_KEY --plain` (if doppler configured in prefs)+ - Then: use `password_manager_config.query_cmd` from `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - If unavailable, use Linear MCP tools exclusively (no curl fallback possible)++2. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` for `secrets_manager` / `doppler` config.++## CLI/API Reference++### Linear GraphQL (fallback when MCP unavailable)++| Command | Usage | Output |+|---------|-------|--------|+| `curl -X POST https://api.linear.app/graphql -H "Authorization: $LINEAR_API_KEY" -H "Content-Type: application/json" -d '{"query":"{ issues(filter: {state: {type: {in: [\"started\",\"unstarted\"]}}}) { nodes { id title state { name } priority assignee { name } } } }"}'` | Active issues | JSON |+| `curl -X POST https://api.linear.app/graphql -H "Authorization: $LINEAR_API_KEY" -H "Content-Type: application/json" -d '{"query":"{ cycles(filter: {isActive: {eq: true}}) { nodes { id number startsAt endsAt } } }"}'` | Current cycles | JSON |++---++## Phase 1 — Load data++Run in parallel:++1. `mcp__linear__list_teams` — get all team IDs+2. `mcp__linear__list_issues` — get issues with cycle filter (use GraphQL fallback for cycle queries if needed)++Then fetch issues for the current cycle: `mcp__linear__list_issues` filtered to current cycle ID.++---++## Route by `$ARGUMENTS`++| Argument | Action |+| --------------- | --------------------------------------- |+| (empty), sprint | Show current sprint board |+| backlog | Show unassigned/unscheduled issues |+| create [title] | Create a new issue (prompt for details) |+| update [id] | Update issue by ID |+| sync | Sync GSD phases to Linear issues |+| [issue-id] | Show and edit that specific issue |++---++## Sprint board view++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ LINEAR ► SPRINT [N] — [start] → [end]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++IN PROGRESS+ [id] [priority] [title] [assignee] [estimate]++TODO+ [id] [priority] [title] [assignee] [estimate]++DONE THIS SPRINT+ [id] [title] [completed date]++BLOCKED / CANCELLED+ [id] [title] [reason]++──────────────────────────────────────────────────────+ Sprint velocity: [done points] / [total points] ([%])+──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each):++AskUserQuestion call 1:+```+ [Create new issue]+ [Update issue status]+ [Move issue to/from sprint]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [View backlog]+ [Sync with GSD phases]+```++---++## Create issue flow++Collect from user (or parse from `$ARGUMENTS`):++- Title+- Team (list choices if ambiguous)+- Priority (urgent/high/medium/low)+- Cycle (current sprint or backlog)+- Assignee (optional)+- Estimate (optional)++Use `mcp__linear__create_issue` to create. Confirm: `Created [id]: [title]`++---++## GSD sync flow++Read all active GSD STATE.md files across projects. For each active phase:++1. Check if a Linear issue exists with matching phase reference.+2. If not, offer to create one.+3. If status differs (GSD says done, Linear says in-progress), offer to sync.++Update Linear issues to match GSD phase completion status.++Use AskUserQuestion after displaying any view to get the next action.++---++## Native tool usage++### Tasks — sprint work tracking++When the user starts working on a Linear issue, use `TaskCreate` to track it locally. Update with `TaskUpdate` as the issue progresses. This bridges Linear state with local session state.++### WebFetch — Linear API fallback++When Linear MCP tools hit quota limits or fail, fall back to `WebFetch` with the Linear GraphQL API:+```+WebFetch(url: "https://api.linear.app/graphql", method: "POST", headers: {"Authorization": "$LINEAR_API_KEY"}, body: '{"query":"{ issues(filter: {cycle: {id: {eq: \"<id>\"}}}}) { nodes { id title state { name } } } }"}')+```diff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.mdnew file mode 100644index 00000000..ec7b7c6f--- /dev/null+++ b/claude-ops/skills/ops-marketing/SKILL.md@@ -0,0 +1,485 @@+---+name: ops-marketing+description: Marketing command center. Email campaigns (Klaviyo), paid ads (Meta/Google), analytics (GA4), SEO, and social media metrics. One dashboard for all marketing channels.+argument-hint: "[email|ads|analytics|seo|social|campaigns|setup]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Grep+ - Glob+ - Agent+ - AskUserQuestion+ - WebFetch+ - WebSearch+effort: medium+maxTurns: 40+---++# OPS ► MARKETING COMMAND CENTER++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `timezone` — display all timestamps correctly+ - `klaviyo_private_key`, `meta_ads_token`, `meta_ad_account_id`, `ga4_property_id`, `google_search_console_site` — check userConfig keys before env vars++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - If `action_needed` is not null → surface it before running any channel queries++3. **Secrets**: Resolve API keys via userConfig → env vars → Doppler (see Credential Resolution section below)++## CLI/API Reference++### Klaviyo REST API++| Endpoint | Method | Description |+|----------|--------|-------------|+| `https://a.klaviyo.com/api/lists/?fields[list]=name,id,profile_count` | GET | All lists + subscriber counts |+| `https://a.klaviyo.com/api/campaigns/?filter=equals(messages.channel,'email')&sort=-created_at` | GET | Recent campaigns |+| `https://a.klaviyo.com/api/flows/?filter=equals(status,'live')` | GET | Active flows |+| `https://a.klaviyo.com/api/metrics/` | GET | Available metrics |++**Auth header**: `Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}` | **Revision header**: `revision: 2024-10-15`++### Meta Graph API++| Endpoint | Method | Description |+|----------|--------|-------------|+| `https://graph.facebook.com/v18.0/${META_ACCOUNT}/insights?fields=spend,...&date_preset=last_7d` | GET | Account-level ad spend |+| `https://graph.facebook.com/v18.0/${META_ACCOUNT}/campaigns?fields=name,status,insights{...}` | GET | Campaign breakdown |+| `https://graph.facebook.com/v18.0/me/accounts?fields=instagram_business_account` | GET | Linked Instagram account |++**Auth header**: `Authorization: Bearer ${META_TOKEN}`++### Google Analytics 4 (Data API)++| Endpoint | Method | Description |+|----------|--------|-------------|+| `https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY}:runReport` | POST | Run custom report |++**Auth**: gcloud ADC — `GA4_TOKEN=$(gcloud auth application-default print-access-token)`++### Google Search Console++| Endpoint | Method | Description |+|----------|--------|-------------|+| `https://searchconsole.googleapis.com/webmasters/v3/sites/${GSC_SITE_ENCODED}/searchAnalytics/query` | POST | Search performance data |++**Auth**: Same gcloud ADC token as GA4++## Credential Resolution++Resolve credentials in this order for each service:++### Klaviyo+```bash+KLAVIYO_KEY="${KLAVIYO_PRIVATE_KEY:-$(claude plugin config get klaviyo_private_key 2>/dev/null)}"+if [ -z "$KLAVIYO_KEY" ]; then+ KLAVIYO_KEY="$(doppler secrets get KLAVIYO_PRIVATE_KEY --plain 2>/dev/null)"+fi+```++### Meta Ads+```bash+META_TOKEN="${META_ADS_TOKEN:-$(claude plugin config get meta_ads_token 2>/dev/null)}"+META_ACCOUNT="${META_AD_ACCOUNT_ID:-$(claude plugin config get meta_ad_account_id 2>/dev/null)}"+if [ -z "$META_TOKEN" ]; then+ META_TOKEN="$(doppler secrets get META_ADS_TOKEN --plain 2>/dev/null)"+fi+```++### GA4+```bash+GA4_PROPERTY="${GA4_PROPERTY_ID:-$(claude plugin config get ga4_property_id 2>/dev/null)}"+# GA4 uses gcloud application default credentials — check if configured:+gcloud auth application-default print-access-token 2>/dev/null+```++### Google Search Console+```bash+GSC_SITE="${GOOGLE_SEARCH_CONSOLE_SITE:-$(claude plugin config get google_search_console_site 2>/dev/null)}"+# Uses same gcloud ADC as GA4+```++---++## Sub-command Routing++Route `$ARGUMENTS` to the correct section below:++| Input | Action |+|---|---|+| (empty), dashboard | Run full marketing dashboard |+| email, klaviyo | Klaviyo email metrics |+| ads, meta | Meta Ads performance |+| google-ads | Google Ads (if configured) |+| analytics, ga4 | GA4 sessions + conversions |+| seo, gsc | Search Console metrics |+| social | Social media aggregator |+| campaigns | Cross-channel campaign overview |+| setup | Configure API keys |++---++## email / klaviyo++Pull Klaviyo metrics for last 30 days.++### Subscriber count+```bash+curl -s "https://a.klaviyo.com/api/lists/?fields[list]=name,id,profile_count" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" | jq '.data[] | {name: .attributes.name, id: .id, count: .attributes.profile_count}'+```++### Recent campaigns (last 10)+```bash+curl -s "https://a.klaviyo.com/api/campaigns/?filter=equals(messages.channel,'email')&sort=-created_at&page[size]=10&fields[campaign]=name,status,created_at,send_time" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" | jq '.data[] | {name: .attributes.name, status: .attributes.status, sent: .attributes.send_time}'+```++### Flow metrics (active flows)+```bash+curl -s "https://a.klaviyo.com/api/flows/?filter=equals(status,'live')&fields[flow]=name,status,created,trigger_type" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" | jq '.data[] | {name: .attributes.name, trigger: .attributes.trigger_type}'+```++### Key email metrics (opens, clicks, revenue via metric aggregates)+```bash+# Get metric IDs first+curl -s "https://a.klaviyo.com/api/metrics/" \+ -H "Authorization: Klaviyo-API-Key ${KLAVIYO_KEY}" \+ -H "revision: 2024-10-15" | jq '.data[] | select(.attributes.name | test("Opened Email|Clicked Email|Placed Order")) | {name: .attributes.name, id: .id}'+```++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ EMAIL (KLAVIYO) — last 30d+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Lists: [list_name] — [N] subscribers+ Campaigns: [N sent] | [N drafts]+ Active Flows: [N]++ RECENT CAMPAIGNS+ [name] [status] sent [date]+ ...+```++---++## ads / meta++Pull Meta Ads insights for the configured ad account.++### Account-level spend (last 7 days)+```bash+curl -s "https://graph.facebook.com/v18.0/${META_ACCOUNT}/insights?fields=spend,impressions,clicks,ctr,cpc,actions,action_values&date_preset=last_7d&level=account" \+ -H "Authorization: Bearer ${META_TOKEN}" | jq '{spend: .data[0].spend, impressions: .data[0].impressions, clicks: .data[0].clicks, ctr: .data[0].ctr, cpc: .data[0].cpc}'+```++### Campaign breakdown (last 7 days)+```bash+curl -s "https://graph.facebook.com/v18.0/${META_ACCOUNT}/campaigns?fields=name,status,daily_budget,lifetime_budget,insights{spend,impressions,clicks,actions,action_values}&date_preset=last_7d" \+ -H "Authorization: Bearer ${META_TOKEN}" | jq '.data[] | {name: .name, status: .status, spend: .insights.data[0].spend}'+```++### ROAS calculation+From `action_values` array: extract `action_type == "purchase"` value, divide by spend.++### Top performing ads (last 7d)+```bash+curl -s "https://graph.facebook.com/v18.0/${META_ACCOUNT}/ads?fields=name,adset_id,insights{spend,impressions,clicks,actions,action_values,ctr,cpc}&date_preset=last_7d&limit=10" \+ -H "Authorization: Bearer ${META_TOKEN}" | jq '.data | sort_by(.insights.data[0].spend | tonumber) | reverse | .[0:5] | .[] | {name: .name, spend: .insights.data[0].spend, ctr: .insights.data[0].ctr}'+```++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ META ADS — last 7d+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Spend: $[X]+ ROAS: [X]x+ Purchases: [N] ($[X] revenue)+ Impressions: [N] CTR: [X]%+ CPC: $[X]++ CAMPAIGNS+ [name] [status] $[spend] [roas]x ROAS+ ...++ TOP ADS (by spend)+ [name] $[spend] [ctr]% CTR+```++---++## analytics / ga4++Pull GA4 data via the Data API using gcloud ADC.++### Get access token+```bash+GA4_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null)+```++### Sessions + conversions (last 7d)+```bash+curl -s -X POST "https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY}:runReport" \+ -H "Authorization: Bearer ${GA4_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],+ "metrics": [+ {"name": "sessions"},+ {"name": "totalUsers"},+ {"name": "conversions"},+ {"name": "totalRevenue"},+ {"name": "bounceRate"},+ {"name": "averageSessionDuration"}+ ]+ }' | jq '.rows[0].metricValues | {sessions: .[0].value, users: .[1].value, conversions: .[2].value, revenue: .[3].value, bounce_rate: .[4].value}'+```++### Traffic sources (last 7d)+```bash+curl -s -X POST "https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY}:runReport" \+ -H "Authorization: Bearer ${GA4_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],+ "dimensions": [{"name": "sessionDefaultChannelGrouping"}],+ "metrics": [{"name": "sessions"}, {"name": "conversions"}],+ "orderBys": [{"metric": {"metricName": "sessions"}, "desc": true}],+ "limit": 8+ }' | jq '.rows[] | {channel: .dimensionValues[0].value, sessions: .metricValues[0].value, conversions: .metricValues[1].value}'+```++### Top pages (last 7d)+```bash+curl -s -X POST "https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY}:runReport" \+ -H "Authorization: Bearer ${GA4_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],+ "dimensions": [{"name": "pagePath"}],+ "metrics": [{"name": "screenPageViews"}, {"name": "averageSessionDuration"}],+ "orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}],+ "limit": 10+ }' | jq '.rows[] | {page: .dimensionValues[0].value, views: .metricValues[0].value}'+```++If `GA4_TOKEN` is empty or gcloud not available, output: `GA4 not configured — run /ops:marketing setup or configure gcloud ADC`.++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ ANALYTICS (GA4) — last 7d+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Sessions: [N] Users: [N]+ Conversions: [N] CVR: [X]%+ Revenue: $[X]+ Bounce Rate: [X]% Avg Session: [Xm Xs]++ TRAFFIC SOURCES+ [channel] [N sessions] [N conversions]+ ...++ TOP PAGES+ [path] [N views]+```++---++## seo / gsc++Pull Google Search Console data.++### Get access token (same gcloud ADC)+```bash+GSC_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null)+GSC_SITE_ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('${GSC_SITE}', safe=''))" 2>/dev/null || echo "${GSC_SITE}" | sed 's|:|%3A|g; s|/|%2F|g')+```++### Search performance (last 28 days)+```bash+curl -s -X POST "https://searchconsole.googleapis.com/webmasters/v3/sites/${GSC_SITE_ENCODED}/searchAnalytics/query" \+ -H "Authorization: Bearer ${GSC_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "startDate": "'$(date -v-28d +%Y-%m-%d 2>/dev/null || date -d '28 days ago' +%Y-%m-%d)'",+ "endDate": "'$(date +%Y-%m-%d)'",+ "dimensions": [],+ "rowLimit": 1+ }' | jq '{clicks: .rows[0].clicks, impressions: .rows[0].impressions, ctr: .rows[0].ctr, position: .rows[0].position}'+```++### Top queries (last 28 days)+```bash+curl -s -X POST "https://searchconsole.googleapis.com/webmasters/v3/sites/${GSC_SITE_ENCODED}/searchAnalytics/query" \+ -H "Authorization: Bearer ${GSC_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "startDate": "'$(date -v-28d +%Y-%m-%d 2>/dev/null || date -d '28 days ago' +%Y-%m-%d)'",+ "endDate": "'$(date +%Y-%m-%d)'",+ "dimensions": ["query"],+ "rowLimit": 20,+ "dimensionFilterGroups": []+ }' | jq '.rows[] | {query: .keys[0], clicks: .clicks, impressions: .impressions, position: (.position | floor)}'+```++### Top pages by clicks+```bash+curl -s -X POST "https://searchconsole.googleapis.com/webmasters/v3/sites/${GSC_SITE_ENCODED}/searchAnalytics/query" \+ -H "Authorization: Bearer ${GSC_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "startDate": "'$(date -v-28d +%Y-%m-%d 2>/dev/null || date -d '28 days ago' +%Y-%m-%d)'",+ "endDate": "'$(date +%Y-%m-%d)'",+ "dimensions": ["page"],+ "rowLimit": 10+ }' | jq '.rows[] | {page: .keys[0], clicks: .clicks, impressions: .impressions, position: (.position | floor)}'+```++If GSC not configured, output: `Search Console not configured — run /ops:marketing setup`.++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ SEO (SEARCH CONSOLE) — last 28d+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Clicks: [N]+ Impressions: [N]+ CTR: [X]%+ Avg Position: [X]++ TOP QUERIES+ [query] [clicks] clicks pos [N]+ ...++ TOP PAGES+ [url] [clicks] clicks [impressions] impr+```++---++## social++Aggregate available social media metrics. Check which are configured.++### Instagram (via Meta Graph API — same token as Meta Ads)+```bash+# Get Instagram Business Account ID linked to the ad account+curl -s "https://graph.facebook.com/v18.0/me/accounts?fields=instagram_business_account" \+ -H "Authorization: Bearer ${META_TOKEN}" | jq '.data[].instagram_business_account.id' 2>/dev/null++# Then pull media insights+curl -s "https://graph.facebook.com/v18.0/${IG_ACCOUNT_ID}?fields=followers_count,media_count,profile_views" \+ -H "Authorization: Bearer ${META_TOKEN}" | jq '{followers: .followers_count, posts: .media_count, profile_views: .profile_views}'+```++### YouTube (if configured via gcloud)+```bash+YT_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null)+curl -s "https://www.googleapis.com/youtube/v3/channels?part=statistics&mine=true" \+ -H "Authorization: Bearer ${YT_TOKEN}" | jq '.items[0].statistics | {subscribers: .subscriberCount, views: .viewCount, videos: .videoCount}'+```++Show `[not configured]` for any unconfigured channels rather than failing.++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ SOCIAL MEDIA+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Instagram: [N followers] [N posts] [N profile views]+ YouTube: [N subscribers] [N total views]+ TikTok: [not configured] — set TIKTOK_ACCESS_TOKEN+```++---++## campaigns++Cross-channel campaign overview — unified view of active campaigns across all configured channels.++Run in parallel:+1. Klaviyo active campaigns (status: draft + scheduled + sending)+2. Meta Ads active campaigns (status: ACTIVE)+3. Show GA4 conversion goals if available++### Output format+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ CROSS-CHANNEL CAMPAIGNS — active+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ EMAIL (Klaviyo)+ [campaign name] [status] [send date or "scheduled for X"]++ PAID (Meta Ads)+ [campaign name] [status] $[daily_budget]/day [objective]++ FLOWS (Always-on automation)+ [flow name] [trigger type] [status: live/draft]+```++---++## dashboard (default — no args)++Run ALL sections in parallel, then render unified dashboard.++```bash+# Run the pre-gathered data script+"${CLAUDE_PLUGIN_ROOT}/bin/ops-marketing-dash" 2>/dev/null+```++Parse the JSON output and display:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ MARKETING DASHBOARD — [date]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Email (Klaviyo) [N] subs | [X]% open rate | $[X] attributed+ Paid (Meta) $[X] spent | [X]x ROAS | [N] purchases+ Organic (GA4) [N] sessions | [X]% CVR | $[X] revenue+ SEO (GSC) [N] clicks | [N] impressions | [X] avg pos+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++For any channel with missing credentials, show `[not configured — /ops:marketing setup]`.++---++## setup++Guide user through configuring each marketing service:++```+MARKETING SETUP+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++Which service do you want to configure?+ 1. Klaviyo (email)+ 2. Meta Ads (paid social)+ 3. Google Analytics 4+ 4. Google Search Console+ 5. All of the above+```++For each selected service, prompt for required credentials and save via `claude plugin config set <key> <value>`.++**Klaviyo:** Ask for Private API Key (from Klaviyo → Settings → API Keys). Save as `klaviyo_private_key`.++**Meta Ads:** Ask for Access Token (from Meta Business → System Users → Generate Token with `ads_read` + `ads_management`). Ask for Ad Account ID (format: `act_XXXXXXXXX`). Save as `meta_ads_token` and `meta_ad_account_id`.++**GA4:** Prompt user to run `gcloud auth application-default login` and provide their GA4 Property ID (numeric, from Admin → Property Settings). Save as `ga4_property_id`.++**Search Console:** Prompt for site URL as registered (e.g. `https://example.com`). Save as `google_search_console_site`. Uses same gcloud ADC as GA4.++After saving, validate each credential with a test API call and report: `[service] ✓ connected` or `[service] ✗ invalid key`.diff --git a/claude-ops/skills/ops-merge/SKILL.md b/claude-ops/skills/ops-merge/SKILL.mdnew file mode 100644index 00000000..299d01fe--- /dev/null+++ b/claude-ops/skills/ops-merge/SKILL.md@@ -0,0 +1,266 @@+---+name: ops-merge+description: Autonomous PR merge pipeline. Scans all repos for open PRs, dispatches subagents to fix CI, resolve conflicts, address review comments, then merges. Use --main to also sync dev↔main branches.+argument-hint: "[--main] [--repo org/repo] [--dry-run]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Edit+ - Grep+ - Glob+ - Agent+ - TaskCreate+ - TaskUpdate+ - TaskList+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - Monitor+ - WebSearch+effort: medium+maxTurns: 50+---++## Runtime Context++Before executing, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `owner`, `timezone`, project registry+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — if `action_needed` set, surface to user+3. **Secrets**: GitHub token: env `$GITHUB_TOKEN` → `doppler secrets get GITHUB_TOKEN --plain` → password manager+++# OPS ► MERGE++## CLI/API Reference++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh pr list --repo <owner/repo> --json number,title,state,headRefName,statusCheckRollup,reviewDecision,mergeable,isDraft` | List PRs with status | JSON array |+| `gh pr view <n> --repo <repo> --json title,body,state,mergeable,reviews` | PR details | JSON |+| `gh pr checks <n> --repo <repo>` | CI check status | Check list |+| `gh pr merge <n> --repo <repo> --squash --admin` | Squash merge PR | Merge result |+| `gh pr create --repo <repo> --title "<t>" --body "<b>" --base dev` | Create PR | PR URL |+| `gh run list --repo <repo> --limit 5 --json conclusion,name,headBranch` | CI runs | JSON array |+| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |+| `gh run watch <run-id> --repo <repo>` | Stream CI run | Live output (use with Monitor) |+| `gh api repos/<repo>/pulls/<n>/comments --jq '.[].body'` | PR review comments | Comment text |++---++## Agent Teams support++If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** for fixer agents (Phase 3). This enables:+- Steering fixers mid-flight if priorities change (e.g., a critical PR should be merged first)+- Fixers can report blockers and you can redirect them without waiting for completion+- Shared context: if fixer-A discovers a breaking change that affects fixer-B's PR, you can notify B++**Team setup** (only when flag is enabled, Phase 3):+```+TeamCreate("merge-fixers")+Agent(team_name="merge-fixers", name="fixer-[repo]", ...)+```++Use `SendMessage(to="fixer-my-api", content="PR #2958 was just merged — rebase your branch")` to coordinate.++If the flag is NOT set, fall back to standard parallel subagents with `isolation: "worktree"`.++## Pre-gathered PR data++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-merge-scan 2>/dev/null || echo '{"prs":[],"error":"merge-scan failed"}'+```++## Your task++You are the **merge orchestrator**. Your job is to get every open PR across the owner's repos merged — fixing whatever blocks them first.++### Parse arguments++From `$ARGUMENTS`:++- `--main` → after all PRs merge to dev, also sync dev↔main for repos that have both branches+- `--repo <slug>` → scope to one repo only (e.g., `--repo your-org/my-api`)+- `--dry-run` → report what would happen, don't dispatch agents or merge anything+- `--force` → skip the confirmation prompt before merging+- (empty) → process all repos, merge to dev only++### Phase 1 — Classify the PR queue++Parse the pre-gathered JSON. For each PR, it's already classified as one of:++| Classification | Meaning | Action |+| ----------------------- | ----------------------------------------------------------------- | ------------------------------------------- |+| `ready` | CI green, approved, no conflicts | Merge immediately |+| `needs-rebase` | `mergeable: CONFLICTING` | Dispatch fixer: rebase on base branch |+| `needs-ci-fix` | CI failures in `statusCheckRollup` | Dispatch fixer: investigate logs, fix, push |+| `needs-review-response` | `reviewDecision: CHANGES_REQUESTED` | Dispatch fixer: resolve comments |+| `blocked` | `mergeStateStatus: BLOCKED` (branch protection, required reviews) | Note why, skip |+| `draft` | `isDraft: true` | Skip — not ready for merge |++Print the queue:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► MERGE — PR Queue+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++| Repo | PR | Title | Status | Action |+|------|----|-------|--------|--------|+| my-api | #2958 | fix(migration) | ready | merge |+| my-app | #4456 | feat(apple-04) | needs-ci-fix | dispatch fixer |+| ... | ... | ... | ... | ... |++Ready: N | Fix needed: N | Blocked: N | Draft: N+──────────────────────────────────────────────────────+```++If `--dry-run`, stop here. Print the queue and exit.++### Phase 2 — Confirm and merge ready PRs++Unless `--force` was passed, use `AskUserQuestion` to confirm before merging:++```+Ready to merge N PRs:+ [repo]#[number] — [title] → [base]+ [repo]#[number] — [title] → [base]++ [Merge all N now] [Let me pick which ones] [Dry run — don't merge]+```++If user picks "Let me pick", show each PR with `[Merge]` / `[Skip]` options via `AskUserQuestion`.++For each confirmed PR:++1. Verify CI is still green: `gh pr checks <number> --repo <repo>`+2. If green: `gh pr merge <number> --repo <repo> --squash --admin`+3. Report: `✓ Merged <repo>#<number> to <base>`++### Phase 3 — Dispatch fixers for PRs that need work++For PRs classified as `needs-rebase`, `needs-ci-fix`, or `needs-review-response`:++**Dispatch subagents in parallel** (max 5 concurrent, one repo per agent):++Each fixer agent gets a worktree and this brief:++```+Task: Fix PR #<number> in <repo> (<classification>)+Repo path: <path from registry>+Branch: <headRefName>++<classification-specific instructions>++For needs-rebase:+ 1. Create worktree from the PR branch+ 2. Rebase on <baseBranchRef>: `git rebase <base>`+ 3. Resolve any conflicts (prefer incoming for .planning/, prefer HEAD for code)+ 4. Push with --force-with-lease --no-verify+ 5. Verify PR is now MERGEABLE++For needs-ci-fix:+ 1. Get failed check logs: `gh run view <id> --repo <repo> --log-failed | tail -80`+ 2. Diagnose the failure+ 3. Fix the code in a worktree+ 4. Commit + push --no-verify+ 5. Wait for CI to re-run (or report what was fixed)++For needs-review-response:+ 1. Read review comments: `gh api repos/<repo>/pulls/<number>/comments --jq '.[].body'`+ 2. Address each comment in code+ 3. Reply to each comment via gh api+ 4. Push fixes+ 5. Re-request review if needed++After fixing:+ - Report back: what was wrong, what was fixed, is CI green now?+ - Do NOT auto-merge after fixing. Report the fix and let Phase 4 handle confirmation.+```++Use `model: "sonnet"` for all fixer agents.++### Phase 4 — Collect results and confirm merges++As fixers complete:++1. Verify the PR is now green: `gh pr checks <number> --repo <repo>`+2. If green, use `AskUserQuestion` to confirm (unless `--force`):+ ```+ Fixer resolved [repo]#[number] — [what was fixed]. CI is now green.+ [Merge now] [Skip — I'll review manually]+ ```+3. If still red: report what's still broken, do not merge++### Phase 5 — `--main` sync (only if flag is set)++For each repo that has separate `dev` and `main` branches:++1. Check if dev is ahead of main: `git -C <path> log main..dev --oneline | head -5`+2. If ahead, show the commits and use `AskUserQuestion`:+ ```+ [repo]: dev is N commits ahead of main:+ [commit list]++ [Create sync PR and merge] [Create PR only — I'll review] [Skip this repo]+ ```+3. If confirmed: create sync PR: `gh pr create --repo <repo> --base main --head dev --title "chore: sync dev → main"`+4. Wait for CI: `gh pr checks <sync-pr-number> --repo <repo> --watch` (background, max 10 min)+5. If CI green: `gh pr merge <sync-pr-number> --repo <repo> --merge --admin` (merge commit, not squash)+6. Pull main back into dev: `git -C <path> fetch origin && git -C <path> checkout dev && git -C <path> merge origin/main --no-edit`++### Phase 6 — Final report++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► MERGE COMPLETE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++| Repo | PR | Result |+|------|----|--------|+| my-api | #2958 | ✓ merged to dev |+| my-app | #4456 | ✓ fixed CI + merged |+| mise | #10 | ✗ 3 critical bugs — skipped |++Merged: N PRs across M repos+Skipped: N (blocked/draft)+Failed: N (still need manual attention)++Main sync: N repos synced (dev → main → dev)+──────────────────────────────────────────────────────+```++---++## Safety Rails (NEVER violate)++- **NEVER force-push to main/master**+- **NEVER merge with red CI** — fix root cause first+- **NEVER bypass review on PRs touching auth, payments, PII, or secrets** — these require `security-reviewer` subagent audit before merge+- **NEVER run `git reset --hard` on shared branches**+- **ALWAYS use worktrees** for fixes (multiple agents may be active)+- **ALWAYS use `--admin` only for squash merges to dev** (not main, unless `--main` flag)+- **Max 10 PRs per invocation** to avoid GitHub API throttling+- **If a PR has > 50 files changed**, flag it for manual review instead of auto-merging++---++## Native tool usage++### Monitor — live CI watching++When waiting for CI after a fixer pushes (Phase 3-4), use `Monitor` to stream the GitHub Actions run output instead of polling:+```+Monitor(command: "gh run watch <run-id> --repo <repo>")+```+This avoids sleep loops and gives real-time feedback on CI progress.++### Tasks — progress tracking++Create a `TaskCreate` for the overall merge pipeline and individual tasks per PR. Update with `TaskUpdate` as each PR is fixed/merged/skipped. This gives the user a live checklist view.++### WebSearch — CI failure context++When a fixer agent encounters an obscure CI failure, use `WebSearch` to find known issues (e.g., npm registry outages, GitHub Actions incidents, flaky test patterns).diff --git a/claude-ops/skills/ops-next/SKILL.md b/claude-ops/skills/ops-next/SKILL.mdnew file mode 100644index 00000000..3d5d476d--- /dev/null+++ b/claude-ops/skills/ops-next/SKILL.md@@ -0,0 +1,162 @@+---+name: ops-next+description: Business-level "what should I do next". Priority stack — fires > unread comms > ready-to-merge PRs > Linear sprint > revenue-generating GSD work. Uses pre-gathered data and routes to the right skill.+argument-hint: "[context]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TaskCreate+ - TaskUpdate+ - WebFetch+ - mcp__linear__list_issues+ - mcp__claude_ai_Slack__slack_search_public_and_private+effort: low+maxTurns: 15+---++## Runtime Context++Before advising, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `owner`, `primary_project`, `default_channels`+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — flag any action_needed as priority+3. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/topics_active.md` for ongoing work context+++# OPS ► NEXT ACTION++## CLI/API Reference++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh pr list --state open --json number,title,statusCheckRollup,reviewDecision` | Open PRs with CI/review status | JSON array |++---++## Pre-gathered data++### Infrastructure & fires++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || echo '{"clusters":[]}'+```++### Git & PRs++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-prs 2>/dev/null || echo '[]'+```++### CI status++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-ci 2>/dev/null || echo '[]'+```++### Unread messages++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-unread 2>/dev/null || echo '{}'+```++### GSD active phases++```!+for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ if [ -f "$expanded/.planning/STATE.md" ]; then+ alias=$(basename "$expanded")+ cat "$expanded/.planning/STATE.md" 2>/dev/null | head -30+ echo "---NEXT---"+ fi+done+```++---++## Your task++Apply the priority stack to all pre-gathered data:++### Priority 1 — FIRES++Check infra data for: unhealthy ECS tasks, stopped services, failed deployments.+Check CI for: broken `main` or `dev` branches.+If any fires exist → **recommend `/ops-fires` immediately**.++### Priority 2 — URGENT COMMS++Check unread counts. If WhatsApp or email has unread messages from humans (not automated):++- Estimate urgency from sender/preview if available+- If urgent comms → **recommend `/ops-inbox [channel]`**++### Priority 3 — READY-TO-MERGE PRs++Check PRs for: CI green + no unresolved review comments + not draft.+If any ready → **recommend reviewing that PR now**.+Check: `gh pr list --state open --json number,title,statusCheckRollup,reviewDecision 2>/dev/null`++### Priority 4 — LINEAR SPRINT++Fetch current sprint issues: use `mcp__linear__list_issues` filtered to current cycle (use Linear GraphQL fallback for cycle queries if needed).+Find highest-priority issue that is in progress or unstarted.++### Priority 5 — GSD WORK++From GSD state, find the highest revenue-impact active phase across all projects.+Revenue weighting: read `revenue.stage` and `priority` from `scripts/registry.json` — projects with lower priority numbers (higher priority) and revenue stage of `growth` or `active` outrank `pre-launch` or `development`. Within the same tier, prioritize closest-to-done phases.++---++## Output format++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► NEXT ACTION+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ TOP PRIORITY: [fires|comms|PR|sprint|gsd]+ ▶ [specific action in one sentence]++ WHY: [1-2 sentence rationale]++──────────────────────────────────────────────────────+ Full priority stack:+ 1. [action] — [why] → [/skill or command]+ 2. [action] — [why] → [/skill or command]+ 3. [action] — [why] → [/skill or command]+ 4. [action] — [why] → [/skill or command]+ 5. [action] — [why] → [/skill or command]++──────────────────────────────────────────────────────+ a) Do #1 now+ b) Do #2 now+ c) Show me everything (/ops-go)+ d) I'll decide — just show the briefing++ → Pick or describe what you want+──────────────────────────────────────────────────────+```++Use AskUserQuestion. When user selects an option, invoke the corresponding skill directly — don't describe it, do it.++If `$ARGUMENTS` contains context (e.g., "focus on <project-alias>"), constrain the analysis to that context.++---++## Native tool usage++### Tasks — action tracking++After the user selects an action, use `TaskCreate` to track it. When routing to the corresponding skill, the task persists as a reminder of what the user chose to focus on.++### WebFetch — enrichment fallback++When pre-gathered data is stale or incomplete, use `WebFetch` to pull fresh data from APIs (Linear GraphQL, Sentry, GitHub) directly.diff --git a/claude-ops/skills/ops-orchestrate/SKILL.md b/claude-ops/skills/ops-orchestrate/SKILL.mdnew file mode 100644index 00000000..346d99ad--- /dev/null+++ b/claude-ops/skills/ops-orchestrate/SKILL.md@@ -0,0 +1,496 @@+---+name: ops-orchestrate+description: "Autonomous multi-project orchestration engine. Audits all registered projects, structures work into dependency-wired tasks, dispatches parallel agents (subagents or Agent Teams), audits completions, and ships PRs. Registry-driven — works for any user with a configured project registry."+argument-hint: "[--teams|--subagents|--hybrid|--dry-run|--project alias|--fires-only|--max-waves N]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Edit+ - Grep+ - Glob+ - Agent+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - TaskCreate+ - TaskUpdate+ - TaskGet+ - TaskList+ - TaskStop+ - TaskOutput+ - Monitor+ - WebFetch+ - WebSearch+ - EnterPlanMode+ - ExitPlanMode+ - CronCreate+ - CronList+ - LSP+ - mcp__sentry__search_issues+ - mcp__linear__list_issues+ - mcp__linear__update_issue+ - mcp__linear__create_issue+effort: high+model: claude-opus-4-6+maxTurns: 100+---++## Runtime Context++Before orchestrating, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `owner`, `timezone`, `yolo_enabled`, registry path+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — ensure all services healthy before dispatching+3. **Secrets**: Resolve via env → Doppler → password manager: `GITHUB_TOKEN`, `SENTRY_AUTH_TOKEN`, `LINEAR_API_KEY`, `ANTHROPIC_API_KEY`+4. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/topics_active.md` for priority context+++# OPS ► ORCHESTRATE — Autonomous Work Engine++## CLI/API Reference++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh pr list --state open --json number,title,statusCheckRollup,reviewDecision,mergeable,isDraft` | Open PRs with status | JSON array |+| `gh pr view <n> --repo <repo> --json files,additions,deletions` | PR file diff summary | JSON |+| `gh pr checks <n>` | CI check status | Check list |+| `gh pr merge <n> --squash --admin` | Squash merge PR | Merge result |+| `gh run list --repo <repo> --workflow "<workflow>" --limit 5 --json conclusion,headBranch` | CI runs for workflow | JSON array |+| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |+| `gh issue list --state open` | Open issues | JSON array |++### sentry-cli / Sentry API++| Command | Usage | Output |+|---------|-------|--------|+| `sentry-cli issues list --project <slug> --status unresolved` | Unresolved issues | Issue list |+| `curl -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" "https://sentry.io/api/0/projects/<org>/<proj>/issues/?query=is:unresolved"` | API fallback | JSON array |++### Linear GraphQL (fallback when MCP unavailable)++| Command | Usage | Output |+|---------|-------|--------|+| `curl -X POST https://api.linear.app/graphql -H "Authorization: $LINEAR_API_KEY" -H "Content-Type: application/json" -d '{"query":"{ issues(filter: {state: {type: {in: [\"started\",\"unstarted\"]}}}) { nodes { id title state { name } priority assignee { name } } } }"}'` | Active issues | JSON |++---++++You are the **master orchestrator**. Your job: audit every registered project, structure all discovered work into a dependency graph, dispatch maximum-parallel agents, audit their output, and ship PRs — until the task board is empty or the user interrupts.++**No preamble. No "would you like me to". Execute immediately.**++---++## Context Detection++Detect where this skill was invoked:++```bash+# If invoked from a specific project directory (not ~), scope to that project+CWD="$(pwd)"+if [ "$CWD" != "$HOME" ] && [ -d "$CWD/.git" ]; then+ echo "SCOPED:$CWD"+else+ echo "GLOBAL"+fi+```++- **SCOPED mode** (invoked inside a project dir): Limit work to that project only. Include all todos/tasks from the current conversation context. Skip the global registry scan.+- **GLOBAL mode** (invoked from ~ or with no git repo): Scan all registered projects.++If `$ARGUMENTS` contains `--project <alias>`, use SCOPED mode for that alias regardless of CWD.++---++## Orchestration Mode — How to Choose++### Decision matrix (shown to user if no flag passed)++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ ORCHESTRATION MODE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ --subagents (default) Fire-and-forget. Cheapest. Best for:+ - Independent single-repo fixes+ - Tasks that don't need mid-flight changes+ - Cost: ~1.5-2x base token usage++ --teams Agent Teams with mid-flight steering. Best for:+ - Cross-repo contract changes (API + consumer)+ - Security/auth work touching 2+ repos+ - When you need to redirect agents based on findings+ - Cost: ~3-7x base token usage++ --hybrid (recommended) Auto-selects per task. Teams for cross-repo+ and security work, subagents for everything else.+ Best balance of speed, cost, and coordination.+ Cost: ~2-4x base token usage++ --dry-run Audit + plan only. Shows what would be dispatched+ without executing. Good for reviewing before committing.+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++If no flag is passed, use `AskUserQuestion`:+```+ [Subagents — fast & cheap] [Agent Teams — steerable] [Hybrid — auto-select] [Dry run — plan only]+```++### Auto-detection heuristic (for `--hybrid` mode)++Tag each task during Phase 2:++| Condition | Mode | Why |+|-----------|------|-----|+| Task touches 1 repo, no auth/payments/PII | `subagent` | Isolated, no coordination needed |+| Task touches 2+ repos (API schema + consumer) | `team` | Teammates coordinate schema handoff |+| Task touches auth, payments, PII, secrets | `team` | Security-reviewer teammate audits in real-time |+| Task is read-only (audit, report, analysis) | `subagent` | No risk, no coordination |+| Task depends on another in-flight task's output | `team` | SendMessage delivers output without re-dispatch |++### Feature flag requirement for Agent Teams++Agent Teams requires `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`. Check before using:++```bash+[ "${CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:-0}" = "1" ] && echo "teams_available" || echo "teams_unavailable"+```++If `--teams` or `--hybrid` is requested but the flag is off, warn and fall back to `--subagents`.++---++## Phase 1 — Audit (parallel, read-only)++### 1a. Discover projects++**SCOPED mode**: Use only the current directory. Read `.planning/STATE.md` if it exists.++**GLOBAL mode**: Scan the project registry:++```bash+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+jq -r '.projects[] | "\(.alias)|\(.paths[0])|\(.repos[0] // "none")|\(.gsd // false)"' "$REGISTRY" 2>/dev/null+```++For each project path, verify it exists on disk. Skip missing paths.++### 1b. Parallel audit dispatch++Group projects into batches of ~8. Dispatch one audit subagent per batch (always subagents — audit is read-only, no steering needed):++Each audit agent checks:+- `git status --porcelain` — uncommitted changes+- `git log origin/dev..HEAD --oneline` — unpushed commits+- `gh pr list --state open --json number,title,statusCheckRollup,reviewDecision,mergeable,isDraft` — open PRs + CI+- `gh run list --limit 5 --json status,conclusion,name,headBranch,createdAt` — recent CI runs+- `.planning/STATE.md` — current GSD phase + progress+- `.planning/ROADMAP.md` — upcoming phases+- Unresolved review comments on open PRs++### 1c. Filter already-fixed failures++Before creating tasks for CI failures:+```bash+# If latest run on dev/main is success → skip (intermittent or already fixed)+gh run list --repo <repo> --workflow "<workflow>" --limit 5 --json conclusion,headBranch \+ --jq '[.[] | select(.headBranch == "dev" or .headBranch == "main")] | .[0].conclusion'+```++- Latest = `success` → **skip**+- Latest = `failure` AND 2+ prior also `failure` → **create task** (persistent)+- Latest = `failure` but prior = `success` → **create P2 task** (new regression)++### 1d. External issue sources (parallel with 1b)++Run these in parallel with the audit agents:++- **Sentry**: `mcp__sentry__search_issues` or `sentry-cli issues list` — P0/P1 unresolved errors+- **Linear**: `mcp__linear__list_issues` for current sprint — in-progress and unstarted+- **GitHub Issues**: `gh issue list --state open` per repo+- **Conversation context**: Scan current conversation for todos, requests, and incomplete work the user mentioned++### 1e. Cross-reference against existing tasks++`TaskList` — check current task board. Flag:+- Tasks already done → mark `completed`+- Tasks stale (root cause changed) → update description+- New work not yet in TaskList → queue for Phase 2++---++## Phase 2 — Structure (TaskCreate + dependency wiring)++### 2a. Decompose into atomic tasks++Each task should be:+- **One PR max** (~2-4 hour scope)+- **One repo only** (isolation for parallel execution)+- **Clear acceptance criteria** (what "done" looks like)++### 2b. TaskCreate with rich metadata++```+TaskCreate({+ title: "fix: resolve auth middleware race condition",+ description: "File: src/middleware/auth.ts:42\nRepo: my-api\nBranch: fix/auth-race\nAcceptance: unit test passes, no Sentry errors for 5min post-deploy",+ metadata: {+ project: "my-api",+ repo: "your-org/my-api",+ priority: "P1-revenue",+ mode: "subagent", // or "team" — used by hybrid mode+ wave: 0, // parallelization wave+ paths: ["src/middleware/auth.ts", "tests/auth/"],+ quality_gate: "npm run type-check && npm run lint && npm run test:unit"+ }+})+```++### 2c. Wire dependencies (CRITICAL for max parallelism)++**Rules for dependency wiring:**++1. **If tasks are independent → NO dependency. They run in the SAME wave.**+2. **Only add `addBlockedBy` when the output of task A is genuinely required as input for task B.**+3. **Never serialize tasks that can run in parallel.** Three independent bug fixes in three repos = wave 0, all three, simultaneously.++Common dependency patterns:+- Deploy task → blocked by its implementation task+- Phase N task → blocked by Phase N-1 completion+- Consumer update → blocked by API schema change (cross-repo)+- PR merge → blocked by CI passing+- Main merge → blocked by dev merge++**Anti-patterns to AVOID:**+- ❌ Serializing independent single-repo fixes (they should be wave 0 parallel)+- ❌ Making task B depend on task A just because A was discovered first+- ❌ Waiting for all wave 0 to complete before starting ANY wave 1 (start wave 1 tasks as soon as their specific blockers clear)++### 2d. Assign waves++```+Wave 0: All tasks with ZERO dependencies → dispatch ALL simultaneously+Wave 1: Tasks blocked only by wave 0 items → dispatch as each blocker clears+Wave N: Cascade — but NEVER wait for the full wave to clear.+ Start each task the MOMENT its specific blockers resolve.+```++### 2e. Tag orchestration mode (hybrid only)++Apply the decision matrix from above to tag each task as `subagent` or `team`.++---++## Phase 3 — Dispatch (maximum parallelism)++### Subagent dispatch++Rules:+- **Max concurrent: 5 agents** (avoid overload)+- **One repo per agent** (no concurrent edits to same path)+- **Each agent gets a worktree** via `isolation: "worktree"`+- **Use `model: "sonnet"`** on every `Agent()` call (saves quota)+- **Use `run_in_background: true`** — never block waiting+- Mark task `in_progress` via `TaskUpdate` before dispatching++```+Agent({+ description: "Fix auth race condition in my-api",+ model: "sonnet",+ isolation: "worktree",+ run_in_background: true,+ prompt: "<full task brief with repo path, file paths, branch strategy, acceptance criteria, quality gate>"+})+```++### Agent Teams dispatch++Only when mode is `--teams` or task is tagged `team` in hybrid:++```+TeamCreate("wave-0-cross-repo")++Agent(team_name="wave-0-cross-repo", name="api-worker", model="sonnet", isolation="worktree",+ prompt="<task brief with FILE OWNERSHIP boundaries>")++Agent(team_name="wave-0-cross-repo", name="mobile-worker", model="sonnet", isolation="worktree",+ prompt="<task brief with FILE OWNERSHIP boundaries>")+```++**File ownership (CRITICAL — prevents overwrites):**+Each teammate prompt MUST include:+```+Your files: src/api/auth.ts, src/middleware/*.ts, tests/auth/+Do NOT edit: src/api/users.ts (owned by api-worker), src/frontend/ (owned by mobile-worker)+```++**Mid-flight steering (the killer feature):**+```+SendMessage(to="api-worker", content="Schema changed — DTO is now UserResponseV2. Update imports.")+SendMessage(to="mobile-worker", content="API endpoint ready. New: POST /v2/users. Proceed with consumer.")+```++**Cross-repo coordination pattern:**+1. Spawn `api-worker` and `consumer-worker` on same team+2. Wire dependency: consumer blocked by api+3. When api-worker completes schema → `SendMessage` to consumer with the new types/endpoint+4. Consumer proceeds with full context — no re-dispatch needed++### Wave execution — NEVER idle++```+WHILE tasks remain:+ 1. TaskList → find ALL unblocked tasks+ 2. Dispatch up to 5 simultaneously (subagent or team per task tag)+ 3. As EACH agent completes → immediately audit (Phase 4)+ 4. As EACH audit passes → immediately ship (Phase 5)+ 5. As EACH ship completes → TaskList again, dispatch newly-unblocked+ 6. NEVER wait for full wave to clear before starting next items+```++Use `Monitor` to stream CI output from running checks instead of sleep-polling.++---++## Phase 4 — Audit (verify each completion)++When an agent reports back, **verify before marking complete**:++1. **Read the PR**: `gh pr view <n> --repo <repo> --json files,additions,deletions`+2. **Verify diff matches task**: does the change actually fix what was described?+3. **Run quality gate**:+ ```bash+ # From task metadata+ cd <worktree> && eval "<quality_gate command>"+ ```+4. **Check CI**: `gh pr checks <n>` — all green?+5. **Security scan**: if auth/payment/PII touched → dispatch `security-reviewer` subagent+6. **If audit fails**:+ - Subagent mode: reopen task, re-dispatch fresh agent with failure context+ - Teams mode: `SendMessage(to="<worker>", content="Audit failed: <issue>. Fix and re-submit.")`+7. **If audit passes**: proceed to Phase 5++---++## Phase 5 — Ship (merge + deploy)++For each PR that passed audit:++1. **Address review comments**: read via `gh api`, resolve each+2. **CI verification**: `gh pr checks <n>` — wait via `Monitor` if still running+3. **Merge conflict resolution**: check `mergeable` state, resolve if needed+4. **Merge to dev**: `gh pr merge <n> --squash --admin` (use `AskUserQuestion` to confirm unless `--force`)+5. **Merge dev → main** (if applicable and authorized): create sync PR, wait CI, merge+6. **Post-deploy verification**: health check, Sentry check for new errors++---++## Phase 5.5 — Liveness Monitor (between every wave)++```bash+# Check each in-flight agent's worktree for recent writes+for wt in .worktrees/*/; do+ last_write=$(find "$wt" -maxdepth 3 -type f -newer /tmp/ops-orchestrate-start 2>/dev/null | wc -l)+ echo "$(basename $wt): $last_write files changed since start"+done+```++**Stalled agent protocol (>15 min since last write):**++- **Subagents**: `TaskStop` → assess partial progress → re-dispatch with narrowed scope+- **Teams**: `SendMessage(to="<worker>", content="Status check — are you stuck?")` → wait 60s → if no response, `TaskStop` and replace++**Never re-dispatch the exact same prompt.** The agent stalled for a reason. Narrow scope, add file paths, or split the task.++---++## Phase 6 — Loop++```+WHILE true:+ TaskList → check board state+ IF all tasks completed/blocked → print final report, HALT+ IF pending unblocked tasks exist → go to Phase 3+ IF all pending are blocked → surface blockers to user, HALT+ Run Phase 5.5 liveness check on in-flight agents+```++### Completion criteria++Do NOT stop until:+- Every task is `completed`, `deleted`, or explicitly `blocked` on user input+- All PRs merged (at minimum to dev)+- All background processes terminated+- All teams cleaned up (Teams mode)+- Final report printed++---++## Reporting++Between waves:+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ORCHESTRATE — Wave N | Mode: [subagents/teams/hybrid]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ TASK OWNER STATUS PR CI DEPLOY+ ──────────────────────────────────────────────────────────+ fix auth api-worker ✓ done #4417 ✓ dev merged+ update types mobile-worker ◉ wip #488 … —+ add tests test-agent ○ queue — — —++ Completed: N/T | In-flight: N | Queued: N | Blocked: N+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++Final report:+```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► ORCHESTRATION COMPLETE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Mode: [subagents/teams/hybrid]+ Completed: N tasks, M PRs shipped, K promoted to main+ Blocked: [list with rationale]+ Follow-ups:[list with task IDs]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++---++## Safety Rails (NEVER violate)++- **NEVER force-push to main/master**+- **NEVER merge with red CI** — fix root cause first+- **NEVER bypass review on PRs touching auth, payments, PII, secrets** — require `security-reviewer` audit+- **NEVER touch `.env`, credentials, or secrets files** — flag and skip+- **NEVER `git reset --hard` on shared branches**+- **ALWAYS use worktrees** — multiple agents may be active concurrently+- **ALWAYS define file ownership** when 2+ teammates touch same repo+- **NEVER spawn teammates after entering delegate mode** (known bug: teammates lose file tools)+- **Max 5 concurrent agents** — respect system limits++---++## Arguments++| Flag | Effect |+|------|--------|+| (empty) | Full audit + execution, ask for mode |+| `--subagents` | Force subagent mode (cheapest) |+| `--teams` | Force Agent Teams mode (steerable, 3-7x cost) |+| `--hybrid` | Auto-select per task (recommended) |+| `--dry-run` | Phase 1+2 only, print plan, don't dispatch |+| `--project <alias>` | Scope to one project |+| `--fires-only` | Only P0 production-broken tasks |+| `--no-main` | Stop at dev merge, never touch main |+| `--max-waves N` | Cap at N waves then halt |+| `--force` | Skip merge confirmations |++---++Begin with Phase 1 immediately. Do not ask for confirmation (except mode selection if no flag).diff --git a/claude-ops/skills/ops-projects/SKILL.md b/claude-ops/skills/ops-projects/SKILL.mdnew file mode 100644index 00000000..e04ba42a--- /dev/null+++ b/claude-ops/skills/ops-projects/SKILL.md@@ -0,0 +1,150 @@+---+name: ops-projects+description: Portfolio dashboard — shows all projects with GSD phase, branch, uncommitted changes, CI status, and next action. Jump to any project by alias.+argument-hint: "[project-alias]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TaskCreate+ - TaskUpdate+ - WebFetch+effort: low+maxTurns: 20+disallowedTools:+ - Edit+ - Write+ - NotebookEdit+---++## Runtime Context++Before rendering, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `owner`, `timezone` for display+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — show service status in dashboard+++# OPS ► PROJECTS DASHBOARD++## CLI/API Reference++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh pr list --repo <owner/repo> --json number,title,statusCheckRollup,reviewDecision,mergeable` | Open PRs with CI | JSON array |+| `gh run list --repo <repo> --limit 5 --json status,conclusion,name,headBranch` | CI runs | JSON array |+| `gh issue list --repo <repo> --json number,title,labels,state` | Issues | JSON array |++---++## Pre-gathered git status++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-git 2>/dev/null || echo '[]'+```++## Open PRs++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-prs 2>/dev/null || echo '[]'+```++## CI status++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-ci 2>/dev/null || echo '[]'+```++## Project registry++```!+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null || echo '{}'+```++## GSD state (all active roadmaps)++```!+for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ if [ -f "$expanded/.planning/STATE.md" ]; then+ alias=$(jq -r --arg p "$d" '.projects[] | select(.paths[] == $p) | .alias' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null | head -1)+ phase=$(grep -m1 'current_phase' "$expanded/.planning/STATE.md" 2>/dev/null | sed 's/.*: //' || echo "?")+ branch=$(git -C "$expanded" branch --show-current 2>/dev/null || echo "?")+ dirty=$(git -C "$expanded" status --porcelain 2>/dev/null | wc -l | tr -d ' ')+ echo "{\"alias\":\"$alias\",\"path\":\"$d\",\"phase\":\"$phase\",\"branch\":\"$branch\",\"dirty\":$dirty}"+ fi+done | jq -s '.'+```++---++## Your task++Parse all pre-gathered data and render the portfolio dashboard.++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► PROJECTS — [date]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ ALIAS PHASE BRANCH DIRTY CI NEXT ACTION+ ────────────────────────────────────────────────────────────────+ example-app 7.2 feature/auth 3 ✓ finish auth tests+ example-api 5.0 dev 0 ✗ fix CI (unit tests)+ ...++OPEN PRs+ #123 example-api fix: auth middleware ✓ CI ready to merge+ #456 example-app feat: onboarding ✗ CI needs fix++──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each) for the project selector. Paginate at 3 projects + `[More projects...]` per page. On the final page, replace "More projects..." with the remaining projects. The user can also type a project alias directly as free text.++**CI column**: green ✓ if last run passed, red ✗ if failing, — if no CI.+**DIRTY**: number of uncommitted files.+**NEXT ACTION**: inferred from GSD phase state and open issues.++---++## Jump to project++If `$ARGUMENTS` contains a project alias, show a deep-dive for that project:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ [PROJECT] — DEEP DIVE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Path: [path]+ Branch: [branch] Dirty: [N files]+ GSD: Phase [N] — [phase name]+ CI: [last 5 runs with status]+ PRs: [open PRs]+ Sentry: [recent errors for this project]++ Actions:+ a) Continue GSD work (/gsd-next)+ b) Fix CI failure+ c) Review open PRs+ d) Check fires (/ops-fires [alias])+```++Use AskUserQuestion after displaying either view.++---++## Native tool usage++### Tasks — project action tracking++When the user jumps to a project, use `TaskCreate` to track the action they take. This carries context forward if they switch between projects.++### WebFetch — CI enrichment++When `gh` is slow or rate-limited, use `WebFetch` to query GitHub Actions API directly for run status.diff --git a/claude-ops/skills/ops-revenue/SKILL.md b/claude-ops/skills/ops-revenue/SKILL.mdnew file mode 100644index 00000000..16287647--- /dev/null+++ b/claude-ops/skills/ops-revenue/SKILL.md@@ -0,0 +1,183 @@+---+name: ops-revenue+description: Revenue and costs tracker. AWS spend via aws ce, credits tracker, project revenue stages. Shows burn rate, runway estimate, credits expiring.+argument-hint: "[costs|revenue|credits|runway|all]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - AskUserQuestion+ - WebFetch+ - Write+effort: low+maxTurns: 20+disallowedTools:+ - Edit+ - NotebookEdit+---++# OPS ► REVENUE & COSTS++## Runtime Context++Before executing, load available context:++1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`+ - `timezone` — display all timestamps correctly++2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`+ - If `action_needed` is not null → surface it before the cost report++3. **Secrets**: AWS Cost Explorer requires credentials.+ ### Secret Resolution+ - AWS: check `$AWS_PROFILE` / `$AWS_ACCESS_KEY_ID` → `doppler secrets get AWS_ACCESS_KEY_ID --plain` → vault query cmd from prefs+ - If no credentials available, report "AWS costs unavailable — credentials not configured" and show only the revenue pipeline from registry++## CLI/API Reference++### aws CLI (Cost Explorer)++| Command | Usage | Output |+|---------|-------|--------|+| `aws ce get-cost-and-usage --time-period Start=<YYYY-MM-DD>,End=<YYYY-MM-DD> --granularity MONTHLY --metrics "UnblendedCost" --group-by "Type=DIMENSION,Key=SERVICE" --output json` | Cost by service | Cost JSON |+| `aws ce get-cost-and-usage --time-period Start=<YYYY-MM-DD>,End=<YYYY-MM-DD> --granularity MONTHLY --metrics "UnblendedCost" --output json` | Total cost | Cost JSON |+| `aws ce get-cost-forecast --time-period Start=<YYYY-MM-DD>,End=<YYYY-MM-DD> --metric "UNBLENDED_COST" --granularity MONTHLY --output json` | End-of-month forecast | Forecast JSON |+| `aws ce list-savings-plans-purchase-recommendation --output json` | Savings plan recommendations | JSON |++---++## Phase 1 — Gather financial data in parallel++### AWS costs (current month)++```bash+aws ce get-cost-and-usage \+ --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" \+ --granularity MONTHLY \+ --metrics "UnblendedCost" \+ --group-by "Type=DIMENSION,Key=SERVICE" \+ --output json 2>/dev/null+```++### AWS costs (last 3 months trend)++```bash+aws ce get-cost-and-usage \+ --time-period "Start=$(date -v-3m +%Y-%m-01),End=$(date +%Y-%m-%d)" \+ --granularity MONTHLY \+ --metrics "UnblendedCost" \+ --output json 2>/dev/null+```++### AWS credits remaining++```bash+aws ce list-savings-plans-purchase-recommendation --output json 2>/dev/null || echo '{}'+aws ce get-credits --output json 2>/dev/null || echo "credits API unavailable"+```++### AWS cost forecast (end of month)++```bash+aws ce get-cost-forecast \+ --time-period "Start=$(date +%Y-%m-%d),End=$(date +%Y-%m-28)" \+ --metric "UNBLENDED_COST" \+ --granularity MONTHLY \+ --output json 2>/dev/null+```++### Project registry (revenue stage)++```bash+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null | jq '[.projects[] | {alias, name, stage: (.revenue_stage // "pre-revenue"), mrr: (.mrr // 0)}]'+```++---++## Phase 2 — Render dashboard++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► REVENUE & COSTS — [month]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++AWS SPEND+ This month to date: $[X]+ Forecast (EOM): $[X]+ Last month: $[X]+ MoM change: [+/-X%]++ Top services:+ [service] $[X] ([%] of total)+ [service] $[X]+ ...++CREDITS+ AWS credits remaining: $[X]+ Expires: [date]+ Burn rate at current: [N months remaining]++REVENUE PIPELINE+ PROJECT STAGE MRR STATUS+ ────────────────────────────────────────────────+ [project] [stage] $[X] [status]+ ...+ ────────────────────────────────────────────────+ TOTAL MRR $[X]++RUNWAY ESTIMATE+ Monthly burn (AWS): $[X]+ Total MRR: $[X]+ Net burn: $[X/month]+ Credits cover: [N months]+ Cash runway: [depends on external data]++──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each):++AskUserQuestion call 1:+```+ [Drill into AWS costs by service]+ [Show cost anomalies (spike detection)]+ [Export cost report]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Update project revenue stage]+ [Set budget alert]+```++---++## Route by `$ARGUMENTS`++| Argument | Action |+| -------- | ---------------------------- |+| costs | Show only AWS cost breakdown |+| credits | Show only credits and expiry |+| revenue | Show only revenue pipeline |+| runway | Calculate and show runway |+| (empty) | Show full dashboard |++Use AskUserQuestion after the dashboard for next action.++---++## Native tool usage++### WebFetch — billing API fallback++When `aws ce` commands fail or return incomplete data, use `WebFetch` to query the AWS Cost Explorer API directly. Also useful for fetching Stripe/billing provider data if configured.++### Write — export reports++When user selects "Export cost report" (option c), use `Write` to save the report as a dated file:+```+Write(file_path: "/tmp/ops-revenue-[date].md", content: "[formatted report]")+```diff --git a/claude-ops/skills/ops-speedup/SKILL.md b/claude-ops/skills/ops-speedup/SKILL.mdnew file mode 100644index 00000000..b0af601f--- /dev/null+++ b/claude-ops/skills/ops-speedup/SKILL.md@@ -0,0 +1,375 @@+---+name: ops-speedup+description: Cross-platform system speedup and cleanup. Auto-detects macOS/Linux/WSL, scans for reclaimable disk space, memory pressure, runaway processes, startup bloat, network issues. CleanMyMac built into Claude Code.+argument-hint: "[scan|clean|deep|auto]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - AskUserQuestion+effort: low+maxTurns: 30+---++## Runtime Context++Before scanning, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `timezone` for timestamps+++# OPS > SPEEDUP — System Optimizer++## CLI/API Reference++### ops-speedup bin script++| Command | Usage | Output |+|---------|-------|--------|+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-speedup` | Visual header + quick scan | Formatted ASCII output |+| `${CLAUDE_PLUGIN_ROOT}/bin/ops-speedup --json` | Machine-readable diagnostics | JSON with disk, memory, process data |+| `zsh ~/.claude/scripts/speedup.sh` | macOS comprehensive cleanup script | Autonomous cleanup with progress |++### System commands used++| Command | Purpose |+|---------|---------|+| `diskutil apfs list` | Purgeable space on APFS volumes |+| `vm_stat` | macOS memory pressure and page stats |+| `ps aux -m` / `ps aux --sort=-%mem` | Top processes by CPU/RAM |+| `brew outdated --json` / `brew cleanup --dry-run` | Homebrew cache analysis |+| `xcrun simctl list runtimes` / `xcrun simctl delete unavailable` | Xcode simulator management |+| `tmutil listlocalsnapshots /` | Time Machine local snapshots |+| `launchctl list` / `launchctl bootout` | Launch agent management |+| `sudo dscacheutil -flushcache` + `sudo killall -HUP mDNSResponder` | macOS DNS flush |+| `sudo systemd-resolve --flush-caches` | Linux DNS flush |+| `journalctl --vacuum-time=7d` | Linux journal log cleanup |++---++## Phase 1 — Visual header + system scan++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-speedup 2>/dev/null || echo "SCAN_FAILED"+```++## Phase 2 — Deep diagnostic scan++Gather full diagnostics (the --json flag returns machine-readable data):++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-speedup --json 2>/dev/null || echo '{}'+```++## macOS fast path++On macOS, there's an existing comprehensive speedup script at `~/.claude/scripts/speedup.sh`. For `auto`, `clean`, or `deep` modes, run it directly:++```bash+zsh ~/.claude/scripts/speedup.sh+```++This handles process cleanup, memory optimization, disk cleanup, network optimization, and more — all autonomously. The ops-speedup adds the visual dashboard wrapper and cross-platform support on top.++## Your task++Parse the diagnostic JSON and present an actionable cleanup report. Then execute cleanup actions the user approves. Run ALL diagnostic probes in parallel — never sequential when independent.++### OS-specific scan additions++After parsing the pre-gathered JSON, run these **parallel** additional scans based on detected OS:++#### macOS additional scans++```bash+# Parallel scans — run all at once+# 1. Homebrew outdated+brew outdated --json 2>/dev/null | jq 'length' || echo "0"++# 2. Simulator runtimes (Xcode)+xcrun simctl list runtimes 2>/dev/null | grep -c "unavailable" || echo "0"++# 3. Old iOS device support files+du -sm ~/Library/Developer/Xcode/iOS\ DeviceSupport 2>/dev/null | awk '{print $1}' || echo "0"++# 4. Homebrew cleanup potential+brew cleanup --dry-run 2>/dev/null | tail -1 || echo "nothing"++# 5. Time Machine local snapshots+tmutil listlocalsnapshots / 2>/dev/null | wc -l | tr -d ' ' || echo "0"++# 6. System caches+du -sm ~/Library/Caches 2>/dev/null | awk '{print $1}' || echo "0"++# 7. Application caches (Electron apps)+du -sm ~/Library/Application\ Support/Slack/Cache 2>/dev/null | awk '{print $1}' || echo "0"+du -sm ~/Library/Application\ Support/discord/Cache 2>/dev/null | awk '{print $1}' || echo "0"+du -sm ~/Library/Application\ Support/Code/Cache 2>/dev/null | awk '{print $1}' || echo "0"++# 8. Disabled SIP check+csrutil status 2>/dev/null || echo "unknown"++# 9. Spotlight indexing status+mdutil -s / 2>/dev/null || echo "unknown"++# 10. Purgeable space+diskutil apfs list 2>/dev/null | grep -i "purgeable" || echo "unknown"+```++#### Linux additional scans++```bash+# 1. Old kernels+dpkg --list 'linux-image-*' 2>/dev/null | grep ^ii | wc -l || rpm -qa kernel 2>/dev/null | wc -l || echo "?"++# 2. Package cache+du -sm /var/cache/apt/archives 2>/dev/null | awk '{print $1}' || du -sm /var/cache/yum 2>/dev/null | awk '{print $1}' || echo "0"++# 3. Journal logs+journalctl --disk-usage 2>/dev/null | grep -oE '[0-9.]+[MG]' || echo "?"++# 4. Orphan packages+apt list --installed 2>/dev/null | wc -l || echo "?"++# 5. Systemd failed units+systemctl --failed --no-pager 2>/dev/null | grep -c "loaded" || echo "0"+```++---++## Phase 3 — Present cleanup report++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > SYSTEM SPEEDUP — [OS] [version] [chip]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ HEALTH SCORE: [0-100] / 100 [████████░░ 80%]++ DISK RECLAIMABLE+ ────────────────────────────────────────────────────+ Brew cache [N] MB ✓ safe+ npm cache [N] MB ✓ safe+ Xcode DerivedData [N] MB ✓ safe+ Xcode DeviceSupport [N] MB ✓ safe+ Docker unused [N] MB ✓ safe+ System caches [N] MB ⚠ review+ App caches [N] MB ✓ safe+ Trash [N] MB ✓ safe+ Logs [N] MB ✓ safe+ Downloads [N] MB ⚠ review+ /tmp [N] MB ✓ safe+ ────────────────────────────────────────────────────+ TOTAL RECLAIMABLE: [N] GB++ MEMORY+ ────────────────────────────────────────────────────+ Pressure: [N]% Swap: [N] MB+ Processes: [N]+ Top CPU: [process] ([N]%)+ Top RAM: [process] ([N] MB)++ NETWORK+ ────────────────────────────────────────────────────+ DNS: [N]ms (< 50ms = good)++ STARTUP+ ────────────────────────────────────────────────────+ Login items: [N]+ Launch agents: [N]++──────────────────────────────────────────────────────+ Cleanup options:+──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each):++AskUserQuestion call 1 — Cleanup:+```+ [Quick clean — caches, tmp, logs (~[N] GB)]+ [Full clean — + trash, brew, npm, docker (~[N] GB)]+ [Deep clean — + DerivedData, simulators (~[N] GB)]+ [More options...]+```++AskUserQuestion call 2 (only if "More options..."):+```+ [Custom — pick what to clean]+ [Memory — kill top RAM hogs]+ [Startup / Network / Skip...]+```++AskUserQuestion call 3 (only if "Startup / Network / Skip..."):+```+ [Startup — review & disable launch agents]+ [Network — flush DNS, optimize resolver]+ [Skip — just show the report]+```++**Health score calculation:**+- Start at 100+- Disk > 90% used: -20+- Disk > 80% used: -10+- RAM pressure > 80%: -15+- RAM pressure > 60%: -5+- Swap > 1GB: -10+- DNS > 100ms: -5+- > 500 processes: -5+- > 10 launch agents: -5+- > 5GB reclaimable: -10+- > 10GB reclaimable: -20++Use AskUserQuestion for the user's choice.++---++## Phase 4 — Execute cleanup++**Before executing any cleanup**, use `AskUserQuestion` to confirm the scope and estimated impact:++```+About to run [quick/full/deep] clean:+ Brew cache: [N] MB ✓+ npm cache: [N] MB ✓+ Logs: [N] MB ✓+ Tmp files: [N] MB ✓+ [Full: Trash: [N] MB ✓]+ [Full: Docker: [N] MB ✓]+ [Deep: DerivedData [N] MB ✓]+ [Deep: Simulators [N] count ✓]+ ────────────────────────────+ Total: ~[N] GB++ [Proceed] [Switch to custom — pick categories] [Cancel]+```++### Quick clean (option 1)++```bash+# macOS+brew cleanup 2>/dev/null+npm cache clean --force 2>/dev/null+rm -rf ~/Library/Logs/*.log 2>/dev/null+rm -rf /tmp/ops-* /tmp/yolo-* /tmp/claude-* 2>/dev/null++# Linux+sudo apt-get autoclean 2>/dev/null || sudo yum clean all 2>/dev/null+npm cache clean --force 2>/dev/null+sudo journalctl --vacuum-time=7d 2>/dev/null+```++### Full clean (option 2)++Quick clean PLUS:++```bash+# macOS+rm -rf ~/.Trash/* 2>/dev/null+brew autoremove 2>/dev/null+docker system prune -f 2>/dev/null++# Linux+rm -rf ~/.local/share/Trash/files/* 2>/dev/null+docker system prune -f 2>/dev/null+```++### Deep clean (option 3)++Full clean PLUS:++```bash+# macOS only+rm -rf ~/Library/Developer/Xcode/DerivedData/* 2>/dev/null+xcrun simctl delete unavailable 2>/dev/null+rm -rf ~/Library/Caches/com.apple.dt.Xcode 2>/dev/null+```++### Custom (option 4)++Show each category with size and let user toggle on/off.++### Memory (option 5)++Show top 10 processes by RAM. Use **batched AskUserQuestion calls** with `multiSelect` (max 4 options per call) to let user pick which to kill. Paginate at 3 processes + `[More processes...]` per page, with `[Kill selected]` and `[Skip]` on the final page:++AskUserQuestion call 1:+```+ [ ] [process] — [N] MB (PID [N])+ [ ] [process] — [N] MB (PID [N])+ [ ] [process] — [N] MB (PID [N])+ [ ] More processes...+```++Continue batching until all processes shown, then final call:+```+ [ ] [process] — [N] MB (PID [N])+ [Kill selected]+ [Skip]+```++```bash+# macOS+ps aux -m | head -11++# Linux+ps aux --sort=-%mem | head -11+```++**NEVER kill**: Finder, WindowServer, kernel_task, systemd, init, loginwindow, Claude.++### Startup (option 6)++List launch agents with toggle:++```bash+# macOS+ls -la ~/Library/LaunchAgents/ 2>/dev/null+launchctl list 2>/dev/null | grep -v "com.apple" | head -20+```++Offer to disable selected agents:+```bash+launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/<plist> 2>/dev/null+```++### Network (option 7)++```bash+# macOS+sudo dscacheutil -flushcache 2>/dev/null+sudo killall -HUP mDNSResponder 2>/dev/null++# Linux+sudo systemd-resolve --flush-caches 2>/dev/null || sudo resolvectl flush-caches 2>/dev/null+```++Optionally test and suggest switching to faster DNS (1.1.1.1 or 8.8.8.8).++---++## Phase 5 — Results++After cleanup:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS > CLEANUP COMPLETE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Reclaimed: [N] GB+ Disk free: [before] GB -> [after] GB+ Health: [before]/100 -> [after]/100+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++If user came from `/ops:dash`, offer `b) Back to dashboard`.++---++## Mode shortcuts++If `$ARGUMENTS` is:+- `scan` or empty — run Phase 1-3 only (report, no cleanup)+- `clean` — run quick clean automatically (no menu)+- `deep` — run deep clean automatically (no menu)+- `auto` — run full clean automatically, report resultsdiff --git a/claude-ops/skills/ops-triage/SKILL.md b/claude-ops/skills/ops-triage/SKILL.mdnew file mode 100644index 00000000..032b6bfe--- /dev/null+++ b/claude-ops/skills/ops-triage/SKILL.md@@ -0,0 +1,226 @@+---+name: ops-triage+description: Cross-platform issue triage. Pulls from Sentry (MCP), Linear (MCP), GitHub Issues (gh). Cross-references against code to find already-fixed issues. Auto-resolves fixed ones. Dispatches agents for active issues.+argument-hint: "[project-alias|sentry|linear|github|all]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - TaskCreate+ - TaskUpdate+ - TaskList+ - WebFetch+ - WebSearch+ - LSP+ - mcp__sentry__search_issues+ - mcp__sentry__get_issue_details+ - mcp__linear__list_issues+ - mcp__linear__update_issue+ - mcp__linear__get_issue+ - mcp__linear__list_teams+effort: high+model: claude-opus-4-6+maxTurns: 40+---++## Runtime Context++Before triaging, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read project registry for repo paths+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — ensure services healthy+3. **Secrets**: Resolve via env → Doppler → password manager: `SENTRY_AUTH_TOKEN`, `LINEAR_API_KEY`, `GITHUB_TOKEN`+4. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/topics_active.md` for issue context+++# OPS ► CROSS-PLATFORM TRIAGE++## CLI/API Reference++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh issue list --state open --json number,title,body,labels,assignees,createdAt,url --limit 50` | Open issues | JSON array |+| `gh issue list --repo <owner/repo> --state open --json number,title,labels,createdAt --limit 20` | Repo issues | JSON array |+| `gh pr list --state merged --search "#<N>"` | PRs referencing issue | JSON array |+| `gh issue close <N> --comment "<msg>"` | Close issue | Confirmation |++### sentry-cli / Sentry API++| Command | Usage | Output |+|---------|-------|--------|+| `sentry-cli issues list --project <slug> --status unresolved` | Unresolved issues | Issue list |+| `curl -H "Authorization: Bearer $SENTRY_AUTH_TOKEN" "https://sentry.io/api/0/projects/<org>/<proj>/issues/?query=is:unresolved"` | API fallback when MCP unavailable | JSON array |++### Linear GraphQL (fallback when MCP unavailable)++| Command | Usage | Output |+|---------|-------|--------|+| `curl -X POST https://api.linear.app/graphql -H "Authorization: $LINEAR_API_KEY" -H "Content-Type: application/json" -d '{"query":"{ issues(filter: {state: {type: {in: [\"started\",\"unstarted\"]}}}) { nodes { id title state { name } priority assignee { name } } } }"}'` | Active issues | JSON |++---++## Agent Teams support++If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** when dispatching fix agents for multiple issues. This enables:+- Fix agents can share findings (e.g., agent fixing Sentry error discovers the same root cause as a Linear issue)+- You can redirect agents if cross-referencing reveals duplicate issues+- Agents report progress and you can prioritize which fix to merge first++**Team setup** (only when flag is enabled, Phase 4 dispatch):+```+TeamCreate("triage-fixers")+Agent(team_name="triage-fixers", name="fix-[issue-id]", subagent_type="ops:triage-agent", ...)+```++Use `broadcast(content="Root cause found: missing index on users.email — check if your issue is related")` to share discoveries.++If the flag is NOT set, fall back to standard parallel subagents.++## Phase 1 — Gather issues in parallel++Run all of these simultaneously:++### GitHub Issues++```bash+gh issue list --state open --json number,title,body,labels,assignees,createdAt,url --limit 50 2>/dev/null+```++### GitHub Issues (registry-driven)++```bash+REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.json"+[ -f "$REGISTRY" ] || REGISTRY="${CLAUDE_PLUGIN_ROOT}/scripts/registry.example.json"+for repo in $(jq -r '.projects[] | select(.gsd == true) | .repos[]' "$REGISTRY" 2>/dev/null); do+ echo "=== $repo ==="+ gh issue list --repo "$repo" --state open --json number,title,labels,createdAt --limit 20 2>/dev/null+done+```++### Sentry++If Sentry MCP is connected, fetch unresolved issues for all projects.+Otherwise run: `echo "Sentry MCP not available"`++### Linear++Use `mcp__linear__list_teams` to get team IDs, then `mcp__linear__list_issues` with `filter: {state: {type: {in: ["unstarted", "started"]}}}` for each team.++---++## Phase 2 — Cross-reference against code++For each Sentry issue, check if it's already fixed:++1. Extract the error message, file path, and line number from the Sentry event.+2. `grep` for the relevant code in the affected repo.+3. Check git log: `git log --oneline --all -- [file] 2>/dev/null | head -20`+4. If the fix is merged and deployed (check ECS deploy timestamps), mark as resolved.++For each GitHub Issue:++- Check if any merged PR references the issue number (`gh pr list --state merged --search "#[N]"`)+- If referenced and merged, mark as potentially resolved++---++## Phase 3 — Confirm and resolve fixed issues++For issues confirmed fixed in code AND deployed, show the full list and use `AskUserQuestion`:++```+Found N issues confirmed fixed and deployed:++ [Sentry] [title] — fix in [commit], deployed [time ago]+ [Linear] [title] — fix in [commit], deployed [time ago]+ [GitHub] #[N] [title] — referenced in merged PR #[M]++ [Resolve all N] [Review each one] [Skip — don't auto-resolve]+```++If user picks "Review each one", show each issue individually with `[Resolve]` / `[Skip]` via `AskUserQuestion`.++For confirmed issues:++- **Sentry**: use Sentry MCP to resolve the issue+- **Linear**: use `mcp__linear__update_issue` with `state: "Done"`+- **GitHub**: `gh issue close [N] --comment "Auto-closed: fix confirmed deployed"`++Log all resolutions.++---++## Phase 4 — Present triage board++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► TRIAGE — [date]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++AUTO-RESOLVED (already fixed)+ ✓ [Sentry] [title] — fix in [commit]+ ✓ [Linear] [title] — closed+ ✓ [GitHub] #[N] [title] — closed++ACTIVE ISSUES (needs work)+ CRITICAL [source] [title] [age] [assigned?]+ HIGH [source] [title] [age] [assigned?]+ MEDIUM [source] [title] [age] [assigned?]++──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each):++AskUserQuestion call 1:+```+ [Dispatch agent for [top critical issue]]+ [Dispatch agent for [second issue]]+ [Assign issue to sprint (Linear)]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Bulk-assign all HIGH to current sprint]+ [Done]+```++---++## Dispatch fix agent++When dispatching for an issue, spawn an Agent using `agents/triage-agent.md` with:++- Full issue context (error, stack trace, affected code)+- Instruction to create feature branch, fix, and open PR+- Report back on completion or if blocked++Filter to `$ARGUMENTS` project/source if specified.++---++## Native tool usage++### Tasks — triage progress++Use `TaskCreate` for each issue being investigated. Update with `TaskUpdate` as issues are resolved/dispatched/skipped. Gives the user a live triage checklist.++### WebFetch — Sentry/GitHub enrichment++When Sentry MCP hits quota limits, fall back to `WebFetch` with `https://sentry.io/api/0/projects/<org>/<project>/issues/?query=is:unresolved` (using `SENTRY_AUTH_TOKEN` header). Same for GitHub issue details when `gh` is slow.++### WebSearch — error context++Use `WebSearch` to find known solutions for recurring errors (e.g., "AWS RDS connection reset", "ECS task stopped reason"). Include findings in the triage board as context.++### LSP — code navigation for fix agents++When dispatching fix agents, use `LSP` to find symbol definitions, references, and call hierarchies. This helps agents navigate unfamiliar codebases faster than grep.diff --git a/claude-ops/skills/ops-voice/SKILL.md b/claude-ops/skills/ops-voice/SKILL.mdnew file mode 100644index 00000000..d623e1d9--- /dev/null+++ b/claude-ops/skills/ops-voice/SKILL.md@@ -0,0 +1,145 @@+---+name: ops-voice+description: Voice operations — make phone calls (Bland AI), text-to-speech (ElevenLabs), transcribe audio (Whisper/Groq). Replace OpenClaw voice capabilities.+argument-hint: "[call|tts|transcribe|setup]"+allowed-tools:+ - Bash+ - Read+ - Write+ - AskUserQuestion+ - WebFetch+---++# OPS:VOICE — Voice Operations++Voice interface commands. All API calls via curl — no SDK dependencies.++**Credential resolution order:** userConfig → env vars → Doppler secrets++---++## Sub-commands++Parse `$ARGUMENTS` for the command keyword, then execute:++---++### `call [phone] [prompt]` — Bland AI phone call++**Requires:** `bland_ai_api_key` in userConfig or `BLAND_AI_API_KEY` env or Doppler.++```bash+BLAND_KEY="${BLAND_AI_API_KEY:-$(doppler secrets get BLAND_AI_API_KEY --plain 2>/dev/null || true)}"+PHONE="<extracted from $ARGUMENTS>"+PROMPT="<extracted from $ARGUMENTS or ask user>"+MAX_DURATION="${BLAND_MAX_DURATION:-300}" # seconds+VOICE="${BLAND_VOICE:-male}"++# Make the call+RESPONSE=$(curl -s -X POST "https://api.bland.ai/v1/calls" \+ -H "authorization: $BLAND_KEY" \+ -H "Content-Type: application/json" \+ -d "{+ \"phone_number\": \"$PHONE\",+ \"task\": \"$PROMPT\",+ \"voice\": \"$VOICE\",+ \"max_duration\": $MAX_DURATION,+ \"record\": true+ }")++CALL_ID=$(echo "$RESPONSE" | python3 -c "import json,sys; print(json.load(sys.stdin).get('call_id',''))" 2>/dev/null)++# Poll for completion (up to 5 min)+if [ -n "$CALL_ID" ]; then+ echo "Call initiated: $CALL_ID"+ for i in $(seq 1 30); do+ sleep 10+ STATUS=$(curl -s "https://api.bland.ai/v1/calls/$CALL_ID" \+ -H "authorization: $BLAND_KEY" | \+ python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('status',''), d.get('transcripts','')[-1].get('text','') if d.get('transcripts') else '')" 2>/dev/null)+ echo "Status: $STATUS"+ [[ "$STATUS" == completed* ]] && break+ done+fi+```++**Output:** Call ID, live status, transcript when complete.++---++### `tts [text] [--voice voice_id] [--out file.mp3]` — ElevenLabs text-to-speech++**Requires:** `elevenlabs_api_key` in userConfig or `ELEVENLABS_API_KEY` env or Doppler.++```bash+EL_KEY="${ELEVENLABS_API_KEY:-$(doppler secrets get ELEVENLABS_API_KEY --plain 2>/dev/null || true)}"+VOICE_ID="${ELEVENLABS_VOICE_ID:-21m00Tcm4TlvDq8ikWAM}" # Rachel (default)+TEXT="<extracted from $ARGUMENTS>"+OUT_FILE="${OUT_FILE:-/tmp/ops-tts-$(date +%s).mp3}"++# List voices if voice name provided (not an ID)+# Synthesize+curl -s -X POST "https://api.elevenlabs.io/v1/text-to-speech/${VOICE_ID}" \+ -H "xi-api-key: $EL_KEY" \+ -H "Content-Type: application/json" \+ -d "{+ \"text\": \"$TEXT\",+ \"model_id\": \"eleven_monolingual_v1\",+ \"voice_settings\": {\"stability\": 0.5, \"similarity_boost\": 0.75}+ }" \+ --output "$OUT_FILE"++echo "Audio saved to: $OUT_FILE"+# Auto-play on macOS+command -v afplay &>/dev/null && afplay "$OUT_FILE" &+```++**Output:** Audio file path. Auto-plays on macOS via `afplay`.++---++### `transcribe [file_path]` — Groq Whisper transcription++**Requires:** `groq_api_key` in userConfig or `GROQ_API_KEY` env or Doppler.++```bash+GROQ_KEY="${GROQ_API_KEY:-$(doppler secrets get GROQ_API_KEY --plain 2>/dev/null || true)}"+AUDIO_FILE="<extracted from $ARGUMENTS>"++if [ ! -f "$AUDIO_FILE" ]; then+ echo "ERROR: File not found: $AUDIO_FILE"+ exit 1+fi++TRANSCRIPT=$(curl -s -X POST "https://api.groq.com/openai/v1/audio/transcriptions" \+ -H "Authorization: Bearer $GROQ_KEY" \+ -F "file=@$AUDIO_FILE" \+ -F "model=whisper-large-v3" \+ -F "response_format=json" | \+ python3 -c "import json,sys; print(json.load(sys.stdin).get('text',''))" 2>/dev/null)++echo "$TRANSCRIPT"+```++**Output:** Transcript text printed to stdout.++---++### `setup` — Configure voice API keys++Walk through credential setup interactively. Check which keys are missing, then prompt for each:++1. Check `BLAND_AI_API_KEY` → if missing, prompt and add to Doppler or shell profile+2. Check `ELEVENLABS_API_KEY` → if missing, prompt+3. Check `GROQ_API_KEY` → if missing, prompt+4. Verify each key with a lightweight API call (list voices for ElevenLabs, check balance for Bland AI, list models for Groq)+5. Report status for all three services++---++## Execution++1. Resolve the sub-command from `$ARGUMENTS` (first word: call / tts / transcribe / setup)+2. Resolve credentials in order: env → Doppler+3. Execute the matching curl block above+4. If a required key is missing and `setup` was not invoked, suggest `/ops:ops-voice setup`diff --git a/claude-ops/skills/ops-yolo/SKILL.md b/claude-ops/skills/ops-yolo/SKILL.mdnew file mode 100644index 00000000..35e5ee5a--- /dev/null+++ b/claude-ops/skills/ops-yolo/SKILL.md@@ -0,0 +1,293 @@+---+name: ops-yolo+description: YOLO mode. Spawns 4 parallel C-suite agents (CEO, CTO, CFO, COO). Each analyzes the business from their perspective using ALL available data. Produces unfiltered Hard Truths report. After user types YOLO, autonomously runs the business for a day using /loop.+argument-hint: "[YOLO|analyze|report]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+ - AskUserQuestion+ - TeamCreate+ - SendMessage+ - TaskCreate+ - TaskUpdate+ - TaskList+ - EnterPlanMode+ - ExitPlanMode+ - CronCreate+ - CronList+ - CronDelete+ - Monitor+ - WebFetch+ - WebSearch+ - mcp__linear__list_issues+ - mcp__claude_ai_Vercel__list_deployments+ - mcp__claude_ai_Slack__slack_search_public_and_private+ - mcp__claude_ai_Gmail__search_threads+effort: high+model: claude-opus-4-6+maxTurns: 50+---++## Runtime Context++Before YOLO analysis, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read `owner`, `timezone`, `yolo_enabled`, all channel configs+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — all services must be healthy for comprehensive analysis+3. **Secrets**: Resolve ALL keys via env → Doppler → password manager: GITHUB_TOKEN, SENTRY_AUTH_TOKEN, LINEAR_API_KEY, AWS_ACCESS_KEY_ID+4. **Ops memories**: Load ALL files from `${CLAUDE_PLUGIN_DATA_DIR}/memories/` — contact profiles, preferences, topics, donts. YOLO agents need maximum context.+++# OPS ► YOLO MODE++## CLI/API Reference++### aws CLI (Cost Explorer)++| Command | Usage | Output |+|---------|-------|--------|+| `aws ce get-cost-and-usage --time-period Start=<YYYY-MM-DD>,End=<YYYY-MM-DD> --granularity MONTHLY --metrics "UnblendedCost" --output json` | Current month spend | Cost JSON |++### gh CLI (GitHub)++| Command | Usage | Output |+|---------|-------|--------|+| `gh pr list --repo <owner/repo> --json number,title,statusCheckRollup,reviewDecision,mergeable,isDraft` | Open PRs with status | JSON array |+| `gh pr merge <n> --repo <repo> --squash --admin` | Squash merge PR | Merge result |+| `gh run list --limit 20 --json status,conclusion,name,headBranch,createdAt` | Recent CI runs | JSON array |++---++## Agent Teams support++If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** instead of fire-and-forget subagents for the C-suite analysis (Phase 2). This enables:+- Agents can share findings mid-analysis (CEO discovers a revenue blocker → CFO factors it into ROI)+- You can steer agents if early findings change priorities+- Agents coordinate on the consensus recommendation++**Team setup** (only when flag is enabled):+```+TeamCreate("yolo-csuite")+Agent(team_name="yolo-csuite", name="ceo", subagent_type="ops:yolo-ceo", ...)+Agent(team_name="yolo-csuite", name="cto", subagent_type="ops:yolo-cto", ...)+Agent(team_name="yolo-csuite", name="cfo", subagent_type="ops:yolo-cfo", ...)+Agent(team_name="yolo-csuite", name="coo", subagent_type="ops:yolo-coo", ...)+```++After initial analysis, use `SendMessage(to="ceo", content="CTO found critical tech debt in auth service — does this change your strategic recommendation?")` to cross-pollinate findings before synthesizing the Hard Truths report.++If the flag is NOT set, fall back to standard parallel subagents (fire-and-forget, no mid-task steering).++## Phase 1 — Pre-gather ALL data++Run all of these simultaneously:++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-infra 2>/dev/null || echo '{}'+```++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-git 2>/dev/null || echo '[]'+```++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-prs 2>/dev/null || echo '[]'+```++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-ci 2>/dev/null || echo '[]'+```++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-unread 2>/dev/null || echo '{}'+```++```!+aws ce get-cost-and-usage --time-period "Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d)" --granularity MONTHLY --metrics "UnblendedCost" --output json 2>/dev/null || echo '{}'+```++```!+cat "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null || echo '{}'+```++```!+for d in $(jq -r '.projects[] | select(.gsd == true) | .paths[]' "${CLAUDE_PLUGIN_ROOT}/scripts/registry.json" 2>/dev/null); do+ expanded="${d/#\~/$HOME}"+ [ -f "$expanded/.planning/STATE.md" ] && echo "=== $(basename $expanded) ===" && cat "$expanded/.planning/STATE.md" && echo "---"+done+```++---++## Phase 2 — Spawn 4 C-suite agents in parallel++Spawn these 4 agents simultaneously using all pre-gathered data as context. Each writes their analysis to a file in `/tmp/yolo-[session]/`:++### Agent 1 — CEO (Strategic)++Uses `agents/yolo-ceo.md`. Writes `/tmp/yolo-[session]/ceo-analysis.md`.++- What's the #1 thing blocking growth right now?+- Are we building the right things?+- Where are we wasting time vs. creating value?+- What would you tell an investor today, unfiltered?++### Agent 2 — CTO (Technical)++Uses `agents/yolo-cto.md`. Writes `/tmp/yolo-[session]/cto-analysis.md`.++- What's the worst technical debt that will bite us?+- Which services are time-bombs?+- Is the team/architecture set up to scale?+- What corners were cut that need fixing now?++### Agent 3 — CFO (Financial)++Uses `agents/yolo-cfo.md`. Writes `/tmp/yolo-[session]/cfo-analysis.md`.++- Actual burn rate vs. runway+- Which AWS services are waste?+- When do we hit zero if nothing changes?+- What's the ROI on current work?++### Agent 4 — COO (Operations)++Uses `agents/yolo-coo.md`. Writes `/tmp/yolo-[session]/coo-analysis.md`.++- What's falling through the cracks right now?+- Which processes are broken?+- What's the top execution risk this week?+- What should be automated that isn't?++---++## Phase 3 — Hard Truths Report++After all 4 agents complete, synthesize into a unified report:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ YOLO ► HARD TRUTHS REPORT — [date]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++ CEO: [1-2 brutal strategic truths]++ CTO: [1-2 brutal technical truths]++ CFO: [1-2 brutal financial truths]++ COO: [1-2 brutal operational truths]++──────────────────────────────────────────────────────+ CONSENSUS: The #1 thing that matters today is:+ [single most important action, no sugar-coating]+──────────────────────────────────────────────────────++ Full analysis files saved to:+ /tmp/yolo-[session]/ceo-analysis.md+ /tmp/yolo-[session]/cto-analysis.md+ /tmp/yolo-[session]/cfo-analysis.md+ /tmp/yolo-[session]/coo-analysis.md++──────────────────────────────────────────────────────+ Type YOLO to hand over the controls.+ I'll run your business autonomously for the next day.+ This means: closing inbox, merging ready PRs,+ fixing fires, advancing GSD phases, triaging issues.++ Or pick an analysis to read:+──────────────────────────────────────────────────────+```++Use **batched AskUserQuestion calls** (max 4 options each):++AskUserQuestion call 1:+```+ [Read CEO analysis]+ [Read CTO analysis]+ [Read CFO analysis]+ [More...]+```++AskUserQuestion call 2 (only if "More..."):+```+ [Read COO analysis]+ [Execute top recommendation now]+ [Type YOLO to go autonomous]+```++---++## Phase 4 — YOLO Autonomous Mode++If user types `YOLO` (all caps), enter autonomous mode via `/loop`.++**Before starting**, use `AskUserQuestion` to confirm scope:++```+YOLO mode will autonomously execute these steps:+ 1. Inbox — reply to humans, archive automated+ 2. Fires — fix CRITICAL/HIGH production issues+ 3. PRs — merge ready PRs (CI green, approved)+ 4. Triage — auto-resolve confirmed-fixed issues+ 5. GSD — advance highest-priority phase+ 6. Linear — sync sprint board+ 7. Deploy — trigger pending deploys+ 8. Report — summary++ [Run all 8 steps] [Pick which steps to run] [Cancel]+```++If user picks "Pick which steps", show steps as `multiSelect` via **batched AskUserQuestion calls** (max 4 options each):++Call 1: `[Inbox]`, `[Fires]`, `[PRs]`, `[More steps...]`+Call 2 (if "More steps..."): `[Triage]`, `[GSD]`, `[Linear]`, `[More steps...]`+Call 3 (if "More steps..."): `[Deploy]`, `[Report]`, `[Done selecting]`++Run the selected steps in sequence, reporting after each step.++**Per-step confirmations** (use `AskUserQuestion` before each destructive action):++- **Inbox**: Show drafted replies and ask `[Send all N replies]` / `[Review each one]` / `[Skip inbox]` before sending any messages+- **Fires**: Show proposed fix and ask `[Dispatch fix agent]` / `[Skip]` before each agent dispatch+- **PRs**: Show PR list and ask `[Merge all N ready PRs]` / `[Pick which ones]` / `[Skip]` before merging+- **Triage**: Show issues to close and ask `[Auto-resolve all N confirmed-fixed]` / `[Review each]` / `[Skip]` before closing+- **Deploy**: Show pending deploys and ask `[Deploy all]` / `[Pick which]` / `[Skip]` before triggering++After each step, check if new fires have appeared before proceeding.+Report final summary when done.++If `$ARGUMENTS` is `analyze` or empty, go straight to Phase 1.+If `$ARGUMENTS` is `YOLO`, skip to Phase 4.+If `$ARGUMENTS` is `report`, skip to Phase 3 (reads existing analysis files if present).++---++## Native tool usage++### Tasks — progress tracking++Use `TaskCreate` at the start of Phase 4 to create a task for each YOLO step. Update with `TaskUpdate` as each completes. This gives the user a live progress view across the autonomous run.++### PlanMode — review before autonomous++Before Phase 4 execution, use `EnterPlanMode` to present the full execution plan. The user reviews what YOLO will do, approves or modifies, then `ExitPlanMode` to begin execution.++### Cron — schedule daily YOLO++After Phase 4 completes, offer to schedule recurring YOLO via `AskUserQuestion`:+```+ [Schedule daily YOLO at 9am] [Schedule weekly Monday briefing] [No schedule]+```+Use `CronCreate` if selected. Use `CronList`/`CronDelete` to manage existing schedules.++### Monitor — live CI/deploy watching++When YOLO dispatches fix agents or triggers deploys, use `Monitor` to stream CI output in real-time instead of polling with sleep loops.++### WebFetch/WebSearch — enrichment++Use `WebFetch` to pull Grafana dashboards, Sentry event details, or AWS status pages when MCPs are unavailable. Use `WebSearch` to find context on production errors (e.g., known AWS outages).diff --git a/claude-ops/skills/ops/SKILL.md b/claude-ops/skills/ops/SKILL.mdnew file mode 100644index 00000000..c683c1df--- /dev/null+++ b/claude-ops/skills/ops/SKILL.md@@ -0,0 +1,54 @@+---+name: ops+description: Business operations command center. Routes to the right ops command based on what you need — briefing, inbox, fires, projects, comms, triage, linear, revenue, deploy, or yolo mode.+argument-hint: "[command] [args]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - Agent+effort: medium+maxTurns: 20+---++## Runtime Context++Before routing, load:+1. **Preferences**: `cat ${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` — read configured channels to determine available commands+2. **Daemon health**: `cat ${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` — if `action_needed`, surface before routing+++# OPS — Business Command Center++Route `$ARGUMENTS` to the correct ops skill:++| Input | Route to |+| --------------------------------------------- | ----------------------- |+| (empty), dash, home, hq | `/ops:ops-dash` |+| go, morning, briefing | `/ops-go` |+| setup, configure, init, install | `/ops:setup $ARGUMENTS` |+| inbox, unread, messages | `/ops-inbox` |+| comms, send, whatsapp, email, slack, telegram | `/ops-comms $ARGUMENTS` |+| fires, incidents, down, sentry | `/ops-fires` |+| projects, dashboard, status | `/ops-projects` |+| next, priority, what | `/ops-next` |+| triage, issues | `/ops-triage` |+| linear, sprint, board | `/ops-linear` |+| revenue, money, mrr, costs | `/ops-revenue` |+| deploy, ship | `/ops-deploy` |+| merge, prs, ship-prs | `/ops-merge $ARGUMENTS` |+| marketing, email, klaviyo, ads, meta, seo, campaigns | `/ops:ops-marketing $ARGUMENTS` |+| ecom, shop, shopify, store, orders, inventory | `/ops:ops-ecom $ARGUMENTS` |+| voice, call, tts, transcribe, phone | `/ops:ops-voice $ARGUMENTS` |+| yolo | `/ops-yolo` |+| doctor, health, fix, diagnose | `/ops:ops-doctor` |+| speedup, clean, optimize, cleanup | `/ops:ops-speedup` |+| orchestrate, subagents, agents, dispatch, run | `/ops:ops-orchestrate $ARGUMENTS` |++If `$ARGUMENTS` is empty, launch the interactive dashboard: invoke `/ops:ops-dash` directly.++## CLI/API Reference++This skill is a router only — it does not call CLI tools directly. All tool usage is delegated to the target skill after routing. See the referenced skill's `## CLI/API Reference` section for details.diff --git a/claude-ops/skills/setup/SKILL.md b/claude-ops/skills/setup/SKILL.mdnew file mode 100644index 00000000..95e89225--- /dev/null+++ b/claude-ops/skills/setup/SKILL.md@@ -0,0 +1,1983 @@+---+name: setup+description: Interactive setup wizard for the claude-ops plugin. Installs missing CLIs, configures env vars for each channel (Telegram, WhatsApp, Email, Slack, Linear, Sentry, Vercel), builds the project registry, and saves user preferences. Run once after installing the plugin or any time to reconfigure.+argument-hint: "[section]"+allowed-tools:+ - Bash+ - Read+ - Write+ - Edit+ - AskUserQuestion+effort: high+maxTurns: 80+---++# OPS ► SETUP WIZARD++You are running an **interactive configuration wizard** for the `claude-ops` plugin. The user wants you to walk them through every step needed to get the plugin working: installing CLIs, setting env vars, configuring channels, populating the project registry, and saving preferences.++**Hard rules:**++- This is a _conversation_, not a script dump. Use `AskUserQuestion` for every decision — never ask in prose when a structured selector will do.+- Never install anything or write any file without explicit user confirmation via `AskUserQuestion`.+- Skip sections the user declines. Don't nag.+- Show what's already configured first, so the user only fills gaps.+- **Never show the user's real name or email in output unless the user explicitly provided it in THIS session.** Do not read from memory, existing configs, or environment variables to populate display names.+- **Max 4 options per `AskUserQuestion` call.** The tool schema enforces `<=4` items in the `options` array. When a step lists >4 choices, filter already-configured items first, then batch the rest into multiple sequential calls of <=4 options each, grouped logically. Use `[More options...]` as the last option to bridge between batches.+- Run ALL diagnostic/probe commands in parallel when possible. Use multiple Bash tool calls in a single message. Never run sequential probes when they're independent (e.g., `gog auth status` AND `wacli doctor` AND keychain scouts should all run simultaneously).+- Background any command that might take >2 seconds (sync, backfill, npm install, brew install).+- All writes go to one of these paths — and nothing else:+ - **`$PREFS_PATH`** — per-user preferences + secrets. Resolves to `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`. Lives in Claude Code's plugin data dir so it survives plugin reinstalls and version bumps. Never committed to git.+ - **`${CLAUDE_PLUGIN_ROOT}/scripts/registry.json`** — per-user project registry (gitignored in the source repo). `mkdir -p` its parent if missing.+ - **`${CLAUDE_PLUGIN_ROOT}/.mcp.json`** — only to add `${user_config.*}` placeholders, never hardcoded tokens.+ - The user's shell profile (`~/.zshrc` etc.) — append-only, never rewrite.+- At the top of every wizard step, make sure `$PREFS_PATH`'s parent directory exists: `mkdir -p "$(dirname "$PREFS_PATH")"`. Claude Code creates `~/.claude/plugins/data/ops-ops-marketplace/` on plugin install but don't assume.++---++## Step 0 — Preflight (runs in background while you read)++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-setup-preflight &>/dev/null &+```++**Preflight data**: All probe results are cached at `/tmp/ops-preflight/`. Before running ANY diagnostic command, check if the result already exists there:+- CLI status: `cat /tmp/ops-preflight/clis.txt`+- Slack: `cat /tmp/ops-preflight/slack.json`+- Telegram: `cat /tmp/ops-preflight/telegram.txt`+- gog/Gmail: `cat /tmp/ops-preflight/gog-gmail.json`+- gog/Calendar: `cat /tmp/ops-preflight/gog-cal.json`+- WhatsApp: `cat /tmp/ops-preflight/wacli-doctor.json` and `wacli-chats.json`+- MCP servers: `cat /tmp/ops-preflight/mcp-servers.txt`+- GitHub: `cat /tmp/ops-preflight/gh-auth.txt`+- AWS: `cat /tmp/ops-preflight/aws-identity.json`+- Projects: `cat /tmp/ops-preflight/projects.txt`+- Existing registry: `cat /tmp/ops-preflight/existing-registry.json`+- Existing prefs: `cat /tmp/ops-preflight/existing-prefs.json`+- Doppler: `cat /tmp/ops-preflight/doppler.json`++Wait for `/tmp/ops-preflight/.complete` to exist before reading (it should be ready within 2-3 seconds). NEVER re-run a probe that already has cached results — read the cache file instead.++---++## Step 0b — Detect current state++Run the detector and parse its JSON output (or read from preflight cache if available):++```!+${CLAUDE_PLUGIN_ROOT}/bin/ops-setup-detect 2>/dev/null+```++If `CLAUDE_PLUGIN_ROOT` is unset, fall back to the latest installed cache dir at `~/.claude/plugins/cache/ops-marketplace/ops/<latest-version>/`. Store the resolved path as `PLUGIN_ROOT` for the rest of the session.++Also resolve `PREFS_PATH` once and reuse it everywhere:++```bash+PREFS_PATH="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"+mkdir -p "$(dirname "$PREFS_PATH")"+```++Print a compact status header to the user, one line per category:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► SETUP WIZARD+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ Shell: zsh → ~/.zshrc+ Core CLIs: ✓ jq ✓ git ✓ gh ✓ aws ✓ node+ Channels: ✓ wacli ✓ gog ○ telegram (no token)+ Secrets: ✓ doppler (project: my-app, config: dev)+ MCPs: ✓ linear ✓ sentry ○ slack ○ vercel+ Registry: 19 projects+ Preferences: not set+──────────────────────────────────────────────────────+```++Use `✓` for present/set, `○` for missing/unset, `✗` for broken.++---++## Step 1 — Ask which sections to configure++Use `AskUserQuestion` with `multiSelect: true`. Offer **only sections that need attention** (skip ones already green). Because AskUserQuestion allows max 4 options, batch into logical groups:++**Batch 1 — Core setup:**++| Option | Header | Description |+| ------------------ | -------- | ------------------------------------------------------------- |+| Install CLIs | cli | Install missing command-line tools via Homebrew |+| Configure MCPs | mcp | Enable Linear, Sentry, Vercel, Gmail MCP servers |+| Build registry | registry | Register projects Claude should manage |+| Shell env | env | Export `CLAUDE_PLUGIN_ROOT` in shell profile |++**Batch 2 — Channels & plugins:**++| Option | Header | Description |+| ------------------ | -------- | ------------------------------------------------------------- |+| Configure channels | channels | Set tokens for Telegram, WhatsApp, Email, Slack |+| Companion plugins | plugins | Install GSD for project roadmap tracking |+| Save preferences | prefs | Owner name, timezone, default priorities |+| Background daemon | daemon | Install ops-daemon for persistent wacli-sync + memory extract |++**Batch 3 — Extras (only show if not already configured):**++| Option | Header | Description |+| ------------------- | -------- | ------------------------------------------------------------- |+| Configure ecommerce | ecom | Set Shopify store URL + admin token, ShipBob |+| Configure marketing | mktg | Set Klaviyo, Meta Ads, GA4, Search Console keys |+| Configure voice | voice | Set Bland AI, ElevenLabs, Groq API keys |++Present each batch as a separate `AskUserQuestion` call. Skip batches where all items are already green. Collect all selections across batches and run each selected section in order.++---++## Step 2 — Install CLIs (if selected)++For each missing tool in the detector output, ask with `AskUserQuestion` one question per tool (or a single multiSelect listing all missing ones):++```+Install jq? [Yes, install now] [Skip]+Install gh? [Yes, install now] [Skip]+Install wacli? [Yes, install now] [Skip — manual install required]+```++For each `Yes`, run:++```bash+${PLUGIN_ROOT}/bin/ops-setup-install <tool>+```++Report success/failure. If Homebrew is missing on macOS, stop and tell the user to install it from https://brew.sh first — do not attempt to install brew automatically.++After installation, re-run `ops-setup-detect` to refresh status before continuing.++---++## Step 2b — Companion plugins (if selected)++### GSD (Get Shit Done)++GSD is a third-party Claude Code plugin that adds project roadmap tracking. When installed, claude-ops dashboards (`/ops:go`, `/ops:projects`, `/ops:next`, `/ops:yolo`) automatically show active phases, progress, and next actions per project. Without it, those sections are simply omitted.++Check if GSD is already installed:++```bash+ls ~/.claude/plugins/cache/*/gsd*/skills/gsd-progress/SKILL.md 2>/dev/null && echo "installed" || echo "not_installed"+```++If not installed, ask via `AskUserQuestion`:++```+GSD adds project roadmap tracking to your ops dashboards.+ /ops:go shows active phases and progress per project+ /ops:projects shows GSD state alongside CI/PR status+ /ops:next factors in GSD work priority++ [Install GSD (latest)] [Skip — I don't need roadmap tracking]+```++On install, run the commands directly — do NOT tell the user to run them manually:++```bash+# Install GSD in one shot — no user intervention needed+claude plugin marketplace add Lifecycle-Innovations-Limited/get-shit-done 2>/dev/null && \+claude plugin install gsd@Lifecycle-Innovations-Limited-get-shit-done 2>/dev/null+```++If `claude` CLI is not available in the path, fall back to the plugin cache mechanism:++```bash+# Direct marketplace clone fallback+GSD_MARKETPLACE_DIR="$HOME/.claude/plugins/marketplaces/Lifecycle-Innovations-Limited-get-shit-done"+if [ ! -d "$GSD_MARKETPLACE_DIR" ]; then+ git clone https://github.com/Lifecycle-Innovations-Limited/get-shit-done.git "$GSD_MARKETPLACE_DIR" 2>/dev/null+fi+```++Report success/failure. Record `plugins.gsd = "installed"` in `$PREFS_PATH`.++If they skip:++```+Skipped GSD. Install later with: /plugin marketplace add Lifecycle-Innovations-Limited/get-shit-done+```++---++## Step 3 — Configure channels (if selected)++Ask which channels the user wants to configure using `AskUserQuestion` with `multiSelect: true`. Because AskUserQuestion allows max 4 options, batch into two groups. Skip channels already configured (show only those needing attention).++**Batch 1 — Messaging:**++| Option | Header | Description |+| -------- | -------- | ----------------------------------------------------------------------- |+| Telegram | telegram | Bot token + owner ID for `/ops-comms telegram` |+| WhatsApp | whatsapp | wacli doctor + auto-heal + backfill |+| Email | email | gog CLI → Gmail MCP fallback for `/ops-inbox email` |+| Slack | slack | Slack MCP server (managed by Claude Code) |++**Batch 2 — Services:**++| Option | Header | Description |+| -------- | -------- | ----------------------------------------------------------------------- |+| Calendar | calendar | gog cal → Google Calendar MCP fallback — schedule context for briefings |+| Doppler | doppler | Secrets manager — set default project + config for all ops skills |+| Vault | vault | Password manager — 1Password, Dashlane, Bitwarden, or macOS Keychain |++Present each batch as a separate `AskUserQuestion` call. Skip batches where all items are already configured. For each selected channel, run the matching sub-flow below.++---++#### Shared: prefer OAuth over manual tokens++Whenever a channel has a **browser-based OAuth flow** available, offer that first and put manual-token entry behind it as a fallback. OAuth is safer (scoped, revocable, no secrets in dotfiles), and usually faster for the user.++| Channel | OAuth path | Manual fallback |+| -------------- | ---------------------------------------------------------- | -------------------------------------- |+| Email (gog) | `gog auth login` (browser) | n/a — gog is OAuth-only |+| Calendar (gog) | same `gog auth login` with `--scopes=calendar` | n/a |+| Slack | `claude mcp add slack` (handles OAuth through Claude Code) | bot token via auto-scan + manual paste |+| Linear | `claude mcp add linear` | API key |+| Sentry | `claude mcp add sentry` | DSN / auth token |+| Vercel | `claude mcp add vercel` | personal access token |+| Telegram | ❌ no OAuth (Bot API is token-only by design) | auto-scan + manual paste (only option) |+| WhatsApp | QR pairing via `wacli auth` (similar UX to OAuth) | n/a — paired sessions only |++When a channel supports OAuth, the default `AskUserQuestion` should lead with it:++```+[Connect via OAuth (recommended)] [Enter a token manually] [Skip]+```++Only go into the credential auto-scan flow below when the user picks "manually" or when the channel (Telegram, local tools) has no OAuth path.++---++---++## Universal Credential Auto-Scan++**BEFORE asking the user for ANY credential**, run this scan sequence. This applies to ALL steps — channels, ecommerce, marketing, voice, and MCPs. The user should never be asked to find a key that's already on their system.++For each variable name (e.g. `TELEGRAM_BOT_TOKEN`, `SHOPIFY_ACCESS_TOKEN`, `KLAVIYO_API_KEY`):++1. **Current shell environment** — `printenv <VAR>`. Running shell inherits exports, Doppler injections, dotenv-loaded files. Most likely to be correct.+2. **Shell profile files** — grep `~/.zshrc`, `~/.bashrc`, `~/.zprofile`, `~/.config/fish/config.fish`, `~/.envrc` (direnv) for `<VAR>=` or `export <VAR>=`. Show the file path next to the value so the user knows where it's from.+3. **Doppler (all projects)** — if `command -v doppler` succeeds:+ ```bash+ for proj in $(doppler projects --json 2>/dev/null | jq -r '.[].slug'); do+ doppler secrets --project "$proj" --config prd --json 2>/dev/null | \+ jq -r --arg var "$VAR" --arg proj "$proj" \+ 'to_entries[] | select(.key == $var) | "\(.value.computed) (doppler:\($proj)/prd)"'+ done+ ```+ Also try the default project config (dev/staging) if prd fails. Show source attribution `(project: <slug>, config: <config>)`.+4. **Dashlane CLI** — if `command -v dcli` succeeds:+ ```bash+ dcli password "$SERVICE_KEYWORD" --output json 2>/dev/null+ ```+ Map service keywords: `shopify` → SHOPIFY vars, `klaviyo` → KLAVIYO vars, `bland` / `bland-ai` → BLAND vars, etc.+5. **macOS Keychain** — for specific services:+ ```bash+ security find-generic-password -s "$SERVICE" -w 2>/dev/null+ ```+ Use service names matching common patterns (e.g. `shopify-admin-token`, `klaviyo-api-key`, `bland-ai-api-key`).+6. **OpenClaw config** — if `~/.openclaw/openclaw.json` exists:+ ```bash+ jq -r --arg var "$VAR" '.agents.defaults.env[$var] // empty' ~/.openclaw/openclaw.json 2>/dev/null+ ```+7. **Installed MCP configs** — read each `.mcp.json` the detector found. For each server entry, look at `.env` and `.args` for the variable name or for literal values that look like the target. Show the MCP server name as the source.+8. **Plugin preferences** — check existing `$PREFS_PATH` for the key under the relevant section (e.g. `.ecom.shopify.admin_token`, `.marketing.klaviyo.api_key`). If found and not a `doppler:` reference, show it as a source.++**Env var → service keyword mapping for auto-scan:**++| Variable names | Service keyword (Dashlane/Keychain) |+| --- | --- |+| `SHOPIFY_ACCESS_TOKEN`, `SHOPIFY_ADMIN_TOKEN`, `SHOPIFY_STORE_URL` | `shopify` |+| `KLAVIYO_API_KEY`, `KLAVIYO_PRIVATE_KEY` | `klaviyo` |+| `META_ACCESS_TOKEN`, `FACEBOOK_ACCESS_TOKEN`, `META_AD_ACCOUNT_ID` | `meta`, `facebook` |+| `GA4_PROPERTY_ID`, `GA_MEASUREMENT_ID` | `google-analytics`, `ga4` |+| `BLAND_AI_API_KEY`, `BLAND_API_KEY` | `bland-ai`, `bland` |+| `ELEVENLABS_API_KEY` | `elevenlabs` |+| `GROQ_API_KEY` | `groq` |+| `SHIPBOB_ACCESS_TOKEN` | `shipbob` |+| `TELEGRAM_BOT_TOKEN`, `TELEGRAM_API_ID`, `TELEGRAM_API_HASH` | `telegram` |+| `SLACK_BOT_TOKEN`, `SLACK_MCP_XOXC_TOKEN` | `slack` |++**Present the findings** with `AskUserQuestion` (**max 4 options per call**):++```+Found credential for SHOPIFY_ACCESS_TOKEN:+ [A] shell env + ~/.zshrc + Dashlane — shpat_508b...682e (matched across 3 sources)+ [B] Doppler (project: mystore, config: prd) — shpat_9f2c...a17b (different!)+ [C] Enter a different one+```++Rules for the prompt:++- Show the **first 8 and last 4 characters** of any token, never the full value.+- **Always collapse matching sources** into one option with `(matched in env + ~/.zshrc + Dashlane)` appended. This is critical to stay within the 4-option limit.+- If sources **disagree**, show each distinct value as a separate option. If there are more than 3 distinct values (rare), batch into multiple calls with `[More sources...]`.+- Placeholder values like `${user_config.*}`, `<your-token>`, `CHANGE_ME`, or empty strings count as NOT FOUND.+- Always include an `[Enter a different one]` option as the last option.+- If NO source has a value, then and only then ask the user to provide it — show instructions for where to find it in the service's dashboard.++**On selection**, use the chosen value as the source of truth and — with the user's consent — optionally propagate it back to the other sources (e.g. "Also update ~/.zshrc and Doppler to match?"). Default to NO for propagation unless the user opts in.++---++#### Shared: credential auto-scan++**This section applies specifically to channel tokens (Telegram, Slack).** For all other steps, see the [Universal Credential Auto-Scan](#universal-credential-auto-scan) section above — the same pattern applies everywhere.++**Before prompting the user to paste any token**, scan for it using the Universal Credential Auto-Scan sequence above. Show the user what was found and ask them to confirm or override. Never silently use a token without confirmation.++---++### 3a — Telegram (user-auth via ops-telegram-autolink)++**Always ask before starting the Telegram flow** — even when the user selected "all channels". Use `AskUserQuestion`:++```+Set up Telegram personal account access?+ [Yes — enter my phone number and authenticate]+ [Skip Telegram]+```++If the user skips, record `channels.telegram = "skipped"` in `$PREFS_PATH` and move on. Do NOT silently mark Telegram as unconfigured — the explicit skip prevents the status header from showing `○ telegram (no token)` as an action item on subsequent runs.++**Bots cannot read user DMs**, so `/ops-inbox telegram` requires a personal-account MCP. The plugin ships `bin/ops-telegram-autolink.mjs` which:++1. Scans scout sources (keychain → ~/.claude.json → shell profiles → Doppler) for previously-extracted `TELEGRAM_API_ID` / `TELEGRAM_API_HASH` / `TELEGRAM_SESSION`.+2. If none found, makes plain HTTP requests to `my.telegram.org` (no browser — `my.telegram.org` uses server-side HTML, no JS required), logs in with a phone code from the bridge file, creates an app if needed, and extracts api_id + api_hash.+3. Runs gram.js `client.start()` to generate a session string, bridging the second code via the same file.+4. Emits final JSON on stdout: `{api_id, api_hash, phone, session}`.++Sub-flow (only runs if user selected Yes above):++1. **Scout first.** Check keychain for previously-extracted Telegram credentials:++ ```bash+ for svc in telegram-api-id telegram-api-hash telegram-phone telegram-session; do+ security find-generic-password -s "$svc" -w 2>/dev/null && echo "FOUND: $svc"+ done+ ```++ Also check `~/.claude.json mcpServers.telegram.env.TELEGRAM_API_ID`. If all 4 are found and the stored `TELEGRAM_SESSION` decodes as a StringSession, tell the user `"✓ Telegram already configured (api_id=XXXXXXX, phone=+XX...)"` and skip to step 8.++2. **Ask the user for their phone number** via `AskUserQuestion` (free-text). Validate it matches `^\+\d{7,15}$`. Explain that the phone is only used once during the first-run extraction and is stored locally only.++3. **Warn about 2 codes.** Inform the user via `AskUserQuestion`: `"Telegram will send TWO codes to your Telegram app — one for my.telegram.org web login, then a second one for gram.js auth. Have your Telegram app ready."` Options: `[I'm ready]`, `[Cancel]`.++4. **Spawn the autolink script in the background with restrictive file perms:**++ ```bash+ (umask 077 && node "${CLAUDE_PLUGIN_ROOT}/bin/ops-telegram-autolink.mjs" --phone "$PHONE" 2>/tmp/ops-telegram-autolink.log 1>/tmp/ops-telegram-autolink.out &)+ echo $! > /tmp/ops-telegram-autolink.pid+ ```++ Use the Bash tool's `run_in_background: true`. The `umask 077` creates all bridge files (log, out) with mode 0600. The .out file contains the full credential JSON including the gram.js session string — if it's world-readable, any local process can exfiltrate long-lived Telegram account access.++5. **Poll the stderr log for `need_code` events.** Every 3 seconds, read `/tmp/ops-telegram-autolink.log` and look for the most recent `{"type":"need_code", ...}` line that hasn't been answered yet. When you see one:+ - Determine which code: `channel: "web_login"` (first) or `channel: "gram_auth"` (second).+ - Use `AskUserQuestion` with a free-text input: `"Enter the code Telegram just sent to your Telegram app (digits only):"`.+ - Write the digits to `/tmp/telegram-code.txt` with restrictive perms: `Bash: (umask 077 && printf '%s' "$CODE" > /tmp/telegram-code.txt)`. The `umask 077` is critical — without it the file is created world-readable on macOS (where `/tmp` is `drwxrwxrwt`) and any local process can race to read the code during the 2s poll window.+ - Wait for the next event.+ - If you see `{"type":"need_password"}`, handle 2FA: ask the user via `AskUserQuestion` and write to `/tmp/telegram-password.txt` with `(umask 077 && printf '%s' "$PW" > /tmp/telegram-password.txt)`. Same perm hardening as the code file. The 2FA password is far more sensitive than a one-time code.++6. **Wait for the script to exit.** Poll until the process is no longer running (`ps -p "$(cat /tmp/ops-telegram-autolink.pid)"`). Read `/tmp/ops-telegram-autolink.out` — it should contain a single JSON line with `api_id`, `api_hash`, `phone`, and `session`. **Security note**: the setup skill should have dispatched the autolink with `(umask 077 && node "${CLAUDE_PLUGIN_ROOT}/bin/ops-telegram-autolink.mjs" --phone "$PHONE" 2>/tmp/ops-telegram-autolink.log 1>/tmp/ops-telegram-autolink.out &)` so the .log and .out files get 0600 mode. Verify with `stat -f '%Lp' /tmp/ops-telegram-autolink.out` → must print `600`. Immediately `shred -u` (Linux) or `rm -P` (macOS) the .out file after reading the credentials into memory.++7. **Persist to keychain + preferences.** macOS only:++ ```bash+ security add-generic-password -U -s telegram-api-id -a "$USER" -w "$API_ID"+ security add-generic-password -U -s telegram-api-hash -a "$USER" -w "$API_HASH"+ security add-generic-password -U -s telegram-phone -a "$USER" -w "$PHONE"+ security add-generic-password -U -s telegram-session -a "$USER" -w "$SESSION"+ ```++ Then update `$PREFS_PATH` with `channels.telegram = {backend: "gram.js", api_id: "...", phone: "...", status: "configured"}`. **Never write the api_hash or session to preferences.json** — those stay in keychain only. preferences.json gets only the non-sensitive metadata.++8. **Auto-configure the MCP server.** Write the credentials directly into the plugin's user config so the user doesn't have to manually paste anything:++ ```bash+ # Read existing user config or create empty+ USER_CONFIG="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/user-config.json"+ mkdir -p "$(dirname "$USER_CONFIG")"++ # Write Telegram credentials to user config+ jq -n \+ --arg api_id "$API_ID" \+ --arg api_hash "$API_HASH" \+ --arg phone "$PHONE" \+ --arg session "$SESSION" \+ '{telegram_api_id: $api_id, telegram_api_hash: $api_hash, telegram_phone: $phone, telegram_session: $session}' \+ > "${USER_CONFIG}.tmp"++ # Merge with existing config if present+ if [ -f "$USER_CONFIG" ]; then+ jq -s '.[0] * .[1]' "$USER_CONFIG" "${USER_CONFIG}.tmp" > "${USER_CONFIG}.new" && mv "${USER_CONFIG}.new" "$USER_CONFIG"+ rm -f "${USER_CONFIG}.tmp"+ else+ mv "${USER_CONFIG}.tmp" "$USER_CONFIG"+ fi+ chmod 600 "$USER_CONFIG"+ ```++ Also update `~/.claude.json` MCP server config if the telegram server entry exists — inject the credentials as env vars:++ ```bash+ # Update .claude.json mcpServers.telegram.env with actual values+ CLAUDE_JSON="$HOME/.claude.json"+ if [ -f "$CLAUDE_JSON" ] && jq -e '.mcpServers.telegram' "$CLAUDE_JSON" >/dev/null 2>&1; then+ jq --arg id "$API_ID" --arg hash "$API_HASH" --arg phone "$PHONE" --arg session "$SESSION" \+ '.mcpServers.telegram.env.TELEGRAM_API_ID = $id | .mcpServers.telegram.env.TELEGRAM_API_HASH = $hash | .mcpServers.telegram.env.TELEGRAM_PHONE = $phone | .mcpServers.telegram.env.TELEGRAM_SESSION = $session' \+ "$CLAUDE_JSON" > "${CLAUDE_JSON}.tmp" && mv "${CLAUDE_JSON}.tmp" "$CLAUDE_JSON"+ fi+ ```++ Print:+ ```+ ✓ Telegram configured automatically.+ API ID: [api_id]+ Phone: [phone]+ Session: stored in keychain + MCP config+ Restart Claude Code to activate the Telegram MCP server.+ ```++9. **Smoke test (optional).** Spawn `node ${CLAUDE_PLUGIN_ROOT}/telegram-server/index.js` with the env vars set inline for 3 seconds. If it doesn't print an auth error, the session works.++**Privacy notes for the user** (show once at start):++- The phone number and all credentials stay on your machine. The wizard never transmits them anywhere except to Telegram's own servers during the HTTP login flow.+- If you already have a gram.js / Telethon session for another project, you can skip this and paste those values manually into `/plugin settings`.+- If Telegram replies "Sorry, too many tries. Please try again later." your account is rate-limited for ~8 hours — the wizard cannot bypass this. Wait and retry.++### 3b — WhatsApp (doctor + self-heal + backfill)++WhatsApp is the channel that most often breaks silently. The wizard must **auto-diagnose, doctor, and fix** — not just report status and give up. Run this whole sub-flow top-to-bottom, stopping only when the system is healthy or the user declines a remediation.++#### Step 3b.1 — Presence++Run `command -v wacli`. If missing, ask `AskUserQuestion`: `[Show install docs]`, `[Skip WhatsApp]`. On install docs, print:++```+wacli is not on Homebrew. Install:+ git clone https://github.com/Lifecycle-Innovations-Limited/wacli ~/src/wacli+ cd ~/src/wacli && go build -o /usr/local/bin/wacli ./cmd/wacli+```++and stop this sub-flow.++#### Step 3b.2 — Collect state++Run these in parallel:++```bash+wacli doctor --json 2>&1+wacli auth status --json 2>&1+wacli messages list --after="$(date -v-1d +%Y-%m-%d 2>/dev/null || date -d '1 day ago' +%Y-%m-%d)" --limit=5 --json 2>&1+wacli chats list --json 2>&1 | head -c 4000+```++Parse:++- `doctor.data.authenticated` (bool)+- `doctor.data.lock_held` + `doctor.data.lock_info` (PID + acquired_at timestamp)+- `doctor.data.fts_enabled` (bool — if false, search is degraded, not fatal)+- `messages.data.messages` length → **this is the key health signal**. Authed with zero messages in the last 24h = broken.+- `chats` count and whether it populated at all++#### Step 3b.3 — Diagnose and classify++Apply these rules in order. Stop at the first match.++**A. Not authenticated**+If `doctor.authenticated: false` → print "WhatsApp needs QR pairing. Run `wacli auth` in a separate terminal and scan the QR code with your phone (WhatsApp → Linked Devices → Link a device), then re-run /ops:setup whatsapp." End of sub-flow. Do **not** try to automate the QR scan — it requires the user's phone camera pointed at the terminal (exception to Rule 2).++**B. Stuck sync (stale lock)**+If `lock_held: true` AND the `lock_info.acquired_at` is older than 2 minutes AND the lock-holder PID is still alive (`ps -p <pid>`):++1. Run `wacli sync` in the background (`timeout 15 wacli sync 2>&1`) via the existing process's stderr tail — OR if we can't tee into it, fall back to:+2. Ask `AskUserQuestion`: `"A wacli sync process (pid=N) has been holding the store lock for Xm. Most likely stuck. Kill it?"` → `[Kill pid N and restart sync]`, `[Leave it running]`.+3. On kill: `kill <pid>` (not -9 first). Wait 3s. If still alive, `kill -9 <pid>`. Verify with `ps -p <pid>`.+4. After kill, re-run `wacli doctor --json` to confirm lock is released. Continue to the next rule.++**C. App-state key desync (the big one)**+Run `timeout 15 wacli sync 2>&1 | tee /tmp/wacli-sync-probe.log` (must be done after B so the lock is free). Grep the output for:++- `didn't find app state key` → **session keys are desynced**, needs re-pair+- `failed to decode app state` → same class of error+- `Failed to do initial fetch of app state` → same class of error++If any match:++1. Print the diagnosis verbatim:+ ```+ ⚠ WhatsApp session is authenticated but the app-state decryption keys+ are out of sync with your primary device. This happens when the+ linked-device session is partially wiped on the phone side.+ Symptom: sync runs but 0 messages come through.+ Fix: logout this session and re-pair via QR.+ ```+2. Ask `AskUserQuestion`: `[Logout and walk me through re-pair]`, `[Skip — I'll fix manually]`.+3. On logout: run `wacli auth logout --json` and show the result. Then print:+ ```+ Now run `wacli auth` in a separate terminal (QR-based auth — requires your phone camera).+ A QR code will appear — scan it from WhatsApp → Settings → Linked Devices → Link a device.+ When it says "Connected", come back and type "done".+ ```+4. Wait for the user to confirm via `AskUserQuestion`: `[Done — re-paired]`, `[Cancel]`.+5. On Done, re-run Step 3b.2 to re-collect state and continue to rule D.++**D. Authenticated, lock free, no recent messages, no key errors**+This is usually a cold cache. Go to Step 3b.4 (backfill).++**E. Healthy (messages flowing)**+If `messages.data.messages` has ≥1 entry from the last 24h, print a ✓ summary and skip to Step 3b.5.++#### Step 3b.4 — Historical backfill (background, silent)++Always run this after a fresh re-pair, AND run it when rule D matches. Never skip unless the user explicitly declines.++Backfill is a background optimization — it should not produce verbose output or alarming status messages. Run it silently and swallow non-fatal errors.++1. Load the top 10 chats by recency:+ ```bash+ wacli chats list --json 2>&1 | jq -r '[.data[] | select(.jid) | {jid, name, last_msg: .last_message_ts}] | sort_by(.last_msg) | reverse | .[0:10]'+ ```+2. Tell the user: `"Running historical backfill on your 10 most-recent chats. This runs in the background."` Do not print per-chat progress or 0-message results.+3. For each chat JID, run **sequentially** (backfill shares the store lock, can't parallelize):+ ```bash+ wacli history backfill --chat="<jid>" --count=50 --requests=2 --wait=30s --idle-exit=5s --json 2>&1+ ```+4. **Suppress all per-chat output.** If the command exits non-zero, swallow the error silently — backfill failures are not user-visible events. Do NOT print "0 messages synced", error tracebacks, or explanations about device connectivity.+5. After the loop completes, print only the final health summary (Step 3b.6).++#### Step 3b.5 — FTS index check (optional)++If `doctor.fts_enabled: false`, print:++```+ℹ Full-text search is disabled — `wacli messages search` will use SQL LIKE (slower).+ This is a non-fatal known-limitation. See wacli docs to enable FTS5.+```++Don't block on this.++#### Step 3b.6 — Record state++Write `channels.whatsapp = "wacli"` to `$PREFS_PATH` and print the final ✓ summary:++```+✓ WhatsApp — wacli authenticated, N chats+```++Never include message counts or backfill results in this summary line.++#### Step 3b.7 — Persistent connection (keepalive)++After successful auth and backfill, set up a persistent connection that keeps wacli connected and auto-syncing. This is what makes WhatsApp reliable across sessions — without it, the linked device disconnects after ~14 days of inactivity and @lid JIDs return empty messages.++**If the ops-daemon is configured (Step 5b), wacli runs as a daemon service** — skip the standalone launchd path below and note to the user that wacli sync is managed by the daemon. The daemon handles bootstrap, auto-backfill, and health reporting centrally.++**Standalone launchd fallback** (only if the ops-daemon is NOT being set up):++**1. Install the keepalive script:**++```bash+KEEPALIVE_SCRIPT="${CLAUDE_PLUGIN_ROOT}/scripts/wacli-keepalive.sh"+chmod +x "$KEEPALIVE_SCRIPT"+```++**2. Generate the launchd plist from template:**++```bash+PLIST_TEMPLATE="${CLAUDE_PLUGIN_ROOT}/scripts/com.claude-ops.wacli-keepalive.plist"+PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.wacli-keepalive.plist"+LOG_DIR="$HOME/.claude/plugins/data/ops-ops-marketplace/logs"+mkdir -p "$LOG_DIR" "$HOME/Library/LaunchAgents"++sed -e "s|__KEEPALIVE_SCRIPT_PATH__|$KEEPALIVE_SCRIPT|g" \+ -e "s|__LOG_DIR__|$LOG_DIR|g" \+ -e "s|__HOME__|$HOME|g" \+ "$PLIST_TEMPLATE" > "$PLIST_DEST"+```++**3. Load the agent:**++```bash+# Unload if already loaded (idempotent)+launchctl bootout gui/$(id -u) "$PLIST_DEST" 2>/dev/null || true+launchctl bootstrap gui/$(id -u) "$PLIST_DEST"+```++**4. Verify it's running:**++Wait 3 seconds, then check:+```bash+launchctl print gui/$(id -u)/com.claude-ops.wacli-keepalive 2>&1 | head -5+cat "$HOME/.wacli/.health" 2>/dev/null+```++If the health file shows `status=connected` or `status=needs_reauth`, the daemon is working. Print:++```+✓ WhatsApp keepalive — launchd agent installed and running+ Persistent sync active. Auto-restarts on disconnect.+ Health: ~/.wacli/.health | Logs: ~/.claude/plugins/data/ops-ops-marketplace/logs/+```++If `status=needs_reauth`, immediately trigger the re-pair flow from Step 3b.3 Rule C.++**5. How the keepalive self-heals:**++The keepalive script (`wacli-keepalive.sh`) handles these failure modes automatically:++| Failure | Auto-fix |+|---------|----------|+| Orphaned wacli process holding lock | Kills stale PIDs, clears lock |+| Connection drop (WhatsApp server restart) | launchd restarts within 60s |+| App-state key desync | Writes `needs_reauth` to health file — ops skills detect this and prompt QR |+| Auth expired | Writes `needs_auth` — same prompt flow |+| Script crash | launchd KeepAlive=true restarts immediately (throttled 60s) |++**6. Health file contract for other ops skills:**++All ops skills that use WhatsApp (`ops-inbox`, `ops-comms`, `ops-go`) MUST check `~/.wacli/.health` before attempting wacli commands. If `status=needs_auth` or `status=needs_reauth`:++1. Print the diagnosis to the user:+ ```+ ⚠ WhatsApp needs re-authentication.+ Run `wacli auth` in a separate terminal and scan the QR code with your phone+ (QR-based auth — exception to Rule 2). Then type "done" to continue.+ ```+2. Use `AskUserQuestion`: `[Done — re-paired]`, `[Skip WhatsApp]`.+3. On Done: restart the keepalive daemon via `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive` and wait 5s for health file update.++This ensures the user is never silently left with a broken WhatsApp connection — every ops skill surfaces the problem and walks them through the fix.++### 3c — Email++Email has two possible backends, tried in this order:++#### Preferred: `gog` CLI++`gog` is the email + calendar CLI that `ops-inbox` and `ops-comms` call by default. It's a self-contained binary with its own OAuth token at `~/.gog/token.json` — full read + send permissions, no Claude Desktop config required.++1. Check `gog` on PATH with `command -v gog`.+2. **If installed**, run `gog auth status 2>&1 || true` and show the output.+ - If auth is red (not authenticated / token expired / exit != 0), run `gog auth login` via Bash tool with `run_in_background: true` (it opens a browser for the OAuth flow). Tell the user: "Opening browser for Gmail OAuth — complete the sign-in there, then type 'done'." Use `AskUserQuestion`: `[Done — authenticated]`, `[Skip email]`.+ - If auth is green, probe with:+ ```bash+ gog gmail labels list --json 2>&1 | head -5+ ```+ If this returns JSON containing a `labels` array, gog is authenticated and the Gmail API is working. Report ✓. If the output is an error or empty, treat as broken and instruct the user to re-run `gog auth login`.+ - Record `channels.email = "gog"` in `$PREFS_PATH` and stop here.++#### Fallback: Claude Gmail MCP connector++If `gog` is not on PATH, look at the detector's `mcp_configured` array for any entry matching (case-insensitive) `gmail`, `google-mail`, or `claude_ai_Gmail` — these are the common names for Anthropic's Gmail connector or user-installed Gmail MCP servers.++3. **If a Gmail MCP is configured**, ask `AskUserQuestion`:+ - `[Use Gmail MCP (read-only fallback)]`+ - `[Install gog instead — show docs]`+ - `[Skip email]`+4. On "Use Gmail MCP", record `channels.email = "mcp:<name>"` in `$PREFS_PATH` (where `<name>` is the actual MCP server name you found) and **print this warning verbatim**:+ ```+ ⚠ Using the Gmail MCP connector as a fallback.+ Read operations (list inbox, search, fetch) will work.+ SEND operations will fail until you explicitly grant send permissions+ in Claude Desktop → Settings → Connectors → Gmail → Permissions.+ The ops plugin cannot grant those permissions for you — it's a Claude+ Desktop-side setting tied to your account.+ If you want unattended sending from ops-comms, install `gog` instead.+ ```+5. On "Install gog instead", print:+ ```+ gog is a private CLI — install from source:+ git clone https://github.com/Lifecycle-Innovations-Limited/gog ~/.gog && cd ~/.gog && ./install.sh+ Or download a release binary from the GitHub releases page.+ ```+ Then stop this sub-flow (don't attempt to `brew install` — gog isn't on Homebrew).++#### Neither available++6. **If `gog` is missing AND no Gmail MCP is configured**, ask `AskUserQuestion`:+ - `[Install gog — show docs]`+ - `[Add a Gmail MCP — show docs]` → print `claude mcp add gmail` and tell the user to re-run `/ops:setup email` after+ - `[Skip email for now]`+7. Whatever the user picks, record the resulting state in `$PREFS_PATH` (either `channels.email = "gog"`, `channels.email = "mcp:<name>"`, or omit the key entirely).++### 3d — Slack (scout + ops-slack-autolink)++Slack's official API requires workspace admin approval for most useful scopes. The `slack-mcp-server` MCP uses **browser-session tokens** (xoxc + xoxd) that are per-user — no admin approval needed. The plugin ships `bin/ops-slack-autolink.mjs` which:++1. **Phase 1 — scout** — checks for already-extracted tokens in:+ - `~/.claude.json mcpServers.slack.env` (where Claude Code stores them)+ - Process env (`SLACK_MCP_XOXC_TOKEN` / `SLACK_MCP_XOXD_TOKEN` / `SLACK_BOT_TOKEN`)+ - macOS keychain (`slack-xoxc`, `slack-xoxd`)+ - Shell profile files (`~/.zshrc`, `~/.bashrc`, `~/.zprofile`, `~/.envrc`)+ - Doppler (`doppler secrets --json`)+2. **Phase 2 — Playwright extraction** — only if nothing is found, launches a persistent-profile Chromium, opens `https://app.slack.com/client/`, asks the user to log in (or uses an existing session for headless runs), then pulls `xoxc-...` from `localStorage.localConfig_v2.teams[teamId].token` and the `d=...` cookie (`xoxd-...`) from the cookie jar.++Ported from [maorfr/slack-token-extractor](https://github.com/maorfr/slack-token-extractor) (Python → Node).++Sub-flow:++1. **Scout first.** Run:++ ```bash+ node "${CLAUDE_PLUGIN_ROOT}/bin/ops-slack-autolink.mjs" --scout-only 2>/tmp/ops-slack.log+ ```++ Parse the stdout JSON. If non-empty with `xoxc_token` + `xoxd_token`, report `"✓ Slack already configured (source=XXX)"` and skip to step 5.++2. **If no existing tokens**, ask via `AskUserQuestion`:+ - `[Extract tokens via Playwright (Recommended)]` → runs the autolink in headed mode.+ - `[I'll paste tokens manually]` → collect `xoxc-...` and `xoxd-...` via two free-text `AskUserQuestion`s.+ - `[Skip Slack]`++3. **On Playwright path**: spawn the autolink in the background:++ ```bash+ (umask 077 && node "${CLAUDE_PLUGIN_ROOT}/bin/ops-slack-autolink.mjs" \+ --workspace "https://app.slack.com/client/" \+ 2>/tmp/ops-slack-autolink.log 1>/tmp/ops-slack-autolink.out &)+ echo $! > /tmp/ops-slack-autolink.pid+ ```++ Poll the log for `{"type":"need_login"}`. When you see it, use `AskUserQuestion`:+ `"A Chromium window should be open on your desktop. Log in to Slack there, then pick [Done]."`. On Done, `touch /tmp/slack-login-done`. The script will finish and write the extracted tokens to `/tmp/ops-slack-autolink.out`.++4. **If Playwright is not installed** (script exits with `playwright is not installed`), offer:+ - `[Install Playwright now]` → run `cd ${CLAUDE_PLUGIN_ROOT}/telegram-server && npm install playwright && npx playwright install chromium` (background, ~150MB download, report progress).+ - `[Fall back to manual paste]` → go to step 2 manual path.++5. **Validate tokens.** Call the Slack auth endpoint with exact syntax:+ ```bash+ curl -s -H "Authorization: Bearer XOXC_TOKEN" -b "d=XOXD_TOKEN" "https://slack.com/api/auth.test"+ ```+ Expect `{"ok":true, "team_id":"T...", "user_id":"U...", "url":"https://<workspace>.slack.com/"}`. If `ok:false`, show the error and re-ask.++6. **Persist.**+ - Keychain: `security add-generic-password -U -s slack-xoxc -a "$USER" -w "$XOXC"; security add-generic-password -U -s slack-xoxd -a "$USER" -w "$XOXD"`.+ - `$PREFS_PATH` → `channels.slack = {backend: "mcp:slack", team_id: "...", source: "...", status: "configured"}`. **Do not** store the raw tokens in preferences.json — keychain only.++7. **Wire into Claude Code plugin settings.** Print instructions:++ ```+ Slack tokens saved to keychain. To activate the MCP, Claude Code needs them+ in ~/.claude.json. Since this skill can't write to ~/.claude.json directly,+ either:+ a) Run: claude mcp add slack --transport stdio -- npx -y slack-mcp-server@latest --transport stdio+ and Claude Code will prompt for the env vars.+ b) Manually paste the xoxc + xoxd into /plugin settings for the Slack MCP.+ ```++ (The reason we don't auto-write: per user-level feedback, ~/.claude.json is a Claude Code internal file and the plugin must not touch it. MCP registration is Claude Code's responsibility.)++8. **Smoke test**: call `https://slack.com/api/conversations.list?limit=1` with the tokens. Expect `ok:true` with at least one channel in the response.++**Privacy notes**:++- Tokens work as long as your browser session stays active — typically weeks to months with regular Slack usage. If the MCP starts returning 401s, re-run `/ops:setup slack`.+- Logging out of Slack invalidates the `d` cookie and breaks the MCP. Use `/ops:setup slack` to re-extract.+- Slack's Terms of Service allow personal-session-token use for your own account. Do not use this flow to access accounts you don't own.++### 3e — Calendar++Calendar isn't a messaging channel, but every other ops skill (briefings, `/ops-next`, `/ops-go`) benefits massively from knowing the user's schedule — meetings blocking deep work, deploy windows, travel days. The wizard wires it up the same way as email: `gog calendar` primary, Google Calendar MCP connector fallback.++#### Preferred: `gog calendar`++`gog` already handles email; the same binary exposes `gog calendar` / `gog cal` with the same OAuth token. No additional auth needed if Step 3c went green.++1. Check `gog` on PATH with `command -v gog`.+2. **If installed and already authed from Step 3c**, probe:+ ```bash+ gog cal list --json --max 3 2>&1 | head -20+ ```+ If this returns JSON with calendar data, record `channels.calendar = "gog"` in `$PREFS_PATH` and print `✓ Calendar — gog cal`. Stop here.+3. **If gog is installed but calendar scope is missing** (typical error: `insufficient scope` or `403 insufficient_permissions`), print:+ ```+ Your gog OAuth token doesn't include the calendar scope.+ Run `gog auth login --scopes=gmail,calendar` via Bash tool with `run_in_background: true` to re-authorize with calendar read access. Tell the user: "Opening browser for Calendar OAuth — complete the sign-in there, then type 'done'." Use `AskUserQuestion`: `[Done — re-authorized]`, `[Skip calendar]`.+ ```+ Do not attempt to re-auth from the skill — it's a browser flow.++#### Fallback: Claude Google Calendar MCP connector++4. **If gog is not on PATH**, scan the detector's `mcp_configured` array for any entry matching (case-insensitive) `calendar`, `google-calendar`, or `claude_ai_Calendar`.+5. If found, ask `AskUserQuestion`:+ - `[Use Google Calendar MCP (read-only fallback)]`+ - `[Install gog instead — show docs]`+ - `[Skip calendar]`+6. On "Use Google Calendar MCP", record `channels.calendar = "mcp:<name>"` in `$PREFS_PATH` and **print this warning verbatim**:+ ```+ ⚠ Using the Google Calendar MCP connector as a fallback.+ Read operations (list calendars, fetch events, check free/busy) will work.+ WRITE operations (create events, decline meetings, reschedule) will fail+ until you explicitly grant write permissions in+ Claude Desktop → Settings → Connectors → Google Calendar → Permissions.+ The ops plugin cannot grant those permissions for you.+ If you want ops-next to auto-block focus time or ops-comms to confirm+ meetings, install `gog` instead.+ ```+7. On "Install gog instead", print the same gog install snippet as Step 3c.++#### Neither available++8. **If `gog` is missing AND no Calendar MCP is configured**, ask:+ - `[Install gog — show docs]`+ - `[Add the Google Calendar MCP — show docs]` → print `claude mcp add google-calendar` and tell the user to re-run `/ops:setup calendar` after+ - `[Skip calendar]`++#### Why this matters (for context in the skill)++Downstream skills (`/ops-go`, `/ops-next`, `/ops-fires`) read `channels.calendar` from `$PREFS_PATH` to decide whether to cross-correlate today's schedule with their output:++- Briefings note "you have a 2pm standup, so don't start that refactor now"+- `/ops-next` deprioritizes deep work when a meeting is <30min away+- `/ops-fires` warns if a production incident falls during a scheduled call+ So this section is not optional for users who want context-aware briefings.++### 3f — Doppler (secrets management)++Doppler is a secrets manager that injects environment variables at runtime. When configured, all ops skills can query secrets via `doppler secrets get` instead of reading from dotfiles or keychain. The wizard checks presence, auth status, and default project context.++#### Step 3f.1 — Presence++```bash+command -v doppler+```++If missing, ask via `AskUserQuestion`:++```+Doppler CLI is not installed.+ [Install now — brew install dopplerhq/cli/doppler]+ [Skip Doppler]+```++On install, run in the background:++```bash+brew install dopplerhq/cli/doppler+```++Report success/failure. If the user skips, record `secrets_manager: "none"` in `$PREFS_PATH` and end this sub-flow.++#### Step 3f.2 — Auth status++Run:++```bash+doppler me --json 2>&1+```++Parse the JSON. If the output contains `"error"` or a non-zero exit code, the user is not authenticated. Print:++```+Doppler is not authenticated. Running `doppler login` now...+```++Run `doppler login` via Bash tool with `run_in_background: true` (it opens a browser for the OAuth flow). Tell the user: "Opening browser for Doppler OAuth — complete the sign-in there, then type 'done'." Use `AskUserQuestion`: `[Done — authenticated]`, `[Skip Doppler]`. On Done, re-run `doppler me --json` to verify. If authenticated, `doppler me` will return JSON with `name` and `email` — confirm:++```+✓ Doppler authenticated as <name> (<email>)+```++Never display the name or email unless they came from `doppler me` output in this session.++#### Step 3f.3 — Project context++If authenticated, list available projects:++```bash+doppler projects --json 2>&1+```++Parse the array of project objects. Present them via `AskUserQuestion` with `singleSelect`. **Max 4 options per call** — if there are more than 3 projects, paginate: show 3 projects + `[More projects...]` per page, with `[Skip — don't set a default project]` always as the last option on the final page.++```+Select your default Doppler project (page 1):+ [ ] my-app+ [ ] my-api+ [ ] my-service+ [ ] More projects...+```++If the user selects a project, fetch its configs:++```bash+doppler configs --project <selected_project> --json 2>&1+```++Present available configs via `AskUserQuestion` with `singleSelect` (max 4 options — paginate if needed):++```+Select the default config for <project>:+ [ ] dev+ [ ] staging+ [ ] production+```++Write the selection to `$PREFS_PATH` (merge, don't overwrite):++```json+{+ "secrets_manager": "doppler",+ "doppler": {+ "project": "<selected>",+ "config": "<selected>"+ }+}+```++Print confirmation:++```+✓ Doppler default context set: <project>/<config>+```++#### Step 3f.4 — Document for agents++Print this note so it's visible in the session:++```+All ops skills can now query secrets via:++ doppler secrets get <KEY> --plain --project <project> --config <config>++For example:+ doppler secrets get TELEGRAM_BOT_TOKEN --plain --project my-app --config dev++The project and config above are the defaults saved to preferences.+Individual skills can override with --project / --config flags.+```++### 3g — Password Manager (credential vault)++Ops agents frequently need to look up credentials (API keys, database passwords, service tokens) on your behalf. This step wires up a password manager so those queries can be automated via a standard command template stored in `$PREFS_PATH`.++#### Step 3g.1 — Auto-detect installed managers++Run these in parallel:++```bash+command -v op 2>/dev/null && op account list --format=json 2>&1 # 1Password CLI+command -v dcli 2>/dev/null && dcli sync 2>&1 # Dashlane CLI+command -v bw 2>/dev/null && bw status --raw 2>&1 # Bitwarden CLI+security find-generic-password -s "test" 2>&1 | head -1 # macOS Keychain (always available)+```++Parse each result to classify as `authenticated`, `needs_unlock`, `not_installed`, or `available` (Keychain is always `available`).++#### Step 3g.2 — Present findings++Show only what was detected via `AskUserQuestion`. **Max 4 options per call.** Since macOS Keychain and Skip are always shown, you have room for at most 2 detected managers per call. If all 3 CLIs (1Password, Dashlane, Bitwarden) are installed, batch into two calls:++**If <=2 CLI managers detected (common case — fits in one call):**+```+Password managers found:+ [1Password — authenticated as <account>]+ [Dashlane — needs unlock]+ [macOS Keychain — always available]+ [Skip — don't connect a password manager]+```++**If all 3 CLI managers detected (rare — batch into two calls):**+Call 1:+```+ [1Password — authenticated as <account>]+ [Dashlane — needs unlock]+ [Bitwarden — <status>]+ [More options...]+```+Call 2:+```+ [macOS Keychain — always available]+ [Skip — don't connect a password manager]+```++Never show managers that aren't installed. Always show macOS Keychain and Skip. If none of the CLIs are installed, skip straight to showing just `[macOS Keychain — always available]` and `[Skip]`.++#### Step 3g.3 — Configure selected manager++**1Password (`op`):**++1. Check auth: `op account list --format=json`+2. If the output is empty or exits non-zero (not signed in), print:+ ```+ 1Password CLI is installed but not signed in.+ Run `op signin` via Bash tool with `run_in_background: true`, then re-run /ops:setup vault.+ ```+ Stop this sub-flow.+3. If authed, list vaults for the user to pick a default:+ ```bash+ op vault list --format=json+ ```+ Use `AskUserQuestion` (single select) to present the vault names. The selected vault becomes `password_manager_config.vault`.+4. Record query syntax:+ ```+ op item get "{{name}}" --fields label=password --format=json+ ```++**Dashlane (`dcli`):**++1. Check auth: `dcli sync`+2. If `dcli sync` fails or returns a not-configured error, print:+ ```+ Dashlane CLI is installed but not configured.+ Run `dcli configure` via Bash tool, then re-run /ops:setup vault.+ ```+ Stop this sub-flow.+3. Record query syntax:+ ```+ dcli password --filter "{{name}}" --output json+ ```+4. No vault selection needed — Dashlane has a flat namespace.++**Bitwarden (`bw`):**++1. Check auth: `bw status --raw` and parse the JSON `status` field.+ - `"unauthenticated"` → print:+ ```+ Bitwarden CLI is installed but not logged in.+ Run `bw login` via Bash tool with `run_in_background: true`, then re-run /ops:setup vault.+ ```+ Stop this sub-flow.+ - `"locked"` → print:+ ```+ Bitwarden vault is locked.+ Run `bw unlock --raw` via Bash tool, capture the session token, and export it as `BW_SESSION` for subsequent commands. Then continue /ops:setup vault.+ ```+ Stop this sub-flow.+ - `"unlocked"` → continue.+2. Record query syntax:+ ```+ bw get item "{{name}}" --pretty+ ```+3. No vault selection — Bitwarden uses a single unlocked vault per session.++**macOS Keychain:**++1. No auth check needed — always available.+2. Note for the user:+ ```+ macOS Keychain is always available but is limited to items stored locally.+ No cross-device sync. Best for machine-specific secrets (API keys added via+ `security add-generic-password`).+ ```+3. Record query syntax:+ ```+ security find-generic-password -s "{{name}}" -w+ ```++#### Step 3g.4 — Write to preferences++After the user selects and configures a manager, write to `$PREFS_PATH`:++```json+{+ "password_manager": "<1password|dashlane|bitwarden|keychain>",+ "password_manager_config": {+ "vault": "<vault name, or omit if not applicable>",+ "query_cmd": "<template with {{name}} placeholder>"+ }+}+```++Merge with the existing file (`jq '. + { ... }'`) — never overwrite. Example for 1Password:++```json+{+ "password_manager": "1password",+ "password_manager_config": {+ "vault": "Private",+ "query_cmd": "op item get \"{{name}}\" --fields label=password --format=json"+ }+}+```++If the user picks Skip, write `"password_manager": "none"` so subsequent runs don't re-prompt unless the user explicitly runs `/ops:setup vault`.++#### Step 3g.5 — Document for agents++After saving, print this note once:++```+All ops skills can now query credentials via your configured password manager.+The query command template is in preferences.json under password_manager_config.query_cmd.+Replace {{name}} with the item name — e.g. "GitHub PAT", "AWS root key", "my-project-db".++To query manually:+ op item get "GitHub PAT" --fields label=password --format=json (1Password example)+ security find-generic-password -s "my-project-db" -w (Keychain example)+```++#### Dashboard display++Update the Step 0b status header to include vault status:++```+ Vault: ✓ 1password (vault: Private)+```++Use `○ none` if skipped, `✗ locked` if the manager is installed but inaccessible.++#### Completion summary (Step 8)++Include in the final summary block:++```+ ✓ Vault: 1password → Private vault+```++Omit this line entirely if `password_manager` is `"none"` or unset.++#### Invocation shortcut++Add to the shortcuts table: `vault`, `password-manager`, `pm` → Step 3g++---++### 3h — Ecommerce (Shopify + dynamic partners)++#### Step 3h.1 — Auto-scan for existing Shopify credentials++**Before asking for anything**, run the Universal Credential Auto-Scan for all Shopify-related vars simultaneously:++```bash+# Scan shell env+printenv SHOPIFY_ACCESS_TOKEN SHOPIFY_ADMIN_TOKEN SHOPIFY_STORE_URL SHOPIFY_ADMIN_API_ACCESS_TOKEN 2>/dev/null++# Scan shell profiles+grep -h 'SHOPIFY\|myshopify' ~/.zshrc ~/.bashrc ~/.zprofile ~/.envrc 2>/dev/null | grep -v '^#'++# Scan Doppler across all projects+for proj in $(doppler projects --json 2>/dev/null | jq -r '.[].slug'); do+ doppler secrets --project "$proj" --config prd --json 2>/dev/null | \+ jq -r --arg proj "$proj" 'to_entries[] | select(.key | test("SHOPIFY|STORE")) | "\(.key)=\(.value.computed) (doppler:\($proj)/prd)"'+done++# Scan Dashlane+dcli password shopify --output json 2>/dev/null++# Scan macOS Keychain+security find-generic-password -s "shopify-admin-token" -w 2>/dev/null+security find-generic-password -s "shopify-access-token" -w 2>/dev/null++# Scan OpenClaw+jq -r '.agents.defaults.env | to_entries[] | select(.key | test("SHOPIFY")) | "\(.key)=\(.value)"' ~/.openclaw/openclaw.json 2>/dev/null++# Check existing prefs+jq -r '.ecom.shopify // empty' "$PREFS_PATH" 2>/dev/null+```++If both `store_url` and `admin_token` are already found, show:+```+✓ Shopify — already configured (<store_url>)+ [Keep existing] [Reconfigure]+```+If the user keeps existing, skip to Step 3h.4. If reconfiguring or no values found, continue.++#### Step 3h.2 — Shopify store URL++If `SHOPIFY_STORE_URL` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format. Only ask via free text if no value was found:+```+Enter your Shopify store URL:+ Format: yourstore.myshopify.com+ (Do not include https://)+```++Validate the input: strip `https://`, strip trailing slash, check that the result ends with `.myshopify.com`. If invalid, ask again with a correction note.++#### Step 3h.3 — Shopify Admin API token++If `SHOPIFY_ACCESS_TOKEN`, `SHOPIFY_ADMIN_TOKEN`, or `SHOPIFY_ADMIN_API_ACCESS_TOKEN` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format with truncated display (`shpat_508b...682e`). Only ask via free text if no value was found:+```+Enter your Shopify Admin API access token:+ To generate one:+ 1. Go to your Shopify admin → Settings → Apps → Develop apps+ 2. Create an app (or select an existing one)+ 3. Under "Configuration", grant the scopes you need (read_orders, read_products, etc.)+ 4. Install the app, then copy the "Admin API access token"+ Token starts with "shpat_"+```++Save to `$PREFS_PATH` under `ecom.shopify`. Apply the Doppler-reference pattern — if Doppler is configured, run:+```bash+doppler secrets set SHOPIFY_ADMIN_TOKEN="<token>" --project <project> --config <config>+```+and store `"admin_token": "doppler:SHOPIFY_ADMIN_TOKEN"` in preferences instead of the raw token.++Smoke test:+```bash+STORE=$(jq -r '.ecom.shopify.store_url' "$PREFS_PATH")+TOKEN=$(jq -r '.ecom.shopify.admin_token' "$PREFS_PATH")+if [[ "$TOKEN" == doppler:* ]]; then+ KEY="${TOKEN#doppler:}"+ TOKEN=$(doppler secrets get "$KEY" --plain 2>/dev/null)+fi+curl -s -H "X-Shopify-Access-Token: $TOKEN" \+ "https://$STORE/admin/api/2024-10/shop.json" | jq '.shop.name'+```+Expect a shop name string. If the response contains `errors` or `{"shop":null}`, show the error and ask the user to check the token scopes. Print `✓ Shopify — connected (<shop name>)`.++#### Step 3h.4 — Dynamic ecommerce partners++After Shopify is configured, ask via `AskUserQuestion` (free text):+```+Do you use any other ecommerce tools you'd like to connect?+ Examples: ShipBob (fulfillment), Recharge (subscriptions), Yotpo (reviews),+ Shippo (shipping rates), Gorgias (support), Attentive (SMS), Loop (returns)+ Type the names separated by commas, or leave blank to skip.+```++If the user provides partner names, process each one in a loop:++**For each partner:**++1. **Research credentials** — web search: `"<partner name> API authentication developer docs 2025"`. Determine:+ - What credentials are needed (API key, OAuth token, webhook secret, base URL, account ID, etc.)+ - The API base URL+ - A suitable health/auth endpoint to smoke test (e.g. `/me`, `/account`, `/v1/ping`, list endpoint with limit=1)+ - The auth header pattern (`Authorization: Bearer`, `X-Api-Key`, custom header, etc.)++2. **Ask for each credential** via `AskUserQuestion` (one question per credential field), citing where to find it based on what the docs say. Example for ShipBob:+ Run the Universal Credential Auto-Scan for `SHIPBOB_ACCESS_TOKEN`, `SHIPBOB_API_TOKEN` before asking. If found, present with source attribution. Only prompt manually if not found:+ ```+ Enter your ShipBob Personal Access Token:+ To generate: ShipBob dashboard → Integrations → API → Personal Access Tokens → Create Token+ ```++3. **Smoke test** using the auth endpoint discovered in step 1:+ ```bash+ curl -s -H "<auth_header>: $TOKEN" "<base_url>/<health_endpoint>" | jq '.<identity_field>'+ ```+ Show the result. If it fails, show the raw response and offer `[Re-enter credentials]` / `[Skip this partner]`.++4. **Save to preferences** under `ecom.partners.<partner_slug>` where `partner_slug` is the lowercased, hyphenated partner name:+ ```json+ {+ "ecom": {+ "partners": {+ "shipbob": {+ "api_base_url": "https://developer.shipbob.com/v1",+ "auth_pattern": "Authorization: Bearer <token>",+ "credentials": { "api_token": "doppler:SHIPBOB_API_TOKEN" },+ "health_endpoint": "/user",+ "configured_at": "<ISO timestamp>"+ }+ }+ }+ }+ ```+ Store actual secrets via Doppler (key: `<PARTNER_SLUG_UPPER>_API_TOKEN`) when Doppler is configured, else store inline. The `auth_pattern` and `api_base_url` fields are the memory that future `/ops:ecom` calls use to reach the partner — always populate them from the researched docs.++5. **Print confirmation**:+ ```+ ✓ <Partner Name> — connected+ ```++6. **Loop**: After each partner, ask `AskUserQuestion`: "Any other ecommerce tools to connect?" → `[Yes — add another]` / `[Done]`. This lets users add partners one at a time if they prefer over the initial comma-separated list.++**Partners with known credential patterns** (use these directly without searching, but still verify with a smoke test):++| Partner | Auth header | Base URL | Health endpoint |+| ---------- | ---------------------------------------- | -------------------------------------- | ---------------------- |+| ShipBob | `Authorization: Bearer <token>` | `https://developer.shipbob.com/v1` | `/user` |+| Recharge | `X-Recharge-Access-Token: <token>` | `https://api.rechargeapayments.com/v1` | `/shop` |+| Yotpo | `X-Api-Key: <app_key>` | `https://api.yotpo.com` | `/core/v3/stores/<id>` |+| Shippo | `Authorization: ShippoToken <token>` | `https://api.goshippo.com` | `/carrier_accounts` |+| Gorgias | `Authorization: Basic <base64>` | `https://<domain>.gorgias.com/api` | `/account` |+| Loop | `x-loop-signature: <secret>` | `https://api.loopreturns.com/api/v1` | `/warehouse` |+| Attentive | `Authorization: Bearer <token>` | `https://api.attentivemobile.com/v1` | `/me` |++For any partner not in this table, always web search for current auth docs before asking for credentials.++---++### 3i — Marketing (Klaviyo, Meta Ads, GA4, Search Console)++**Before showing the service selector**, run the Universal Credential Auto-Scan for all marketing vars simultaneously:++```bash+# Shell env+printenv KLAVIYO_API_KEY KLAVIYO_PRIVATE_KEY META_ACCESS_TOKEN FACEBOOK_ACCESS_TOKEN META_AD_ACCOUNT_ID GA4_PROPERTY_ID GA_MEASUREMENT_ID 2>/dev/null++# Shell profiles+grep -h 'KLAVIYO\|META_\|FACEBOOK\|GA4\|GA_MEASUREMENT' ~/.zshrc ~/.bashrc ~/.zprofile ~/.envrc 2>/dev/null | grep -v '^#'++# Doppler across all projects+for proj in $(doppler projects --json 2>/dev/null | jq -r '.[].slug'); do+ doppler secrets --project "$proj" --config prd --json 2>/dev/null | \+ jq -r --arg proj "$proj" 'to_entries[] | select(.key | test("KLAVIYO|META|FACEBOOK|GA4|GOOGLE")) | "\(.key)=\(.value.computed) (doppler:\($proj)/prd)"'+done++# Dashlane+dcli password klaviyo --output json 2>/dev/null+dcli password facebook --output json 2>/dev/null+dcli password meta --output json 2>/dev/null++# OpenClaw+jq -r '.agents.defaults.env | to_entries[] | select(.key | test("KLAVIYO|META_|FACEBOOK|GA4")) | "\(.key)=\(.value)"' ~/.openclaw/openclaw.json 2>/dev/null+```++Cache these results — use them to pre-fill answers for each sub-step below. For each service below, check if already configured (check `$PREFS_PATH` under `marketing.*`, then the auto-scan results above) before prompting. If already set, show `✓ <service> — already configured` and offer `[Keep]` / `[Reconfigure]`.++Ask which marketing integrations to configure via `AskUserQuestion` with `multiSelect: true` (4 options — fits in one call):++| Option | Header | Description |+| ----------------------- | -------- | --------------------------------------------- |+| Klaviyo | klaviyo | Email/SMS marketing — private API key |+| Meta Ads | meta | Facebook/Instagram ads — access token + ad account ID |+| Google Analytics 4 | ga4 | Web analytics — GA4 property ID |+| Google Search Console | gsc | SEO data — site URL (uses gcloud auth) |++#### Klaviyo++If `KLAVIYO_API_KEY` or `KLAVIYO_PRIVATE_KEY` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format. Only ask via free text if not found:+```+Enter your Klaviyo Private API Key:+ To generate one: Klaviyo dashboard → Settings → API Keys → Create Private Key+ Key starts with "pk_"+```++Smoke test:+```bash+curl -s -H "Authorization: Klaviyo-API-Key $KEY" \+ -H "revision: 2024-10-15" \+ "https://a.klaviyo.com/api/lists" | jq '.data | length'+```+Expect a number ≥ 0. If the response contains `"detail"` with an auth error, show it and re-ask.++#### Meta Ads++If `META_ACCESS_TOKEN` or `FACEBOOK_ACCESS_TOKEN` was found in the auto-scan, present it. If `META_AD_ACCOUNT_ID` was found, present that too. Only ask via free text for values not found.++Ask for:+1. Access token (explain: Meta Business Suite → Settings → System Users or your personal account → Generate token with `ads_read` permission)+2. Ad account ID (format: `act_XXXXXXXXXX` — found in Business Manager → Ad Accounts)++Smoke test:+```bash+curl -s "https://graph.facebook.com/v20.0/$AD_ACCOUNT_ID/campaigns?access_token=$TOKEN&limit=1" | jq '.data | length'+```++#### Google Analytics 4++If `GA4_PROPERTY_ID` or `GA_MEASUREMENT_ID` was found in the auto-scan, present it. Only ask via free text if not found. Ask for the GA4 Property ID (explain: GA4 dashboard → Admin → Property Settings → Property ID, format: numeric, e.g. `123456789`).++No API key needed if `gcloud` is authenticated — the GA4 Data API uses Application Default Credentials. Check:+```bash+gcloud auth application-default print-access-token 2>/dev/null | head -c 10+```+If gcloud ADC is not set up, note that GA4 queries will require manual auth: `gcloud auth application-default login`.++#### Google Search Console++Ask for the site URL (format: `https://example.com/` or `sc-domain:example.com`). No API key needed if gcloud is authed.++Smoke test:+```bash+ACCESS_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null)+curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \+ "https://searchconsole.googleapis.com/webmasters/v3/sites" | jq '.siteEntry | length'+```++#### Save to preferences++Write to `$PREFS_PATH` (merge):+```json+{+ "marketing": {+ "klaviyo": { "api_key": "<pk_...>" },+ "meta": { "access_token": "<token>", "ad_account_id": "act_XXXXXXXXXX" },+ "ga4": { "property_id": "123456789" },+ "gsc": { "site_url": "https://example.com/" }+ }+}+```++Same Doppler-reference pattern as Step 3h — prefer `doppler:KEY_NAME` over raw tokens when Doppler is configured.++#### Dynamic marketing partners++After the known services, ask via `AskUserQuestion` (free text):+```+Any other marketing tools you'd like to connect?+ Examples: Postscript (SMS), Privy (popups), Triple Whale (attribution), Northbeam,+ Hotjar, Heap, Segment, Mixpanel, Mailchimp, ActiveCampaign, HubSpot+ Type names separated by commas, or leave blank to skip.+```++If the user provides partner names, apply the same dynamic partner loop as Step 3h.4 — for each partner:++1. **Research credentials** via web search: `"<partner name> API authentication developer docs 2025"`+2. **Ask for credentials** via `AskUserQuestion` with instructions sourced from the docs+3. **Smoke test** against the auth/health endpoint+4. **Save to preferences** under `marketing.partners.<partner_slug>`:+ ```json+ {+ "marketing": {+ "partners": {+ "triple-whale": {+ "api_base_url": "https://api.triplewhale.com/api/v2",+ "auth_pattern": "Authorization: Bearer <token>",+ "credentials": { "api_key": "doppler:TRIPLE_WHALE_API_KEY" },+ "health_endpoint": "/attribution/get-attribution-data",+ "configured_at": "<ISO timestamp>"+ }+ }+ }+ }+ ```+5. **Loop** — offer `[Add another]` / `[Done]` after each partner.++**Partners with known credential patterns** (use directly, still smoke test):++| Partner | Auth header | Base URL | Health endpoint |+| ------------- | -------------------------------------- | ---------------------------------------------- | ------------------- |+| HubSpot | `Authorization: Bearer <token>` | `https://api.hubapi.com` | `/crm/v3/objects/contacts?limit=1` |+| Mailchimp | `Authorization: Bearer <api_key>` | `https://<dc>.api.mailchimp.com/3.0` | `/ping` |+| Segment | `Authorization: Basic <base64_key:>` | `https://api.segment.io/v1` | n/a — use write key |+| Mixpanel | `Authorization: Basic <base64_secret:>` | `https://data.mixpanel.com/api/2.0` | `/engage?limit=1` |+| Postscript | `Authorization: ApiKey <key>` | `https://api.postscript.io/api/v2` | `/shops` |+| Triple Whale | `Authorization: Bearer <token>` | `https://api.triplewhale.com/api/v2` | `/attribution/get-attribution-data` |++For any partner not in this table, always web search for current auth docs before asking for credentials.++---++### 3j — Voice (Bland AI, ElevenLabs, Groq)++**Before showing the service selector**, run the Universal Credential Auto-Scan for all voice vars simultaneously:++```bash+# Shell env+printenv BLAND_AI_API_KEY BLAND_API_KEY ELEVENLABS_API_KEY GROQ_API_KEY 2>/dev/null++# Shell profiles+grep -h 'BLAND\|ELEVENLABS\|GROQ' ~/.zshrc ~/.bashrc ~/.zprofile ~/.envrc 2>/dev/null | grep -v '^#'++# Doppler across all projects+for proj in $(doppler projects --json 2>/dev/null | jq -r '.[].slug'); do+ doppler secrets --project "$proj" --config prd --json 2>/dev/null | \+ jq -r --arg proj "$proj" 'to_entries[] | select(.key | test("BLAND|ELEVENLABS|GROQ")) | "\(.key)=\(.value.computed) (doppler:\($proj)/prd)"'+done++# Dashlane+dcli password "bland-ai" --output json 2>/dev/null+dcli password elevenlabs --output json 2>/dev/null+dcli password groq --output json 2>/dev/null++# OpenClaw (common location for AI service keys)+jq -r '.agents.defaults.env | to_entries[] | select(.key | test("BLAND|ELEVENLABS|GROQ")) | "\(.key)=\(.value)"' ~/.openclaw/openclaw.json 2>/dev/null+```++Cache these results — use them to pre-fill answers for each sub-step below. Check existing config in `$PREFS_PATH` under `voice.*` too. If a key is already set, show `✓ <service> — already configured` and offer `[Keep]` / `[Reconfigure]`.++Ask which voice services to configure via `AskUserQuestion` with `multiSelect: true`:++| Option | Header | Description |+| ----------- | ----------- | ---------------------------------------------- |+| Bland AI | bland | Outbound AI phone calls — API key |+| ElevenLabs | elevenlabs | Text-to-speech and voice cloning — API key |+| Groq | groq | Fast LLM inference (Whisper, LLaMA) — API key |++#### Bland AI++If `BLAND_AI_API_KEY` or `BLAND_API_KEY` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format. Only ask via free text if not found:+```+Enter your Bland AI API Key:+ To find it: https://app.bland.ai → Settings → API Key+```++Smoke test:+```bash+curl -s -H "Authorization: $KEY" "https://api.bland.ai/v1/me" | jq '.user.id'+```+Expect a non-null user ID.++#### ElevenLabs++If `ELEVENLABS_API_KEY` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format. Only ask via free text if not found:+```+Enter your ElevenLabs API Key:+ To find it: https://elevenlabs.io → Profile (top-right) → API Key+```++Smoke test:+```bash+curl -s -H "xi-api-key: $KEY" "https://api.elevenlabs.io/v1/user" | jq '.subscription.tier'+```+Expect a subscription tier string (e.g. `"free"`, `"starter"`).++#### Groq++If `GROQ_API_KEY` was found in the auto-scan, present it using the Universal Credential Auto-Scan prompt format. Only ask via free text if not found:+```+Enter your Groq API Key:+ To generate one: https://console.groq.com → API Keys → Create API Key+ Key starts with "gsk_"+```++Smoke test:+```bash+curl -s -H "Authorization: Bearer $KEY" \+ "https://api.groq.com/openai/v1/models" | jq '.data | length'+```+Expect a positive integer (number of available models).++#### Save to preferences++Write to `$PREFS_PATH` (merge):+```json+{+ "voice": {+ "bland": { "api_key": "<key>" },+ "elevenlabs": { "api_key": "<key>" },+ "groq": { "api_key": "gsk_..." }+ }+}+```++Same Doppler-reference pattern — prefer `doppler:KEY_NAME` over raw tokens when Doppler is configured.++---++## Step 4 — Configure MCPs (if selected)++For each MCP that isn't in `mcp_configured`, print the one-line command the user should run:++```+Linear: claude mcp add linear+Sentry: claude mcp add sentry+Vercel: claude mcp add vercel+Slack: claude mcp add slack+Gmail: claude mcp add gmail (fallback only — prefer `gog` CLI, see Step 3c)+```++Offer `[Open Claude Code docs]`, `[Skip]`. Do **not** try to register MCPs from the skill — the plugin can't do that safely.++**Email note:** the ops plugin's primary email path is the `gog` CLI (full read + send, own OAuth). The Gmail MCP connector works as a fallback but **cannot send** without extra permission config in Claude Desktop → Settings → Connectors. The wizard handles that detection in Step 3c; this step only lists it so users who deliberately prefer MCP can install it here.++---++## Step 5 — Build the project registry (if selected)++### Auto-discover from filesystem++Before asking the user to manually enter projects, scan for existing git repositories:++```bash+find ~ ~/Projects -maxdepth 2 -name ".git" -type d 2>/dev/null | sed 's|/.git||' | sort+```++Present the discovered paths to the user via `AskUserQuestion` with `multiSelect: true`. **Max 4 options per call** — paginate at 3 projects per page + `[More...]` or `[None — I'll enter projects manually]` as the last option:++```+Found git repositories (page 1 of N):+ [ ] ~/Projects/my-app+ [ ] ~/Projects/my-api+ [ ] ~/Projects/my-ai+ [ ] More repositories...+```++On the final page, replace "More repositories..." with `[None of the above / Done selecting]`.++For each selected project, collect these fields one `AskUserQuestion` at a time:++- `alias` (short name, required — suggest the directory name as default)+- `org` (GitHub org or owner, e.g. `your-org` or `your-username`)+- `infra.platform` → select `[aws]`, `[vercel]`, `[cloudflare]`, `[other]`+- `revenue.model` → select in batches of 4: `[saas]`, `[subscription]`, `[marketplace]`, `[More...]` then `[internal]`, `[portfolio]`, `[other]`++### Existing registry++If `registry.json` already has projects, ask first (4 options, fits in one call): `[Keep existing N projects]`, `[Add more projects]`, `[Auto-detect from existing registry]`, `[Start from scratch]`.++- "Keep existing" → skip this step.+- "Auto-detect from existing registry" → re-read the registry, show a summary of what's already there, and offer to add missing fields or newly-discovered repos.+- "Start from scratch" → write an empty skeleton first (`{"version":"1.0","owner":"","projects":[]}`) — **prompt to confirm before overwriting**.+- "Add more" → run the auto-discover scan above, then offer manual entry as a fallback.++### Manual add loop++After auto-discovery (or if the user selects "I'll enter projects manually"):++- Ask `AskUserQuestion`: "Add another project?" → `[Yes]`, `[Done]`.+- If Yes, collect these fields **one `AskUserQuestion` at a time**:+ - `alias` (short name, required)+ - `paths` (comma-separated absolute paths, required)+ - `repos` (comma-separated `org/repo`, required)+ - `type` → select `[monorepo]`, `[multi-repo]`+ - `infra.platform` → select `[aws]`, `[vercel]`, `[cloudflare]`, `[other]`+ - `revenue.model` → select in batches of 4: `[saas]`, `[subscription]`, `[marketplace]`, `[More...]` then `[internal]`, `[portfolio]`, `[other]`+ - `revenue.stage` → select `[pre-launch]`, `[development]`, `[growth]`, `[active]`+ - `gsd` → select `[Yes]`, `[No]`+ - `priority` (1-99, defaults to max+1)+- Read the current registry with `jq`, append the new project, write back atomically (`jq ... > tmp && mv tmp registry.json`).+- After each addition, print the running count and offer `[Add another]` / `[Done]`.++---++## Step 5b — Background Daemon (if selected)++The ops-daemon manages persistent background services — WhatsApp sync, memory extraction, and future integrations — under a single launchd agent. It auto-heals on failure and writes a shared health file that all ops skills can read.++**What the daemon does:** Manages persistent connections (WhatsApp sync, memory extraction) and auto-heals on failure. All services run under a single launchd agent (`com.claude-ops.daemon`) that restarts itself if it crashes, with per-service health tracking written to `daemon-health.json`.++Ask the user via `AskUserQuestion`:++```+Install the ops background daemon?+ Manages background services persistently — recommended for reliable briefings and monitoring.+ Services enabled depend on what was configured earlier in setup.+ [Yes — install daemon] [Skip — use standalone keepalive instead]+```++If the user skips, fall back to the standalone keepalive path in Step 3b.7.++On `Yes`:++**1. Install and configure the daemon:**++```bash+DAEMON_SCRIPT="${CLAUDE_PLUGIN_ROOT}/scripts/ops-daemon.sh"+chmod +x "$DAEMON_SCRIPT"+PLIST_TEMPLATE="${CLAUDE_PLUGIN_ROOT}/scripts/com.claude-ops.daemon.plist"+PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.daemon.plist"+DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+LOG_DIR="$DATA_DIR/logs"+mkdir -p "$LOG_DIR"++# Generate plist+sed -e "s|__DAEMON_SCRIPT_PATH__|$DAEMON_SCRIPT|g" \+ -e "s|__LOG_DIR__|$LOG_DIR|g" \+ -e "s|__HOME__|$HOME|g" \+ "$PLIST_TEMPLATE" > "$PLIST_DEST"++# Copy default services config if none exists+SERVICES_CONFIG="$DATA_DIR/daemon-services.json"+if [[ ! -f "$SERVICES_CONFIG" ]]; then+ sed "s|__SCRIPTS_DIR__|${CLAUDE_PLUGIN_ROOT}/scripts|g" \+ "${CLAUDE_PLUGIN_ROOT}/scripts/daemon-services.default.json" > "$SERVICES_CONFIG"+fi++# Remove the old standalone wacli keepalive if present+launchctl bootout gui/$(id -u)/com.claude-ops.wacli-keepalive 2>/dev/null || true+rm -f "$HOME/Library/LaunchAgents/com.claude-ops.wacli-keepalive.plist"++# Load daemon+launchctl bootout gui/$(id -u) "$PLIST_DEST" 2>/dev/null || true+launchctl bootstrap gui/$(id -u) "$PLIST_DEST"+```++**2. Verify health after 5 seconds:**++```bash+cat "$DATA_DIR/daemon-health.json" 2>/dev/null+```++Parse the JSON. If `action_needed` is not null, surface the required action to the user. If the daemon wrote a health file, print:++```+✓ Background daemon — running (wacli-sync: connected, memory-extractor: scheduled)+```++If the health file is missing (daemon may still be initializing), wait 5 more seconds and retry once. If still missing, print:++```+⚠ Daemon started but health file not yet written. Check:+ launchctl print gui/$(id -u)/com.claude-ops.daemon+ tail -20 ~/.claude/plugins/data/ops-ops-marketplace/logs/ops-daemon.log+```++**3. Build the services list and record in preferences:**++Determine which services to enable based on what was configured in earlier steps:++- `wacli-sync` — always include if WhatsApp is configured (`channels.whatsapp` is set)+- `memory-extractor` — always include+- `inbox-digest` — always include (runs every 4h, aggregates all configured channels)+- `store-health` — include ONLY if ecommerce was configured (`ecom.shopify.store_url` is set in `$PREFS_PATH`)+- `competitor-intel` — always include (runs weekly Monday 10am)+- `message-listener` — include if WhatsApp or Telegram is configured (persistent poller)++Build the services array programmatically:+```bash+SERVICES='["memory-extractor","inbox-digest","competitor-intel"]'+PREFS=$(cat "$PREFS_PATH" 2>/dev/null || echo '{}')+# Add wacli-sync + message-listener if WhatsApp is configured+if echo "$PREFS" | jq -e '.channels.whatsapp' > /dev/null 2>&1; then+ SERVICES=$(echo "$SERVICES" | jq '. + ["wacli-sync","message-listener"]')+fi+# Add message-listener for Telegram too (deduplicate)+if echo "$PREFS" | jq -e '.channels.telegram' > /dev/null 2>&1; then+ SERVICES=$(echo "$SERVICES" | jq '. + ["message-listener"] | unique')+fi+# Add store-health only if Shopify is configured+if echo "$PREFS" | jq -e '.ecom.shopify.store_url' > /dev/null 2>&1; then+ SERVICES=$(echo "$SERVICES" | jq '. + ["store-health"]')+fi+echo "Services to enable: $SERVICES"+```++Write daemon services config to `$DATA_DIR/daemon-services.json` — merge with or replace the default, enabling only the services determined above. Each service entry should include:+- `wacli-sync`: `{ "enabled": true, "interval": "continuous" }`+- `memory-extractor`: `{ "enabled": true, "interval": "300" }` (every 5 min)+- `inbox-digest`: `{ "enabled": true, "schedule": "0 */4 * * *" }` (every 4h)+- `store-health`: `{ "enabled": true, "schedule": "0 9 * * *" }` (daily 9am) — only if ecom configured+- `competitor-intel`: `{ "enabled": true, "schedule": "0 10 * * 1" }` (weekly Monday 10am)+- `message-listener`: `{ "enabled": true, "interval": "continuous" }`++Write `daemon.enabled = true` and `daemon.services` (the computed array) to `$PREFS_PATH`.++---++## Step 6 — Save preferences (if selected)++Collect these via `AskUserQuestion` — one question each. **Never auto-fill from memory, existing configs, or previous sessions. Always ask explicitly.**++1. **Owner name** (free text): "What should Claude call you in briefings?" — no default, no suggestions from memory.++2. **Timezone** (single select — max 4 options per call, batch by region):++ First, detect the system timezone via `date +%Z` or `readlink /etc/localtime`. If detected, offer it as the first option:+ ```+ Select your timezone:+ [<detected timezone>]+ [Americas...]+ [Europe/Asia/Oceania...]+ [Other — type it]+ ```+ If user picks "Americas...": `[America/New_York]`, `[America/Los_Angeles]`, `[America/Chicago]`, `[Back]`+ If user picks "Europe/Asia/Oceania...": `[Europe/London]`, `[Asia/Bangkok]`, `[Asia/Tokyo]`, `[Australia/Sydney]`++3. **Briefing verbosity** (single select):+ ```+ How much detail do you want in briefings?+ [full] — complete rundown of all channels, projects, and incidents+ [compact] — key signals only, one line per item+ [minimal] — just the fires and urgent items+ ```++4. **Primary project** → select from registry aliases (skip if registry is empty).++5. **YOLO mode** → select `[Yes — auto-approve low-risk actions]`, `[No — always confirm]`.++6. **Default channels** (multiSelect over configured channels only — never show channels that weren't configured in Step 3):+ ```+ Which channels should ops skills use by default?+ [ ] telegram+ [ ] slack+ ```++Write to `$PREFS_PATH`:++```json+{+ "version": "1.0",+ "owner": "...",+ "primary_project": "...",+ "timezone": "...",+ "briefing_verbosity": "...",+ "yolo_enabled": false,+ "default_channels": ["whatsapp", "email"],+ "secrets_manager": "doppler",+ "doppler": {+ "project": "...",+ "config": "..."+ },+ "channels": {+ "telegram": { "bot_token": "...", "owner_id": "..." }+ }+}+```++If the file already exists, **merge** — don't overwrite. Read with `jq`, apply updates with `jq '. + { ... }'`, write back.++---++## Step 7 — Shell env (if selected)++1. Check whether `CLAUDE_PLUGIN_ROOT` is already exported in the profile file (grep for `CLAUDE_PLUGIN_ROOT`).+2. If missing, ask: "Append `export CLAUDE_PLUGIN_ROOT=...` to `~/.zshrc`?" → `[Yes]`, `[Skip — I'll do it manually]`.+3. If Yes, append (don't overwrite). Use `>>`, not `>`.+4. Tell the user to run `source ~/.zshrc` or open a new terminal for it to take effect.++---++## Step 8 — Final summary + validation++Re-run the detector and present a final status dashboard:++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► SETUP COMPLETE+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ ✓ Core CLIs: jq, git, gh, aws, node+ ✓ Channels: telegram, whatsapp, email+ ✓ Ecommerce: shopify (<store_url>) ← omit line if not configured+ ✓ Marketing: klaviyo, meta, ga4, gsc ← omit line if not configured+ ✓ Voice: bland, elevenlabs, groq ← omit line if not configured+ ✓ Secrets: doppler → my-app/dev+ ✓ MCPs: linear, sentry, vercel+ ✓ Registry: 20 projects+ ✓ Prefs: saved to ~/.claude/plugins/data/ops-ops-marketplace/preferences.json+ ✓ Daemon: ops-daemon → wacli-sync, memory-extractor, inbox-digest++ Next: /ops-go for your first briefing+──────────────────────────────────────────────────────+```++For each of ecommerce, marketing, and voice: only show the status line if at least one service was configured in that category. Use `✓` if configured, `○` if skipped. Omit the line entirely if the section was never visited.++For the daemon line, list only the services that were actually enabled (from the computed services array in Step 5b).++If any required tool is still missing, list it with the exact command to install it and stop short of claiming success.++After displaying the summary, run the completion banner to celebrate the successful setup. Pass the actual counts from the setup session:++```bash+bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-setup-complete --channels <N> --projects <N> --agents 9 --skills 15+```++Where `<N>` is replaced with the actual number of channels configured and projects registered during this session.++---++## Daemon Health Contract++All ops skills should check daemon health before relying on background services:++```bash+cat ~/.claude/plugins/data/ops-ops-marketplace/daemon-health.json+```++If `action_needed` is not null, surface the required action to the user before proceeding.+If the daemon is not running, offer to start it: `launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.claude-ops.daemon.plist`++---++## Invocation shortcuts++If `$ARGUMENTS` contains a specific section name, jump straight to that section:++| Argument | Go to |+| -------------------------------------- | ------- |+| `cli`, `install` | Step 2 |+| `channels` | Step 3 |+| `telegram` | Step 3a |+| `whatsapp`, `wacli`, `whatsapp-doctor` | Step 3b |+| `email` | Step 3c |+| `slack` | Step 3d |+| `calendar`, `cal` | Step 3e |+| `doppler`, `secrets` | Step 3f |+| `vault`, `password-manager`, `pm` | Step 3g |+| `ecom`, `shopify`, `store` | Step 3h |+| `marketing`, `klaviyo`, `ads`, `meta`, `ga4` | Step 3i |+| `voice`, `bland`, `elevenlabs`, `tts` | Step 3j |+| `mcp` | Step 4 |+| `registry`, `projects` | Step 5 |+| `daemon`, `background` | Step 5b |+| `prefs`, `preferences` | Step 6 |+| `env`, `shell` | Step 7 |++Empty argument → full wizard from Step 0.++---++## Safety++- **Never** run `brew install` or write files without an explicit `AskUserQuestion` confirmation.+- **Never** overwrite an existing file without showing the diff and asking.+- **Never** put secrets in `registry.json` or commit them. Secrets only go in `$PREFS_PATH` (outside the plugin source tree entirely — Claude Code's per-plugin data dir) or the user's shell profile.+- **Never** touch `~/.claude.json` or `~/.claude/settings.json` — MCP registration is Claude Code's job, not yours.+- **Never** show the user's real name or email in output unless they explicitly provided it in the current session. Do not read from memory files, existing preferences, or environment variables to populate display names.++---++## Appendix: CLI Reference (EXACT SYNTAX — never guess)++### gog (v0.12.0+)++```bash+# Auth check+gog auth status++# Gmail — probe if API works+gog gmail labels list --json++# Gmail — search (query is positional, NOT --query flag)+gog gmail search "newer_than:1d" --max 5 --json --results-only++# Gmail — read thread+gog gmail read THREAD_ID --json++# Gmail — send+gog gmail send --to "[email protected]" --subject "test" --body "hello"++# Gmail — archive (remove INBOX label)+gog gmail labels modify MESSAGE_ID --remove INBOX++# Calendar — list today's events (NOT --time-min, use `gog cal list`)+gog cal list --json --max 10++# Calendar — auth with calendar scope+gog auth login --scopes=gmail,calendar+```++### wacli++```bash+# Health check+wacli doctor --json++# Auth status+wacli auth status --json++# List chats (MUST use subcommand `list`)+wacli chats list --json++# List messages (--after flag uses YYYY-MM-DD)+# macOS+wacli messages list --after="$(date -v-1d +%Y-%m-%d)" --limit=5 --json+# Linux+wacli messages list --after="$(date -d '1 day ago' +%Y-%m-%d)" --limit=5 --json++# Send message+wacli send --to "JID" --message "text"++# Sync (connect and pull)+wacli sync++# Backfill history+wacli history backfill --chat="JID" --count=50 --requests=2 --wait=30s --idle-exit=5s --json++# Contact lookup+wacli contacts --search "name" --json+```++> After setup, the memory-extractor daemon service will populate `memories/contact_*.md` from this contact data.++### Slack token validation++```bash+curl -s -H "Authorization: Bearer XOXC_TOKEN" -b "d=XOXD_TOKEN" "https://slack.com/api/auth.test"+```++### macOS Keychain++```bash+security find-generic-password -s "KEY_NAME" -w 2>/dev/null+security add-generic-password -U -s "KEY_NAME" -a "$USER" -w "VALUE"+security delete-generic-password -s "KEY_NAME" 2>/dev/null+```diff --git a/claude-ops/skills/uninstall/SKILL.md b/claude-ops/skills/uninstall/SKILL.mdnew file mode 100644index 00000000..bdeac61e--- /dev/null+++ b/claude-ops/skills/uninstall/SKILL.md@@ -0,0 +1,181 @@+---+name: uninstall+description: Completely remove claude-ops plugin, all stored credentials, cached files, shell exports, and MCP registrations. Confirms each step before deletion.+argument-hint: "[--confirm]"+allowed-tools:+ - Bash+ - Read+ - AskUserQuestion+effort: low+maxTurns: 15+---++# OPS > UNINSTALL++You are running a **complete uninstall** of the claude-ops plugin. This removes everything the plugin and `/ops:setup` created. Every deletion step requires user confirmation via `AskUserQuestion` — never delete silently.++---++## Step 1 — Confirm intent++Use `AskUserQuestion`:++```+This will completely remove claude-ops and all its data:+ - Plugin installation and marketplace registration+ - Stored preferences and project registry+ - Cached plugin files+ - Keychain credentials (Telegram, Slack tokens)+ - Shell profile exports (CLAUDE_PLUGIN_ROOT)+ - MCP server registrations (Telegram, Slack)++ [Uninstall everything] [Cancel]+```++If cancelled, stop immediately.++---++## Step 2 — Detect what exists++Scan for all claude-ops artifacts. Build a list of what's present:++```bash+# Preferences+PREFS_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"+ls -la "$PREFS_DIR" 2>/dev/null++# Cache+CACHE_DIR="$HOME/.claude/plugins/cache/ops-marketplace"+ls -la "$CACHE_DIR" 2>/dev/null++# Keychain entries (macOS)+for key in telegram-api-id telegram-api-hash telegram-phone telegram-session slack-xoxc slack-xoxd; do+ security find-generic-password -s "$key" 2>/dev/null && echo "FOUND: $key"+done++# Shell profile exports+grep -l 'CLAUDE_PLUGIN_ROOT' ~/.zshrc ~/.bashrc ~/.zprofile ~/.bash_profile 2>/dev/null++# MCP registrations+grep -l 'telegram\|slack-mcp' ~/.claude.json 2>/dev/null+```++Print a summary of what was found, then proceed to delete each category.++---++## Step 3 — Remove keychain credentials++For each found keychain entry, ask via `AskUserQuestion`:++```+Remove keychain credential: <key-name>?+ [Yes] [Skip]+```++On Yes:++```bash+security delete-generic-password -s "<key-name>" 2>/dev/null+```++---++## Step 4 — Remove preferences and cache++Ask via `AskUserQuestion`:++```+Remove plugin data?+ - Preferences: <prefs-dir>+ - Cache: <cache-dir>++ [Yes, delete both] [Skip]+```++On Yes:++```bash+rm -rf "$PREFS_DIR"+rm -rf "$CACHE_DIR"+```++---++## Step 5 — Clean shell profile++For each shell profile file that contains `CLAUDE_PLUGIN_ROOT`:++Ask via `AskUserQuestion`:++```+Remove CLAUDE_PLUGIN_ROOT export from <file>?+ [Yes] [Skip]+```++On Yes, read the file and remove lines containing `CLAUDE_PLUGIN_ROOT`. Use `sed` or similar — do NOT rewrite the entire file. Only remove the specific export line.++```bash+sed -i '' '/CLAUDE_PLUGIN_ROOT/d' "<file>"+```++---++## Step 6 — Remove MCP registrations++Check if `~/.claude.json` contains MCP server entries added by the plugin (telegram, slack-mcp). For each:++Ask via `AskUserQuestion`:++```+Remove MCP server registration: <server-name> from ~/.claude.json?+ [Yes] [Skip]+```++On Yes, use `jq` to remove the entry:++```bash+jq 'del(.mcpServers["<server-name>"])' ~/.claude.json > /tmp/claude-json-tmp && mv /tmp/claude-json-tmp ~/.claude.json+```++---++## Step 7 — Uninstall plugin and marketplace++Run the Claude Code uninstall commands:++```bash+claude plugin uninstall ops@lifecycle-innovations-limited-claude-ops 2>/dev/null || true+claude plugin marketplace remove lifecycle-innovations-limited-claude-ops 2>/dev/null || true+```++If these commands fail (e.g. not in an interactive Claude Code session), print:++```+Run these manually in Claude Code:+ /plugin uninstall ops@lifecycle-innovations-limited-claude-ops+ /plugin marketplace remove lifecycle-innovations-limited-claude-ops+```++---++## Step 8 — Final confirmation++Print:++```+claude-ops has been completely removed.++ Keychain: <N> credentials deleted+ Preferences: deleted+ Cache: deleted+ Shell: <N> exports removed+ MCP: <N> servers removed+ Plugin: uninstalled++To reinstall later:+ /plugin marketplace add Lifecycle-Innovations-Limited/claude-ops+ /plugin install ops@lifecycle-innovations-limited-claude-ops+ /ops:setup+```diff --git a/claude-ops/telegram-server/README.md b/claude-ops/telegram-server/README.mdnew file mode 100644index 00000000..35b40f53--- /dev/null+++ b/claude-ops/telegram-server/README.md@@ -0,0 +1,91 @@+# claude-ops Telegram MCP Server++User-auth Telegram MCP server for the `/ops:ops-inbox` skill. Authenticates as a **personal Telegram account** via MTProto (gram.js), not as a BotFather bot, so it can read and reply to real DM conversations.++## Why user-auth, not bot?++Bots cannot read messages sent in private chats between two users — only messages sent directly to the bot. For the `/ops:ops-inbox` use case (managing the owner's personal inbox), we must authenticate as the user's account.++## Setup++### 1. Get API credentials++Go to https://my.telegram.org/apps and create a **personal** application (not a bot). You'll get:++- `api_id` (integer)+- `api_hash` (32-char string)++### 2. Install dependencies++```bash+cd claude-ops/telegram-server+npm install+```++### 3. First-run authentication (interactive)++```bash+TELEGRAM_API_ID=12345 \+TELEGRAM_API_HASH=abcdef... \+TELEGRAM_PHONE=+15551234567 \+node index.js --auth+```++The script will prompt for an SMS code and (if enabled) your 2FA password. On success it prints a `TELEGRAM_SESSION` string — save this securely (it's your session token).++### 4. Configure MCP server in Claude Code++Add to `~/.claude/settings.json`:++```json+{+ "mcpServers": {+ "telegram": {+ "command": "node",+ "args": ["/path/to/claude-ops/telegram-server/index.js"],+ "env": {+ "TELEGRAM_API_ID": "${TELEGRAM_API_ID}",+ "TELEGRAM_API_HASH": "${TELEGRAM_API_HASH}",+ "TELEGRAM_SESSION": "${TELEGRAM_SESSION}",+ "TELEGRAM_PHONE": "${TELEGRAM_PHONE}"+ }+ }+ }+}+```++Export the env vars from a secret manager (Doppler, 1Password, direnv — **never commit**):++```bash+export TELEGRAM_API_ID="..."+export TELEGRAM_API_HASH="..."+export TELEGRAM_SESSION="..." # from step 3+export TELEGRAM_PHONE="+1..."+export TELEGRAM_ENABLED=true # enables in ops-unread detection+```++Restart Claude Code to load the MCP server.++## Tools++| Tool | Description |+| ----------------- | -------------------------------------------------------------------- |+| `list_dialogs` | List recent conversations (DMs, groups, channels) with unread counts |+| `get_messages` | Fetch messages from a specific chat |+| `send_message` | Send a message to a chat or user |+| `search_messages` | Full-text search across all conversations |++## Security++- **Never commit `TELEGRAM_SESSION`** — it's equivalent to your password+- Session tokens are device-bound; if stolen, log out via Telegram app → Settings → Devices+- All credentials come from environment variables; nothing is hardcoded in this repo+- The server runs over stdio (local only); no network exposure beyond Telegram's official API++## Troubleshooting++**"Session is no longer valid"**: Re-run `node index.js --auth` to generate a fresh session.++**"TELEGRAM_API_ID is required"**: The env vars aren't being passed to the MCP server. Check your `~/.claude/settings.json` env block.++**Rate limiting**: Telegram enforces per-account limits. If you hit one, wait 15-30 minutes before retrying.diff --git a/claude-ops/telegram-server/auth-with-chat-db.mjs b/claude-ops/telegram-server/auth-with-chat-db.mjsnew file mode 100644index 00000000..633dec61--- /dev/null+++ b/claude-ops/telegram-server/auth-with-chat-db.mjs@@ -0,0 +1,87 @@+#!/usr/bin/env node+// Auto-auth: read Telegram code from /tmp/telegram-code.txt (file-based input).+import { TelegramClient } from "telegram";+import { StringSession } from "telegram/sessions/index.js";+import { readFileSync, writeFileSync, existsSync, unlinkSync } from "node:fs";++const API_ID = parseInt(process.env.TELEGRAM_API_ID, 10);+const API_HASH = process.env.TELEGRAM_API_HASH;+const PHONE = process.env.TELEGRAM_PHONE;+const CODE_FILE = "/tmp/telegram-code.txt";++if (existsSync(CODE_FILE)) unlinkSync(CODE_FILE);++if (!API_ID || !API_HASH || !PHONE) {+ console.error("missing env");+ process.exit(1);+}++function readFileCode() {+ if (existsSync(CODE_FILE)) {+ const c = readFileSync(CODE_FILE, "utf8").trim();+ if (/^\d{4,8}$/.test(c)) return c;+ }+ return null;+}++async function waitForCode(maxSec = 180) {+ const start = Date.now();+ let lastLog = 0;+ while (Date.now() - start < maxSec * 1000) {+ const code = readFileCode();+ if (code) {+ console.error(`code found: ${code}`);+ return code;+ }+ if (Date.now() - lastLog > 10000) {+ console.error(+ `waiting for code — write to ${CODE_FILE} (${Math.floor((Date.now() - start) / 1000)}s)`,+ );+ lastLog = Date.now();+ }+ await new Promise((r) => setTimeout(r, 2000));+ }+ throw new Error("timeout");+}++const stringSession = new StringSession("");+const client = new TelegramClient(stringSession, API_ID, API_HASH, {+ connectionRetries: 5,+ baseLogger: {+ log: () => {},+ warn: () => {},+ error: (...a) => console.error(...a),+ info: () => {},+ debug: () => {},+ },+});++await client.start({+ phoneNumber: async () => PHONE,+ password: async () => {+ console.error("2FA: empty");+ return "";+ },+ phoneCode: async () => {+ console.error("Telegram sent code; waiting for /tmp/telegram-code.txt");+ return await waitForCode(180);+ },+ onError: (err) => console.error("auth err:", err.message),+});++const saved = client.session.save();+console.log("=== SESSION STRING ===");+console.log(saved);+console.log("=== END ===");+// 0o600: /tmp is world-readable on macOS (drwxrwxrwt). Without this mode+// any local process could read the session string during the window between+// write and whoever reads it next.+writeFileSync("/tmp/telegram-session.txt", saved, { mode: 0o600 });+// writeFileSync mode only applies to NEW files; if it already existed,+// chmod explicitly.+try {+ (await import("node:fs")).chmodSync("/tmp/telegram-session.txt", 0o600);+} catch {}+console.error("session saved to /tmp/telegram-session.txt (0600)");+await client.disconnect();+process.exit(0);diff --git a/claude-ops/telegram-server/index.js b/claude-ops/telegram-server/index.jsnew file mode 100644index 00000000..14879a86--- /dev/null+++ b/claude-ops/telegram-server/index.js@@ -0,0 +1,372 @@+#!/usr/bin/env node+/**+ * Telegram MCP Server for claude-ops (USER-AUTH, not bot)+ *+ * Uses gram.js MTProto to authenticate as a personal Telegram account,+ * allowing access to real DM conversations — not just bot interactions.+ *+ * Required env vars:+ * TELEGRAM_API_ID — from https://my.telegram.org/apps+ * TELEGRAM_API_HASH — from https://my.telegram.org/apps+ * TELEGRAM_SESSION — persisted string session (populated after first auth)+ * TELEGRAM_PHONE — phone number (E.164 format, e.g. +15551234567)+ *+ * First-run auth:+ * Run `node index.js --auth` in a terminal. It will prompt for the SMS code+ * and 2FA password, then print a TELEGRAM_SESSION string to save to env.+ *+ * Tools exposed:+ * list_dialogs — list recent conversations (DMs, groups, channels)+ * get_messages — fetch messages from a specific chat+ * send_message — send a message to a chat+ * search_messages — full-text search across all chats+ */++import { Server } from "@modelcontextprotocol/sdk/server/index.js";+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import {+ CallToolRequestSchema,+ ListToolsRequestSchema,+} from "@modelcontextprotocol/sdk/types.js";+import { TelegramClient } from "telegram";+import { StringSession } from "telegram/sessions/index.js";+import readline from "node:readline/promises";+import { stdin as input, stdout as output } from "node:process";++const API_ID = parseInt(process.env.TELEGRAM_API_ID || "0", 10);+const API_HASH = process.env.TELEGRAM_API_HASH || "";+const SESSION_STRING = process.env.TELEGRAM_SESSION || "";+const PHONE = process.env.TELEGRAM_PHONE || "";++// Detect whether credentials are present — server always starts regardless+const CONFIGURED = !!(API_ID && API_HASH && SESSION_STRING);+const NOT_CONFIGURED_MSG =+ "Telegram not configured. Run /ops:setup telegram to set up your credentials.";++let client = null;++if (CONFIGURED) {+ // First-run interactive auth mode (only when creds are available)+ if (process.argv.includes("--auth")) {+ const stringSession = new StringSession(SESSION_STRING);+ const authClient = new TelegramClient(stringSession, API_ID, API_HASH, {+ connectionRetries: 5,+ baseLogger: {+ log: () => {},+ warn: () => {},+ error: (...args) => process.stderr.write(args.join(" ") + "\n"),+ info: () => {},+ debug: () => {},+ },+ });+ const rl = readline.createInterface({ input, output });+ await authClient.start({+ phoneNumber: async () =>+ PHONE || (await rl.question("Phone number (E.164): ")),+ password: async () =>+ await rl.question("2FA password (blank if none): "),+ phoneCode: async () => await rl.question("SMS code: "),+ onError: (err) => process.stderr.write(`Auth error: ${err.message}\n`),+ });+ rl.close();+ const saved = authClient.session.save();+ process.stdout.write("\n=== AUTH SUCCESSFUL ===\n");+ process.stdout.write("Save this to TELEGRAM_SESSION env var:\n\n");+ process.stdout.write(saved + "\n");+ await authClient.disconnect();+ process.exit(0);+ }++ // Connect using saved session+ const stringSession = new StringSession(SESSION_STRING);+ client = new TelegramClient(stringSession, API_ID, API_HASH, {+ connectionRetries: 5,+ baseLogger: {+ log: () => {},+ warn: () => {},+ error: (...args) => process.stderr.write(args.join(" ") + "\n"),+ info: () => {},+ debug: () => {},+ },+ });++ try {+ await client.connect();+ if (!(await client.checkAuthorization())) {+ process.stderr.write(+ "Warning: Telegram session is no longer valid. Re-run `node index.js --auth`.\n",+ );+ client = null;+ }+ } catch (err) {+ process.stderr.write(+ `Warning: Failed to connect to Telegram: ${err.message}\n`,+ );+ client = null;+ }+} else {+ process.stderr.write(+ "Telegram credentials not set — server starting in unconfigured mode.\n",+ );+}++// ── MCP server setup ──+const server = new Server(+ { name: "claude-ops-telegram", version: "0.2.0" },+ { capabilities: { tools: {} } },+);++server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: [+ {+ name: "list_dialogs",+ description:+ "List recent Telegram conversations (DMs, groups, channels). Returns last-message preview, sender, timestamp, and unread count.",+ inputSchema: {+ type: "object",+ properties: {+ limit: {+ type: "number",+ description: "Max dialogs to return (default 30, max 100)",+ },+ archived: {+ type: "boolean",+ description: "Include archived dialogs (default false)",+ },+ },+ required: [],+ },+ },+ {+ name: "get_messages",+ description:+ "Fetch recent messages from a specific chat. Use chat_id from list_dialogs or a username like @example.",+ inputSchema: {+ type: "object",+ properties: {+ chat: {+ type: "string",+ description: "Chat ID (numeric) or @username",+ },+ limit: {+ type: "number",+ description: "Number of messages to fetch (default 20, max 100)",+ },+ },+ required: ["chat"],+ },+ },+ {+ name: "send_message",+ description:+ "Send a message to a Telegram chat or user (personal account, not bot).",+ inputSchema: {+ type: "object",+ properties: {+ chat: {+ type: "string",+ description: "Chat ID (numeric) or @username",+ },+ text: {+ type: "string",+ description: "Message text (supports Markdown)",+ },+ },+ required: ["chat", "text"],+ },+ },+ {+ name: "search_messages",+ description: "Full-text search across all Telegram conversations.",+ inputSchema: {+ type: "object",+ properties: {+ query: {+ type: "string",+ description: "Search query text",+ },+ limit: {+ type: "number",+ description: "Max results (default 20)",+ },+ },+ required: ["query"],+ },+ },+ ],+}));++function formatPeer(entity) {+ if (!entity) return "Unknown";+ if (entity.title) return entity.title;+ const first = entity.firstName || "";+ const last = entity.lastName || "";+ const name = `${first} ${last}`.trim();+ if (name) return name;+ if (entity.username) return `@${entity.username}`;+ return String(entity.id || "Unknown");+}++function resolveChatArg(chat) {+ // Accept numeric ID or @username+ if (/^-?\d+$/.test(chat)) return parseInt(chat, 10);+ return chat.startsWith("@") ? chat : `@${chat}`;+}++server.setRequestHandler(CallToolRequestSchema, async (request) => {+ const { name, arguments: args } = request.params;++ if (!client) {+ return {+ content: [{ type: "text", text: NOT_CONFIGURED_MSG }],+ isError: true,+ };+ }++ try {+ if (name === "list_dialogs") {+ const limit = Math.min(args?.limit || 30, 100);+ const includeArchived = args?.archived || false;++ const dialogs = await client.getDialogs({+ limit,+ archived: includeArchived,+ });++ const formatted = dialogs.map((d) => {+ const peer = formatPeer(d.entity);+ const lastMsg = d.message;+ const fromMe = lastMsg?.out || false;+ const text = lastMsg?.message || "[non-text message]";+ const ts = lastMsg?.date+ ? new Date(lastMsg.date * 1000).toISOString()+ : "";+ return {+ chat_id: String(d.id),+ name: peer,+ type: d.isChannel ? "channel" : d.isGroup ? "group" : "dm",+ unread: d.unreadCount || 0,+ last_message: {+ from_me: fromMe,+ text: text.slice(0, 200),+ timestamp: ts,+ },+ };+ });++ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(+ { dialogs: formatted, count: formatted.length },+ null,+ 2,+ ),+ },+ ],+ };+ }++ if (name === "get_messages") {+ const chat = resolveChatArg(args.chat);+ const limit = Math.min(args?.limit || 20, 100);++ const messages = await client.getMessages(chat, { limit });++ const formatted = messages.map((m) => ({+ id: m.id,+ from_me: m.out,+ sender: formatPeer(m.sender),+ text: m.message || "[non-text message]",+ timestamp: m.date ? new Date(m.date * 1000).toISOString() : "",+ }));++ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(+ { messages: formatted, count: formatted.length },+ null,+ 2,+ ),+ },+ ],+ };+ }++ if (name === "send_message") {+ const chat = resolveChatArg(args.chat);+ const result = await client.sendMessage(chat, { message: args.text });++ return {+ content: [+ {+ type: "text",+ text: `Message sent. ID: ${result.id}, to: ${chat}`,+ },+ ],+ };+ }++ if (name === "search_messages") {+ const limit = Math.min(args?.limit || 20, 100);+ // gram.js messages.search on global scope+ const { Api } = await import("telegram");+ const results = await client.invoke(+ new Api.messages.SearchGlobal({+ q: args.query,+ filter: new Api.InputMessagesFilterEmpty(),+ minDate: 0,+ maxDate: 0,+ offsetRate: 0,+ offsetPeer: new Api.InputPeerEmpty(),+ offsetId: 0,+ limit,+ }),+ );++ const msgs = (results.messages || []).map((m) => ({+ id: m.id,+ text: m.message || "[non-text]",+ timestamp: m.date ? new Date(m.date * 1000).toISOString() : "",+ from_me: m.out || false,+ }));++ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(+ { results: msgs, count: msgs.length },+ null,+ 2,+ ),+ },+ ],+ };+ }++ throw new Error(`Unknown tool: ${name}`);+ } catch (error) {+ return {+ content: [{ type: "text", text: `Error: ${error.message}` }],+ isError: true,+ };+ }+});++const transport = new StdioServerTransport();+await server.connect(transport);+process.stderr.write("Telegram MCP server running (user-auth mode)\n");++// Graceful shutdown+process.on("SIGINT", async () => {+ if (client) await client.disconnect();+ process.exit(0);+});+process.on("SIGTERM", async () => {+ if (client) await client.disconnect();+ process.exit(0);+});diff --git a/claude-ops/telegram-server/package-lock.json b/claude-ops/telegram-server/package-lock.jsonnew file mode 100644index 00000000..3e4b574d--- /dev/null+++ b/claude-ops/telegram-server/package-lock.json@@ -0,0 +1,1702 @@+{+ "name": "claude-ops-telegram-server",+ "version": "0.2.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "claude-ops-telegram-server",+ "version": "0.2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.0.0",+ "playwright": "^1.59.1",+ "telegram": "^2.26.22"+ },+ "bin": {+ "claude-ops-telegram": "index.js"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@cryptography/aes": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/@cryptography/aes/-/aes-0.1.1.tgz",+ "integrity": "sha512-PcYz4FDGblO6tM2kSC+VzhhK62vml6k6/YAkiWtyPvrgJVfnDRoHGDtKn5UiaRRUrvUTTocBpvc2rRgTCqxjsg==",+ "license": "GPL-3.0-or-later"+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.13",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.13.tgz",+ "integrity": "sha512-TsQLe4i2gvoTtrHje625ngThGBySOgSK3Xo2XRYOdqGN1teR8+I7vchQC46uLJi8OF62YTYA3AhSpumtkhsaKQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ajv": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",+ "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/async-mutex": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz",+ "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.3.1"+ }+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/big-integer": {+ "version": "1.6.52",+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",+ "license": "Unlicense",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/buffer": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.2.1"+ }+ },+ "node_modules/bufferutil": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.1.0.tgz",+ "integrity": "sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/d": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz",+ "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==",+ "license": "ISC",+ "dependencies": {+ "es5-ext": "^0.10.64",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/dom-serializer": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz",+ "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==",+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.0.1",+ "domhandler": "^4.2.0",+ "entities": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"+ }+ },+ "node_modules/domelementtype": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "BSD-2-Clause"+ },+ "node_modules/domhandler": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz",+ "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "domelementtype": "^2.2.0"+ },+ "engines": {+ "node": ">= 4"+ },+ "funding": {+ "url": "https://github.com/fb55/domhandler?sponsor=1"+ }+ },+ "node_modules/domutils": {+ "version": "2.8.0",+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",+ "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "dom-serializer": "^1.0.1",+ "domelementtype": "^2.2.0",+ "domhandler": "^4.2.0"+ },+ "funding": {+ "url": "https://github.com/fb55/domutils?sponsor=1"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/entities": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",+ "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==",+ "license": "BSD-2-Clause",+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es5-ext": {+ "version": "0.10.64",+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz",+ "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==",+ "hasInstallScript": true,+ "license": "ISC",+ "dependencies": {+ "es6-iterator": "^2.0.3",+ "es6-symbol": "^3.1.3",+ "esniff": "^2.0.1",+ "next-tick": "^1.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/es6-iterator": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",+ "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "^0.10.35",+ "es6-symbol": "^3.1.1"+ }+ },+ "node_modules/es6-symbol": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz",+ "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.2",+ "ext": "^1.7.0"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/esniff": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz",+ "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==",+ "license": "ISC",+ "dependencies": {+ "d": "^1.0.1",+ "es5-ext": "^0.10.62",+ "event-emitter": "^0.3.5",+ "type": "^2.7.2"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/event-emitter": {+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",+ "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==",+ "license": "MIT",+ "dependencies": {+ "d": "1",+ "es5-ext": "~0.10.14"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.3.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.2.tgz",+ "integrity": "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "10.1.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/ext": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz",+ "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==",+ "license": "ISC",+ "dependencies": {+ "type": "^2.7.2"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "license": "ISC"+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.12",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz",+ "integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/htmlparser2": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz",+ "integrity": "sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A==",+ "funding": [+ "https://github.com/fb55/htmlparser2?sponsor=1",+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.0.1",+ "domhandler": "^4.0.0",+ "domutils": "^2.5.2",+ "entities": "^2.0.0"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",+ "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/is-typedarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",+ "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.2.tgz",+ "integrity": "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mime": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=10.0.0"+ }+ },+ "node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/next-tick": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz",+ "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==",+ "license": "ISC"+ },+ "node_modules/node-gyp-build": {+ "version": "4.8.4",+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",+ "license": "MIT",+ "bin": {+ "node-gyp-build": "bin.js",+ "node-gyp-build-optional": "optional.js",+ "node-gyp-build-test": "build-test.js"+ }+ },+ "node_modules/node-localstorage": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-2.2.1.tgz",+ "integrity": "sha512-vv8fJuOUCCvSPjDjBLlMqYMHob4aGjkmrkaE42/mZr0VT+ZAU10jRF8oTnX9+pgU9/vYJ8P7YT3Vd6ajkmzSCw==",+ "license": "MIT",+ "dependencies": {+ "write-file-atomic": "^1.1.4"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/pako": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",+ "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",+ "license": "(MIT AND Zlib)"+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-browserify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",+ "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",+ "license": "MIT"+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",+ "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.59.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",+ "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/real-cancellable-promise": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/real-cancellable-promise/-/real-cancellable-promise-1.2.3.tgz",+ "integrity": "sha512-hBI5Gy/55VEeeMtImMgEirD7eq5UmqJf1J8dFZtbJZA/3rB0pYFZ7PayMGueb6v4UtUtpKpP+05L0VwyE1hI9Q==",+ "license": "MIT"+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/slide": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz",+ "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==",+ "license": "ISC",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/smart-buffer": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/socks": {+ "version": "2.8.7",+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",+ "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.0.1",+ "smart-buffer": "^4.2.0"+ },+ "engines": {+ "node": ">= 10.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/store2": {+ "version": "2.14.4",+ "resolved": "https://registry.npmjs.org/store2/-/store2-2.14.4.tgz",+ "integrity": "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw==",+ "license": "MIT"+ },+ "node_modules/telegram": {+ "version": "2.26.22",+ "resolved": "https://registry.npmjs.org/telegram/-/telegram-2.26.22.tgz",+ "integrity": "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg==",+ "license": "MIT",+ "dependencies": {+ "@cryptography/aes": "^0.1.1",+ "async-mutex": "^0.3.0",+ "big-integer": "^1.6.48",+ "buffer": "^6.0.3",+ "htmlparser2": "^6.1.0",+ "mime": "^3.0.0",+ "node-localstorage": "^2.2.1",+ "pako": "^2.0.3",+ "path-browserify": "^1.0.1",+ "real-cancellable-promise": "^1.1.1",+ "socks": "^2.6.2",+ "store2": "^2.13.0",+ "ts-custom-error": "^3.2.0",+ "websocket": "^1.0.34"+ },+ "optionalDependencies": {+ "bufferutil": "^4.0.3",+ "utf-8-validate": "^5.0.5"+ }+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/ts-custom-error": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",+ "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type": {+ "version": "2.7.3",+ "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz",+ "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==",+ "license": "ISC"+ },+ "node_modules/type-is": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^1.0.5",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/typedarray-to-buffer": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz",+ "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==",+ "license": "MIT",+ "dependencies": {+ "is-typedarray": "^1.0.0"+ }+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/utf-8-validate": {+ "version": "5.0.10",+ "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",+ "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-gyp-build": "^4.3.0"+ },+ "engines": {+ "node": ">=6.14.2"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/websocket": {+ "version": "1.0.35",+ "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz",+ "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "bufferutil": "^4.0.1",+ "debug": "^2.2.0",+ "es5-ext": "^0.10.63",+ "typedarray-to-buffer": "^3.1.5",+ "utf-8-validate": "^5.0.2",+ "yaeti": "^0.0.6"+ },+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/websocket/node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/websocket/node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/write-file-atomic": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz",+ "integrity": "sha512-SdrHoC/yVBPpV0Xq/mUZQIpW2sWXAShb/V4pomcJXh92RuaO+f3UTWItiR3Px+pLnV2PvC2/bfn5cwr5X6Vfxw==",+ "license": "ISC",+ "dependencies": {+ "graceful-fs": "^4.1.11",+ "imurmurhash": "^0.1.4",+ "slide": "^1.1.5"+ }+ },+ "node_modules/yaeti": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz",+ "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.32"+ }+ },+ "node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }+ }+ }+}diff --git a/claude-ops/telegram-server/package.json b/claude-ops/telegram-server/package.jsonnew file mode 100644index 00000000..04abe3b6--- /dev/null+++ b/claude-ops/telegram-server/package.json@@ -0,0 +1,22 @@+{+ "name": "claude-ops-telegram-server",+ "version": "0.2.0",+ "description": "Telegram user-auth MCP server for claude-ops plugin (personal account via MTProto, not bots)",+ "type": "module",+ "main": "index.js",+ "bin": {+ "claude-ops-telegram": "./index.js"+ },+ "scripts": {+ "start": "node index.js",+ "auth": "node index.js --auth"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.0.0",+ "playwright": "^1.59.1",+ "telegram": "^2.26.22"+ },+ "engines": {+ "node": ">=18.0.0"+ }+}diff --git a/claude-ops/templates/shopify-admin-app/.dockerignore b/claude-ops/templates/shopify-admin-app/.dockerignorenew file mode 100644index 00000000..78e1a231--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.dockerignore@@ -0,0 +1,3 @@+.cache+build+node_modulesdiff --git a/claude-ops/templates/shopify-admin-app/.editorconfig b/claude-ops/templates/shopify-admin-app/.editorconfignew file mode 100644index 00000000..c9fe4a74--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.editorconfig@@ -0,0 +1,15 @@+# editorconfig.org+root = true++[*]+charset = utf-8+indent_size = 2+indent_style = space+insert_final_newline = true+trim_trailing_whitespace = true++# Markdown syntax specifies that trailing whitespaces can be meaningful,+# so let’s not trim those. e.g. 2 trailing spaces = linebreak (<br />)+# See https://daringfireball.net/projects/markdown/syntax#p+[*.md]+trim_trailing_whitespace = falsediff --git a/claude-ops/templates/shopify-admin-app/.eslintignore b/claude-ops/templates/shopify-admin-app/.eslintignorenew file mode 100644index 00000000..3796499f--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.eslintignore@@ -0,0 +1,6 @@+node_modules+build+public/build+shopify-app-remix+*/*.yml+.shopifydiff --git a/claude-ops/templates/shopify-admin-app/.eslintrc.cjs b/claude-ops/templates/shopify-admin-app/.eslintrc.cjsnew file mode 100644index 00000000..a42d9754--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.eslintrc.cjs@@ -0,0 +1,13 @@+/** @type {import('@types/eslint').Linter.BaseConfig} */+module.exports = {+ root: true,+ extends: [+ "@remix-run/eslint-config",+ "@remix-run/eslint-config/node",+ "@remix-run/eslint-config/jest-testing-library",+ "prettier",+ ],+ globals: {+ shopify: "readonly"+ },+};diff --git a/claude-ops/templates/shopify-admin-app/.gitignore b/claude-ops/templates/shopify-admin-app/.gitignorenew file mode 100644index 00000000..abb6caf8--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.gitignore@@ -0,0 +1,25 @@+node_modules+.DS_Store++/.cache+/build+/app/build+/public/build/+/public/_dev+/app/public/build+/prisma/dev.sqlite+/prisma/dev.sqlite-journal+database.sqlite++.env+.env.*++package-lock.json+yarn.lock+pnpm-lock.yaml++/extensions/*/dist++# Ignore shopify files created during app dev+.shopify/*+.shopify.lockdiff --git a/claude-ops/templates/shopify-admin-app/.graphqlrc.ts b/claude-ops/templates/shopify-admin-app/.graphqlrc.tsnew file mode 100644index 00000000..c46b6d0f--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.graphqlrc.ts@@ -0,0 +1,45 @@+import fs from "fs";+import { ApiVersion } from "@shopify/shopify-api";+import { shopifyApiProject, ApiType } from "@shopify/api-codegen-preset";+import type { IGraphQLConfig } from "graphql-config";++function getConfig() {+ const config: IGraphQLConfig = {+ projects: {+ default: shopifyApiProject({+ apiType: ApiType.Admin,+ apiVersion: ApiVersion.July25,+ documents: [+ "./app/**/*.{js,ts,jsx,tsx}",+ "./app/.server/**/*.{js,ts,jsx,tsx}",+ ],+ outputDir: "./app/types",+ }),+ },+ };++ let extensions: string[] = [];+ try {+ extensions = fs.readdirSync("./extensions");+ } catch {+ // ignore if no extensions+ }++ for (const entry of extensions) {+ const extensionPath = `./extensions/${entry}`;+ const schema = `${extensionPath}/schema.graphql`;+ if (!fs.existsSync(schema)) {+ continue;+ }+ config.projects[entry] = {+ schema,+ documents: [`${extensionPath}/**/*.graphql`],+ };+ }++ return config;+}++const config = getConfig();++export default config;diff --git a/claude-ops/templates/shopify-admin-app/.npmrc b/claude-ops/templates/shopify-admin-app/.npmrcnew file mode 100644index 00000000..00928d65--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.npmrc@@ -0,0 +1,2 @@+engine-strict=true+@shopify:registry=https://registry.npmjs.orgdiff --git a/claude-ops/templates/shopify-admin-app/.prettierignore b/claude-ops/templates/shopify-admin-app/.prettierignorenew file mode 100644index 00000000..82667c50--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/.prettierignore@@ -0,0 +1,7 @@+package.json+.shadowenv.d+.vscode+node_modules+prisma+public+.shopifydiff --git a/claude-ops/templates/shopify-admin-app/Dockerfile b/claude-ops/templates/shopify-admin-app/Dockerfilenew file mode 100644index 00000000..07bc9cf7--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/Dockerfile@@ -0,0 +1,21 @@+FROM node:18-alpine+RUN apk add --no-cache openssl++EXPOSE 3000++WORKDIR /app++ENV NODE_ENV=production++COPY package.json package-lock.json* ./++RUN npm ci --omit=dev && npm cache clean --force+# Remove CLI packages since we don't need them in production by default.+# Remove this line if you want to run CLI commands in your container.+RUN npm remove @shopify/cli++COPY . .++RUN npm run build++CMD ["npm", "run", "docker-start"]diff --git a/claude-ops/templates/shopify-admin-app/README.md b/claude-ops/templates/shopify-admin-app/README.mdnew file mode 100644index 00000000..829e2182--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/README.md@@ -0,0 +1,352 @@+# Shopify App Template - Remix++> [!NOTE]+> **Remix is now React Router.** As of [React Router v7](https://remix.run/blog/merging-remix-and-react-router), Remix and React Router have merged.+>+> For new projects, use the **[Shopify App Template - React Router](https://github.com/Shopify/shopify-app-template-react-router)** instead.+>+> To migrate your existing Remix app, follow the **[migration guide](https://github.com/Shopify/shopify-app-template-react-router/wiki/Upgrading-from-Remix)**.++This is a template for building a [Shopify app](https://shopify.dev/docs/apps/getting-started) using the [Remix](https://remix.run) framework.++Rather than cloning this repo, you can use your preferred package manager and the Shopify CLI with [these steps](https://shopify.dev/docs/apps/getting-started/create).++Visit the [`shopify.dev` documentation](https://shopify.dev/docs/api/shopify-app-remix) for more details on the Remix app package.++## Quick start++### Prerequisites++Before you begin, you'll need the following:++1. **Node.js**: [Download and install](https://nodejs.org/en/download/) it if you haven't already.+2. **Shopify Partner Account**: [Create an account](https://partners.shopify.com/signup) if you don't have one.+3. **Test Store**: Set up either a [development store](https://help.shopify.com/en/partners/dashboard/development-stores#create-a-development-store) or a [Shopify Plus sandbox store](https://help.shopify.com/en/partners/dashboard/managing-stores/plus-sandbox-store) for testing your app.+4. **Shopify CLI**: [Download and install](https://shopify.dev/docs/apps/tools/cli/getting-started) it if you haven't already.+```shell+npm install -g @shopify/cli@latest+```++### Setup++```shell+shopify app init --template=https://github.com/Shopify/shopify-app-template-remix+```++### Local Development++```shell+shopify app dev+```++++Local development is powered by [the Shopify CLI](https://shopify.dev/docs/apps/tools/cli). It logs into your partners account, connects to an app, provides environment variables, updates remote config, creates a tunnel and provides commands to generate extensions.++### Authenticating and querying data++To authenticate and query data you can use the `shopify` const that is exported from `/app/shopify.server.js`:++```js+export async function loader({ request }) {+ const { admin } = await shopify.authenticate.admin(request);++ const response = await admin.graphql(`+ {+ products(first: 25) {+ nodes {+ title+ description+ }+ }+ }`);++ const {+ data: {+ products: { nodes },+ },+ } = await response.json();++ return nodes;+}+```++This template comes preconfigured with examples of:++1. Setting up your Shopify app in [/app/shopify.server.ts](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/shopify.server.ts)+2. Querying data using Graphql. Please see: [/app/routes/app.\_index.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/app._index.tsx).+3. Responding to webhooks in individual files such as [/app/routes/webhooks.app.uninstalled.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/webhooks.app.uninstalled.tsx) and [/app/routes/webhooks.app.scopes_update.tsx](https://github.com/Shopify/shopify-app-template-remix/blob/main/app/routes/webhooks.app.scopes_update.tsx)++Please read the [documentation for @shopify/shopify-app-remix](https://www.npmjs.com/package/@shopify/shopify-app-remix#authenticating-admin-requests) to understand what other API's are available.++## Deployment++### Application Storage++This template uses [Prisma](https://www.prisma.io/) to store session data, by default using an [SQLite](https://www.sqlite.org/index.html) database.+The database is defined as a Prisma schema in `prisma/schema.prisma`.++This use of SQLite works in production if your app runs as a single instance.+The database that works best for you depends on the data your app needs and how it is queried.+You can run your database of choice on a server yourself or host it with a SaaS company.+Here's a short list of databases providers that provide a free tier to get started:++| Database | Type | Hosters |+| ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| MySQL | SQL | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-mysql), [Planet Scale](https://planetscale.com/), [Amazon Aurora](https://aws.amazon.com/rds/aurora/), [Google Cloud SQL](https://cloud.google.com/sql/docs/mysql) |+| PostgreSQL | SQL | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-postgresql), [Amazon Aurora](https://aws.amazon.com/rds/aurora/), [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres) |+| Redis | Key-value | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-redis), [Amazon MemoryDB](https://aws.amazon.com/memorydb/) |+| MongoDB | NoSQL / Document | [Digital Ocean](https://www.digitalocean.com/products/managed-databases-mongodb), [MongoDB Atlas](https://www.mongodb.com/atlas/database) |++To use one of these, you can use a different [datasource provider](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#datasource) in your `schema.prisma` file, or a different [SessionStorage adapter package](https://github.com/Shopify/shopify-api-js/blob/main/packages/shopify-api/docs/guides/session-storage.md).++### Build++Remix handles building the app for you, by running the command below with the package manager of your choice:++Using yarn:++```shell+yarn build+```++Using npm:++```shell+npm run build+```++Using pnpm:++```shell+pnpm run build+```++## Hosting++When you're ready to set up your app in production, you can follow [our deployment documentation](https://shopify.dev/docs/apps/deployment/web) to host your app on a cloud provider like [Heroku](https://www.heroku.com/) or [Fly.io](https://fly.io/).++When you reach the step for [setting up environment variables](https://shopify.dev/docs/apps/deployment/web#set-env-vars), you also need to set the variable `NODE_ENV=production`.++### Hosting on Vercel++Using the Vercel Preset is recommended when hosting your Shopify Remix app on Vercel. You'll also want to ensure imports that would normally come from `@remix-run/node` are imported from `@vercel/remix` instead. Learn more about hosting Remix apps on Vercel [here](https://vercel.com/docs/frameworks/remix).++```diff+// vite.config.ts+import { vitePlugin as remix } from "@remix-run/dev";+import { defineConfig, type UserConfig } from "vite";+import tsconfigPaths from "vite-tsconfig-paths";++ import { vercelPreset } from '@vercel/remix/vite';++installGlobals();++export default defineConfig({+ plugins: [+ remix({+ ignoredRouteFiles: ["**/.*"],++ presets: [vercelPreset()],+ }),+ tsconfigPaths(),+ ],+});+```++## Troubleshooting++### Database tables don't exist++If you get this error:++```+The table `main.Session` does not exist in the current database.+```++You need to create the database for Prisma. Run the `setup` script in `package.json` using your preferred package manager.++### Navigating/redirecting breaks an embedded app++Embedded Shopify apps must maintain the user session, which can be tricky inside an iFrame. To avoid issues:++1. Use `Link` from `@remix-run/react` or `@shopify/polaris`. Do not use `<a>`.+2. Use the `redirect` helper returned from `authenticate.admin`. Do not use `redirect` from `@remix-run/node`+3. Use `useSubmit` or `<Form/>` from `@remix-run/react`. Do not use a lowercase `<form/>`.++This only applies if your app is embedded, which it will be by default.++### Non Embedded++Shopify apps are best when they are embedded in the Shopify Admin, which is how this template is configured. If you have a reason to not embed your app please make the following changes:++1. Ensure `embedded = false` is set in [shopify.app.toml`](./shopify.app.toml). [Docs here](https://shopify.dev/docs/apps/build/cli-for-apps/app-configuration#global).+2. Pass `isEmbeddedApp: false` to `shopifyApp()` in `./app/shopify.server.js|ts`.+3. Change the `isEmbeddedApp` prop to `isEmbeddedApp={false}` for the `AppProvider` in `/app/routes/app.jsx|tsx`.+4. Remove the `@shopify/app-bridge-react` dependency from [package.json](./package.json) and `vite.config.ts|js`.+5. Remove anything imported from `@shopify/app-bridge-react`. For example: `NavMenu`, `TitleBar` and `useAppBridge`.++### OAuth goes into a loop when I change my app's scopes++If you change your app's scopes and authentication goes into a loop and fails with a message from Shopify that it tried too many times, you might have forgotten to update your scopes with Shopify.+To do that, you can run the `deploy` CLI command.++Using yarn:++```shell+yarn deploy+```++Using npm:++```shell+npm run deploy+```++Using pnpm:++```shell+pnpm run deploy+```++### My shop-specific webhook subscriptions aren't updated++If you are registering webhooks in the `afterAuth` hook, using `shopify.registerWebhooks`, you may find that your subscriptions aren't being updated.++Instead of using the `afterAuth` hook, the recommended approach is to declare app-specific webhooks in the `shopify.app.toml` file. This approach is easier since Shopify will automatically update changes to webhook subscriptions every time you run `deploy` (e.g: `npm run deploy`). Please read these guides to understand more:++1. [app-specific vs shop-specific webhooks](https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-subscriptions)+2. [Create a subscription tutorial](https://shopify.dev/docs/apps/build/webhooks/subscribe/get-started?framework=remix&deliveryMethod=https)++If you do need shop-specific webhooks, please keep in mind that the package calls `afterAuth` in 2 scenarios:++- After installing the app+- When an access token expires++During normal development, the app won't need to re-authenticate most of the time, so shop-specific subscriptions aren't updated. To force your app to update the subscriptions, you can uninstall and reinstall it in your development store. That will force the OAuth process and call the `afterAuth` hook.++### Admin created webhook failing HMAC validation++Webhooks subscriptions created in the [Shopify admin](https://help.shopify.com/en/manual/orders/notifications/webhooks) will fail HMAC validation. This is because the webhook payload is not signed with your app's secret key. There are 2 solutions:++1. Use [app-specific webhooks](https://shopify.dev/docs/apps/build/webhooks/subscribe#app-specific-subscriptions) defined in your toml file instead (recommended)+2. Create [webhook subscriptions](https://shopify.dev/docs/api/shopify-app-remix/v1/guide-webhooks) using the `shopifyApp` object.++Test your webhooks with the [Shopify CLI](https://shopify.dev/docs/apps/tools/cli/commands#webhook-trigger) or by triggering events manually in the Shopify admin(e.g. Updating the product title to trigger a `PRODUCTS_UPDATE`).++### Incorrect GraphQL Hints++By default the [graphql.vscode-graphql](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) extension for VS Code will assume that GraphQL queries or mutations are for the [Shopify Admin API](https://shopify.dev/docs/api/admin). This is a sensible default, but it may not be true if:++1. You use another Shopify API such as the storefront API.+2. You use a third party GraphQL API.++in this situation, please update the [.graphqlrc.ts](https://github.com/Shopify/shopify-app-template-remix/blob/main/.graphqlrc.ts) config.++### First parameter has member 'readable' that is not a ReadableStream.++See [hosting on Vercel](#hosting-on-vercel).++### Admin object undefined on webhook events triggered by the CLI++When you trigger a webhook event using the Shopify CLI, the `admin` object will be `undefined`. This is because the CLI triggers an event with a valid, but non-existent, shop. The `admin` object is only available when the webhook is triggered by a shop that has installed the app.++Webhooks triggered by the CLI are intended for initial experimentation testing of your webhook configuration. For more information on how to test your webhooks, see the [Shopify CLI documentation](https://shopify.dev/docs/apps/tools/cli/commands#webhook-trigger).++### Using Defer & await for streaming responses++To test [streaming using defer/await](https://remix.run/docs/en/main/guides/streaming) during local development you'll need to use the Shopify CLI slightly differently:++1. First setup ngrok: https://ngrok.com/product/secure-tunnels+2. Create an ngrok tunnel on port 8080: `ngrok http 8080`.+3. Copy the forwarding address. This should be something like: `https://f355-2607-fea8-bb5c-8700-7972-d2b5-3f2b-94ab.ngrok-free.app`+4. In a separate terminal run `yarn shopify app dev --tunnel-url=TUNNEL_URL:8080` replacing `TUNNEL_URL` for the address you copied in step 3.++By default the CLI uses a cloudflare tunnel. Unfortunately it cloudflare tunnels wait for the Response stream to finish, then sends one chunk.++This will not affect production, since tunnels are only for local development.++### Using MongoDB and Prisma++By default this template uses SQLlite as the database. It is recommended to move to a persisted database for production. If you choose to use MongoDB, you will need to make some modifications to the schema and prisma configuration. For more information please see the [Prisma MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb).++Alternatively you can use a MongDB database directly with the [MongoDB session storage adapter](https://github.com/Shopify/shopify-app-js/tree/main/packages/apps/session-storage/shopify-app-session-storage-mongodb).++#### Mapping the id field++In MongoDB, an ID must be a single field that defines an @id attribute and a @map("\_id") attribute.+The prisma adapter expects the ID field to be the ID of the session, and not the \_id field of the document.++To make this work you can add a new field to the schema that maps the \_id field to the id field. For more information see the [Prisma documentation](https://www.prisma.io/docs/orm/prisma-schema/data-model/models#defining-an-id-field)++```prisma+model Session {+ session_id String @id @default(auto()) @map("_id") @db.ObjectId+ id String @unique+...+}+```++#### Error: The "mongodb" provider is not supported with this command++MongoDB does not support the [prisma migrate](https://www.prisma.io/docs/orm/prisma-migrate/understanding-prisma-migrate/overview) command. Instead, you can use the [prisma db push](https://www.prisma.io/docs/orm/reference/prisma-cli-reference#db-push) command and update the `shopify.web.toml` file with the following commands. If you are using MongoDB please see the [Prisma documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb) for more information.++```toml+[commands]+predev = "npx prisma generate && npx prisma db push"+dev = "npm exec remix vite:dev"+```++#### Prisma needs to perform transactions, which requires your mongodb server to be run as a replica set++See the [Prisma documentation](https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb/connect-your-database-node-mongodb) for connecting to a MongoDB database.++### I want to use Polaris v13.0.0 or higher++Currently, this template is set up to work on node v18.20 or higher. However, `@shopify/polaris` is limited to v12 because v13 can only run on node v20+.++You don't have to make any changes to the code in order to be able to upgrade Polaris to v13, but you'll need to do the following:++- Upgrade your node version to v20.10 or higher.+- Update your `Dockerfile` to pull `FROM node:20-alpine` instead of `node:18-alpine`++### "nbf" claim timestamp check failed++This error will occur of the `nbf` claim timestamp check failed. This is because the JWT token is expired.+If you are consistently getting this error, it could be that the clock on your machine is not in sync with the server.++To fix this ensure you have enabled `Set time and date automatically` in the `Date and Time` settings on your computer.++## Benefits++Shopify apps are built on a variety of Shopify tools to create a great merchant experience.++<!-- TODO: Uncomment this after we've updated the docs -->+<!-- The [create an app](https://shopify.dev/docs/apps/getting-started/create) tutorial in our developer documentation will guide you through creating a Shopify app using this template. -->++The Remix app template comes with the following out-of-the-box functionality:++- [OAuth](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-admin-requests): Installing the app and granting permissions+- [GraphQL Admin API](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#using-the-shopify-admin-graphql-api): Querying or mutating Shopify admin data+- [Webhooks](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-webhook-requests): Callbacks sent by Shopify when certain events occur+- [AppBridge](https://shopify.dev/docs/api/app-bridge): This template uses the next generation of the Shopify App Bridge library which works in unison with previous versions.+- [Polaris](https://polaris.shopify.com/): Design system that enables apps to create Shopify-like experiences++## Tech Stack++This template uses [Remix](https://remix.run). The following Shopify tools are also included to ease app development:++- [Shopify App Remix](https://shopify.dev/docs/api/shopify-app-remix) provides authentication and methods for interacting with Shopify APIs.+- [Shopify App Bridge](https://shopify.dev/docs/apps/tools/app-bridge) allows your app to seamlessly integrate your app within Shopify's Admin.+- [Polaris React](https://polaris.shopify.com/) is a powerful design system and component library that helps developers build high quality, consistent experiences for Shopify merchants.+- [Webhooks](https://github.com/Shopify/shopify-app-js/tree/main/packages/shopify-app-remix#authenticating-webhook-requests): Callbacks sent by Shopify when certain events occur+- [Polaris](https://polaris.shopify.com/): Design system that enables apps to create Shopify-like experiences++## Resources++- [Remix Docs](https://remix.run/docs/en/v1)+- [Shopify App Remix](https://shopify.dev/docs/api/shopify-app-remix)+- [Introduction to Shopify apps](https://shopify.dev/docs/apps/getting-started)+- [App authentication](https://shopify.dev/docs/apps/auth)+- [Shopify CLI](https://shopify.dev/docs/apps/tools/cli)+- [App extensions](https://shopify.dev/docs/apps/app-extensions/list)+- [Shopify Functions](https://shopify.dev/docs/api/functions)+- [Getting started with internationalizing your app](https://shopify.dev/docs/apps/best-practices/internationalization/getting-started)diff --git a/claude-ops/templates/shopify-admin-app/app/db.server.ts b/claude-ops/templates/shopify-admin-app/app/db.server.tsnew file mode 100644index 00000000..a0d5575f--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/db.server.ts@@ -0,0 +1,15 @@+import { PrismaClient } from "@prisma/client";++declare global {+ var prismaGlobal: PrismaClient;+}++if (process.env.NODE_ENV !== "production") {+ if (!global.prismaGlobal) {+ global.prismaGlobal = new PrismaClient();+ }+}++const prisma = global.prismaGlobal ?? new PrismaClient();++export default prisma;diff --git a/claude-ops/templates/shopify-admin-app/app/entry.server.tsx b/claude-ops/templates/shopify-admin-app/app/entry.server.tsxnew file mode 100644index 00000000..86274311--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/entry.server.tsx@@ -0,0 +1,59 @@+import { PassThrough } from "stream";+import { renderToPipeableStream } from "react-dom/server";+import { RemixServer } from "@remix-run/react";+import {+ createReadableStreamFromReadable,+ type EntryContext,+} from "@remix-run/node";+import { isbot } from "isbot";+import { addDocumentResponseHeaders } from "./shopify.server";++export const streamTimeout = 5000;++export default async function handleRequest(+ request: Request,+ responseStatusCode: number,+ responseHeaders: Headers,+ remixContext: EntryContext+) {+ addDocumentResponseHeaders(request, responseHeaders);+ const userAgent = request.headers.get("user-agent");+ const callbackName = isbot(userAgent ?? '')+ ? "onAllReady"+ : "onShellReady";++ return new Promise((resolve, reject) => {+ const { pipe, abort } = renderToPipeableStream(+ <RemixServer+ context={remixContext}+ url={request.url}+ />,+ {+ [callbackName]: () => {+ const body = new PassThrough();+ const stream = createReadableStreamFromReadable(body);++ responseHeaders.set("Content-Type", "text/html");+ resolve(+ new Response(stream, {+ headers: responseHeaders,+ status: responseStatusCode,+ })+ );+ pipe(body);+ },+ onShellError(error) {+ reject(error);+ },+ onError(error) {+ responseStatusCode = 500;+ console.error(error);+ },+ }+ );++ // Automatically timeout the React renderer after 6 seconds, which ensures+ // React has enough time to flush down the rejected boundary contents+ setTimeout(abort, streamTimeout + 1000);+ });+}diff --git a/claude-ops/templates/shopify-admin-app/app/globals.d.ts b/claude-ops/templates/shopify-admin-app/app/globals.d.tsnew file mode 100644index 00000000..cbe652db--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/globals.d.ts@@ -0,0 +1 @@+declare module "*.css";diff --git a/claude-ops/templates/shopify-admin-app/app/root.tsx b/claude-ops/templates/shopify-admin-app/app/root.tsxnew file mode 100644index 00000000..805f121f--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/root.tsx@@ -0,0 +1,30 @@+import {+ Links,+ Meta,+ Outlet,+ Scripts,+ ScrollRestoration,+} from "@remix-run/react";++export default function App() {+ return (+ <html>+ <head>+ <meta charSet="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <link rel="preconnect" href="https://cdn.shopify.com/" />+ <link+ rel="stylesheet"+ href="https://cdn.shopify.com/static/fonts/inter/v4/styles.css"+ />+ <Meta />+ <Links />+ </head>+ <body>+ <Outlet />+ <ScrollRestoration />+ <Scripts />+ </body>+ </html>+ );+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes.ts b/claude-ops/templates/shopify-admin-app/app/routes.tsnew file mode 100644index 00000000..83892841--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes.ts@@ -0,0 +1,3 @@+import { flatRoutes } from "@remix-run/fs-routes";++export default flatRoutes();diff --git a/claude-ops/templates/shopify-admin-app/app/routes/_index/route.tsx b/claude-ops/templates/shopify-admin-app/app/routes/_index/route.tsxnew file mode 100644index 00000000..2de9dd47--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/_index/route.tsx@@ -0,0 +1,58 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { Form, useLoaderData } from "@remix-run/react";++import { login } from "../../shopify.server";++import styles from "./styles.module.css";++export const loader = async ({ request }: LoaderFunctionArgs) => {+ const url = new URL(request.url);++ if (url.searchParams.get("shop")) {+ throw redirect(`/app?${url.searchParams.toString()}`);+ }++ return { showForm: Boolean(login) };+};++export default function App() {+ const { showForm } = useLoaderData<typeof loader>();++ return (+ <div className={styles.index}>+ <div className={styles.content}>+ <h1 className={styles.heading}>A short heading about [your app]</h1>+ <p className={styles.text}>+ A tagline about [your app] that describes your value proposition.+ </p>+ {showForm && (+ <Form className={styles.form} method="post" action="/auth/login">+ <label className={styles.label}>+ <span>Shop domain</span>+ <input className={styles.input} type="text" name="shop" />+ <span>e.g: my-shop-domain.myshopify.com</span>+ </label>+ <button className={styles.button} type="submit">+ Log in+ </button>+ </Form>+ )}+ <ul className={styles.list}>+ <li>+ <strong>Product feature</strong>. Some detail about your feature and+ its benefit to your customer.+ </li>+ <li>+ <strong>Product feature</strong>. Some detail about your feature and+ its benefit to your customer.+ </li>+ <li>+ <strong>Product feature</strong>. Some detail about your feature and+ its benefit to your customer.+ </li>+ </ul>+ </div>+ </div>+ );+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/_index/styles.module.css b/claude-ops/templates/shopify-admin-app/app/routes/_index/styles.module.cssnew file mode 100644index 00000000..271721fd--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/_index/styles.module.css@@ -0,0 +1,73 @@+.index {+ align-items: center;+ display: flex;+ justify-content: center;+ height: 100%;+ width: 100%;+ text-align: center;+ padding: 1rem;+}++.heading,+.text {+ padding: 0;+ margin: 0;+}++.text {+ font-size: 1.2rem;+ padding-bottom: 2rem;+}++.content {+ display: grid;+ gap: 2rem;+}++.form {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ margin: 0 auto;+ gap: 1rem;+}++.label {+ display: grid;+ gap: 0.2rem;+ max-width: 20rem;+ text-align: left;+ font-size: 1rem;+}++.input {+ padding: 0.4rem;+}++.button {+ padding: 0.4rem;+}++.list {+ list-style: none;+ padding: 0;+ padding-top: 3rem;+ margin: 0;+ display: flex;+ gap: 2rem;+}++.list > li {+ max-width: 20rem;+ text-align: left;+}++@media only screen and (max-width: 50rem) {+ .list {+ display: block;+ }++ .list > li {+ padding-bottom: 1rem;+ }+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/app._index.tsx b/claude-ops/templates/shopify-admin-app/app/routes/app._index.tsxnew file mode 100644index 00000000..18b215b0--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/app._index.tsx@@ -0,0 +1,334 @@+import { useEffect } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";+import { useFetcher } from "@remix-run/react";+import {+ Page,+ Layout,+ Text,+ Card,+ Button,+ BlockStack,+ Box,+ List,+ Link,+ InlineStack,+} from "@shopify/polaris";+import { TitleBar, useAppBridge } from "@shopify/app-bridge-react";+import { authenticate } from "../shopify.server";++export const loader = async ({ request }: LoaderFunctionArgs) => {+ await authenticate.admin(request);++ return null;+};++export const action = async ({ request }: ActionFunctionArgs) => {+ const { admin } = await authenticate.admin(request);+ const color = ["Red", "Orange", "Yellow", "Green"][+ Math.floor(Math.random() * 4)+ ];+ const response = await admin.graphql(+ `#graphql+ mutation populateProduct($product: ProductCreateInput!) {+ productCreate(product: $product) {+ product {+ id+ title+ handle+ status+ variants(first: 10) {+ edges {+ node {+ id+ price+ barcode+ createdAt+ }+ }+ }+ }+ }+ }`,+ {+ variables: {+ product: {+ title: `${color} Snowboard`,+ },+ },+ },+ );+ const responseJson = await response.json();++ const product = responseJson.data!.productCreate!.product!;+ const variantId = product.variants.edges[0]!.node!.id!;++ const variantResponse = await admin.graphql(+ `#graphql+ mutation shopifyRemixTemplateUpdateVariant($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {+ productVariantsBulkUpdate(productId: $productId, variants: $variants) {+ productVariants {+ id+ price+ barcode+ createdAt+ }+ }+ }`,+ {+ variables: {+ productId: product.id,+ variants: [{ id: variantId, price: "100.00" }],+ },+ },+ );++ const variantResponseJson = await variantResponse.json();++ return {+ product: responseJson!.data!.productCreate!.product,+ variant:+ variantResponseJson!.data!.productVariantsBulkUpdate!.productVariants,+ };+};++export default function Index() {+ const fetcher = useFetcher<typeof action>();++ const shopify = useAppBridge();+ const isLoading =+ ["loading", "submitting"].includes(fetcher.state) &&+ fetcher.formMethod === "POST";+ const productId = fetcher.data?.product?.id.replace(+ "gid://shopify/Product/",+ "",+ );++ useEffect(() => {+ if (productId) {+ shopify.toast.show("Product created");+ }+ }, [productId, shopify]);+ const generateProduct = () => fetcher.submit({}, { method: "POST" });++ return (+ <Page>+ <TitleBar title="Remix app template">+ <button variant="primary" onClick={generateProduct}>+ Generate a product+ </button>+ </TitleBar>+ <BlockStack gap="500">+ <Layout>+ <Layout.Section>+ <Card>+ <BlockStack gap="500">+ <BlockStack gap="200">+ <Text as="h2" variant="headingMd">+ Congrats on creating a new Shopify app 🎉+ </Text>+ <Text variant="bodyMd" as="p">+ This embedded app template uses{" "}+ <Link+ url="https://shopify.dev/docs/apps/tools/app-bridge"+ target="_blank"+ removeUnderline+ >+ App Bridge+ </Link>{" "}+ interface examples like an{" "}+ <Link url="/app/additional" removeUnderline>+ additional page in the app nav+ </Link>+ , as well as an{" "}+ <Link+ url="https://shopify.dev/docs/api/admin-graphql"+ target="_blank"+ removeUnderline+ >+ Admin GraphQL+ </Link>{" "}+ mutation demo, to provide a starting point for app+ development.+ </Text>+ </BlockStack>+ <BlockStack gap="200">+ <Text as="h3" variant="headingMd">+ Get started with products+ </Text>+ <Text as="p" variant="bodyMd">+ Generate a product with GraphQL and get the JSON output for+ that product. Learn more about the{" "}+ <Link+ url="https://shopify.dev/docs/api/admin-graphql/latest/mutations/productCreate"+ target="_blank"+ removeUnderline+ >+ productCreate+ </Link>{" "}+ mutation in our API references.+ </Text>+ </BlockStack>+ <InlineStack gap="300">+ <Button loading={isLoading} onClick={generateProduct}>+ Generate a product+ </Button>+ {fetcher.data?.product && (+ <Button+ url={`shopify:admin/products/${productId}`}+ target="_blank"+ variant="plain"+ >+ View product+ </Button>+ )}+ </InlineStack>+ {fetcher.data?.product && (+ <>+ <Text as="h3" variant="headingMd">+ {" "}+ productCreate mutation+ </Text>+ <Box+ padding="400"+ background="bg-surface-active"+ borderWidth="025"+ borderRadius="200"+ borderColor="border"+ overflowX="scroll"+ >+ <pre style={{ margin: 0 }}>+ <code>+ {JSON.stringify(fetcher.data.product, null, 2)}+ </code>+ </pre>+ </Box>+ <Text as="h3" variant="headingMd">+ {" "}+ productVariantsBulkUpdate mutation+ </Text>+ <Box+ padding="400"+ background="bg-surface-active"+ borderWidth="025"+ borderRadius="200"+ borderColor="border"+ overflowX="scroll"+ >+ <pre style={{ margin: 0 }}>+ <code>+ {JSON.stringify(fetcher.data.variant, null, 2)}+ </code>+ </pre>+ </Box>+ </>+ )}+ </BlockStack>+ </Card>+ </Layout.Section>+ <Layout.Section variant="oneThird">+ <BlockStack gap="500">+ <Card>+ <BlockStack gap="200">+ <Text as="h2" variant="headingMd">+ App template specs+ </Text>+ <BlockStack gap="200">+ <InlineStack align="space-between">+ <Text as="span" variant="bodyMd">+ Framework+ </Text>+ <Link+ url="https://remix.run"+ target="_blank"+ removeUnderline+ >+ Remix+ </Link>+ </InlineStack>+ <InlineStack align="space-between">+ <Text as="span" variant="bodyMd">+ Database+ </Text>+ <Link+ url="https://www.prisma.io/"+ target="_blank"+ removeUnderline+ >+ Prisma+ </Link>+ </InlineStack>+ <InlineStack align="space-between">+ <Text as="span" variant="bodyMd">+ Interface+ </Text>+ <span>+ <Link+ url="https://polaris.shopify.com"+ target="_blank"+ removeUnderline+ >+ Polaris+ </Link>+ {", "}+ <Link+ url="https://shopify.dev/docs/apps/tools/app-bridge"+ target="_blank"+ removeUnderline+ >+ App Bridge+ </Link>+ </span>+ </InlineStack>+ <InlineStack align="space-between">+ <Text as="span" variant="bodyMd">+ API+ </Text>+ <Link+ url="https://shopify.dev/docs/api/admin-graphql"+ target="_blank"+ removeUnderline+ >+ GraphQL API+ </Link>+ </InlineStack>+ </BlockStack>+ </BlockStack>+ </Card>+ <Card>+ <BlockStack gap="200">+ <Text as="h2" variant="headingMd">+ Next steps+ </Text>+ <List>+ <List.Item>+ Build an{" "}+ <Link+ url="https://shopify.dev/docs/apps/getting-started/build-app-example"+ target="_blank"+ removeUnderline+ >+ {" "}+ example app+ </Link>{" "}+ to get started+ </List.Item>+ <List.Item>+ Explore Shopify’s API with{" "}+ <Link+ url="https://shopify.dev/docs/apps/tools/graphiql-admin-api"+ target="_blank"+ removeUnderline+ >+ GraphiQL+ </Link>+ </List.Item>+ </List>+ </BlockStack>+ </Card>+ </BlockStack>+ </Layout.Section>+ </Layout>+ </BlockStack>+ </Page>+ );+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/app.additional.tsx b/claude-ops/templates/shopify-admin-app/app/routes/app.additional.tsxnew file mode 100644index 00000000..eb9b0cfd--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/app.additional.tsx@@ -0,0 +1,83 @@+import {+ Box,+ Card,+ Layout,+ Link,+ List,+ Page,+ Text,+ BlockStack,+} from "@shopify/polaris";+import { TitleBar } from "@shopify/app-bridge-react";++export default function AdditionalPage() {+ return (+ <Page>+ <TitleBar title="Additional page" />+ <Layout>+ <Layout.Section>+ <Card>+ <BlockStack gap="300">+ <Text as="p" variant="bodyMd">+ The app template comes with an additional page which+ demonstrates how to create multiple pages within app navigation+ using{" "}+ <Link+ url="https://shopify.dev/docs/apps/tools/app-bridge"+ target="_blank"+ removeUnderline+ >+ App Bridge+ </Link>+ .+ </Text>+ <Text as="p" variant="bodyMd">+ To create your own page and have it show up in the app+ navigation, add a page inside <Code>app/routes</Code>, and a+ link to it in the <Code><NavMenu></Code> component found+ in <Code>app/routes/app.jsx</Code>.+ </Text>+ </BlockStack>+ </Card>+ </Layout.Section>+ <Layout.Section variant="oneThird">+ <Card>+ <BlockStack gap="200">+ <Text as="h2" variant="headingMd">+ Resources+ </Text>+ <List>+ <List.Item>+ <Link+ url="https://shopify.dev/docs/apps/design-guidelines/navigation#app-nav"+ target="_blank"+ removeUnderline+ >+ App nav best practices+ </Link>+ </List.Item>+ </List>+ </BlockStack>+ </Card>+ </Layout.Section>+ </Layout>+ </Page>+ );+}++function Code({ children }: { children: React.ReactNode }) {+ return (+ <Box+ as="span"+ padding="025"+ paddingInlineStart="100"+ paddingInlineEnd="100"+ background="bg-surface-active"+ borderWidth="025"+ borderColor="border"+ borderRadius="100"+ >+ <code>{children}</code>+ </Box>+ );+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/app.tsx b/claude-ops/templates/shopify-admin-app/app/routes/app.tsxnew file mode 100644index 00000000..bdcf1162--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/app.tsx@@ -0,0 +1,41 @@+import type { HeadersFunction, LoaderFunctionArgs } from "@remix-run/node";+import { Link, Outlet, useLoaderData, useRouteError } from "@remix-run/react";+import { boundary } from "@shopify/shopify-app-remix/server";+import { AppProvider } from "@shopify/shopify-app-remix/react";+import { NavMenu } from "@shopify/app-bridge-react";+import polarisStyles from "@shopify/polaris/build/esm/styles.css?url";++import { authenticate } from "../shopify.server";++export const links = () => [{ rel: "stylesheet", href: polarisStyles }];++export const loader = async ({ request }: LoaderFunctionArgs) => {+ await authenticate.admin(request);++ return { apiKey: process.env.SHOPIFY_API_KEY || "" };+};++export default function App() {+ const { apiKey } = useLoaderData<typeof loader>();++ return (+ <AppProvider isEmbeddedApp apiKey={apiKey}>+ <NavMenu>+ <Link to="/app" rel="home">+ Home+ </Link>+ <Link to="/app/additional">Additional page</Link>+ </NavMenu>+ <Outlet />+ </AppProvider>+ );+}++// Shopify needs Remix to catch some thrown responses, so that their headers are included in the response.+export function ErrorBoundary() {+ return boundary.error(useRouteError());+}++export const headers: HeadersFunction = (headersArgs) => {+ return boundary.headers(headersArgs);+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/auth.$.tsx b/claude-ops/templates/shopify-admin-app/app/routes/auth.$.tsxnew file mode 100644index 00000000..8919320d--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/auth.$.tsx@@ -0,0 +1,8 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const loader = async ({ request }: LoaderFunctionArgs) => {+ await authenticate.admin(request);++ return null;+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/auth.login/error.server.tsx b/claude-ops/templates/shopify-admin-app/app/routes/auth.login/error.server.tsxnew file mode 100644index 00000000..2c794974--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/auth.login/error.server.tsx@@ -0,0 +1,16 @@+import type { LoginError } from "@shopify/shopify-app-remix/server";+import { LoginErrorType } from "@shopify/shopify-app-remix/server";++interface LoginErrorMessage {+ shop?: string;+}++export function loginErrorMessage(loginErrors: LoginError): LoginErrorMessage {+ if (loginErrors?.shop === LoginErrorType.MissingShop) {+ return { shop: "Please enter your shop domain to log in" };+ } else if (loginErrors?.shop === LoginErrorType.InvalidShop) {+ return { shop: "Please enter a valid shop domain to log in" };+ }++ return {};+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/auth.login/route.tsx b/claude-ops/templates/shopify-admin-app/app/routes/auth.login/route.tsxnew file mode 100644index 00000000..0e9aece7--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/auth.login/route.tsx@@ -0,0 +1,68 @@+import { useState } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";+import { Form, useActionData, useLoaderData } from "@remix-run/react";+import {+ AppProvider as PolarisAppProvider,+ Button,+ Card,+ FormLayout,+ Page,+ Text,+ TextField,+} from "@shopify/polaris";+import polarisTranslations from "@shopify/polaris/locales/en.json";+import polarisStyles from "@shopify/polaris/build/esm/styles.css?url";++import { login } from "../../shopify.server";++import { loginErrorMessage } from "./error.server";++export const links = () => [{ rel: "stylesheet", href: polarisStyles }];++export const loader = async ({ request }: LoaderFunctionArgs) => {+ const errors = loginErrorMessage(await login(request));++ return { errors, polarisTranslations };+};++export const action = async ({ request }: ActionFunctionArgs) => {+ const errors = loginErrorMessage(await login(request));++ return {+ errors,+ };+};++export default function Auth() {+ const loaderData = useLoaderData<typeof loader>();+ const actionData = useActionData<typeof action>();+ const [shop, setShop] = useState("");+ const { errors } = actionData || loaderData;++ return (+ <PolarisAppProvider i18n={loaderData.polarisTranslations}>+ <Page>+ <Card>+ <Form method="post">+ <FormLayout>+ <Text variant="headingMd" as="h2">+ Log in+ </Text>+ <TextField+ type="text"+ name="shop"+ label="Shop domain"+ helpText="example.myshopify.com"+ value={shop}+ onChange={setShop}+ autoComplete="on"+ error={errors.shop}+ />+ <Button submit>Log in</Button>+ </FormLayout>+ </Form>+ </Card>+ </Page>+ </PolarisAppProvider>+ );+}diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.scopes_update.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.scopes_update.tsxnew file mode 100644index 00000000..c36bb64c--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.scopes_update.tsx@@ -0,0 +1,21 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";+import db from "../db.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { payload, session, topic, shop } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`);++ const current = payload.current as string[];+ if (session) {+ await db.session.update({+ where: {+ id: session.id+ },+ data: {+ scope: current.toString(),+ },+ });+ }+ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.uninstalled.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.uninstalled.tsxnew file mode 100644index 00000000..54d3161c--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.app.uninstalled.tsx@@ -0,0 +1,17 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";+import db from "../db.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, session, topic } = await authenticate.webhook(request);++ console.log(`Received ${topic} webhook for ${shop}`);++ // Webhook requests can trigger multiple times and after an app has already been uninstalled.+ // If this webhook already ran, the session may have been deleted previously.+ if (session) {+ await db.session.deleteMany({ where: { shop } });+ }++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.data_request.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.data_request.tsxnew file mode 100644index 00000000..10771134--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.data_request.tsx@@ -0,0 +1,16 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} compliance webhook for ${shop}`, {+ customerId: payload.customer?.id,+ email: payload.customer?.email,+ });++ // MANDATORY: Respond to customer data request within 30 days.+ // Return all stored data for this customer.+ // See: https://shopify.dev/docs/apps/build/privacy-law-compliance++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.redact.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.redact.tsxnew file mode 100644index 00000000..81228442--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.customers.redact.tsx@@ -0,0 +1,14 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} compliance webhook for ${shop}`, {+ customerId: payload.customer?.id,+ });++ // MANDATORY: Delete all stored customer data within 30 days.+ // See: https://shopify.dev/docs/apps/build/privacy-law-compliance++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.fulfillments.create.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.fulfillments.create.tsxnew file mode 100644index 00000000..d9be40ff--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.fulfillments.create.tsx@@ -0,0 +1,16 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`, {+ fulfillmentId: payload.id,+ orderId: payload.order_id,+ status: payload.status,+ trackingNumber: payload.tracking_number,+ });++ // TODO: Handle fulfillment creation — notify customer, update status, etc.++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.inventory.update.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.inventory.update.tsxnew file mode 100644index 00000000..d00da9d8--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.inventory.update.tsx@@ -0,0 +1,15 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`, {+ inventoryItemId: payload.inventory_item_id,+ locationId: payload.location_id,+ available: payload.available,+ });++ // TODO: Handle inventory level changes — reorder alerts, sync, etc.++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.create.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.create.tsxnew file mode 100644index 00000000..ee4c9545--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.create.tsx@@ -0,0 +1,14 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`, {+ orderId: payload.id,+ totalPrice: payload.total_price,+ });++ // TODO: Process new order — sync to your system, trigger fulfillment, etc.++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.updated.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.updated.tsxnew file mode 100644index 00000000..954527e9--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.orders.updated.tsx@@ -0,0 +1,15 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`, {+ orderId: payload.id,+ financialStatus: payload.financial_status,+ fulfillmentStatus: payload.fulfillment_status,+ });++ // TODO: Handle order updates — status changes, cancellations, refunds, etc.++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.products.update.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.products.update.tsxnew file mode 100644index 00000000..d26312de--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.products.update.tsx@@ -0,0 +1,15 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic, payload } = await authenticate.webhook(request);+ console.log(`Received ${topic} webhook for ${shop}`, {+ productId: payload.id,+ title: payload.title,+ status: payload.status,+ });++ // TODO: Sync product changes — update catalog, adjust inventory, etc.++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/routes/webhooks.shop.redact.tsx b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.shop.redact.tsxnew file mode 100644index 00000000..fb9f3c21--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/routes/webhooks.shop.redact.tsx@@ -0,0 +1,13 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { authenticate } from "../shopify.server";++export const action = async ({ request }: ActionFunctionArgs) => {+ const { shop, topic } = await authenticate.webhook(request);+ console.log(`Received ${topic} compliance webhook for ${shop}`);++ // MANDATORY: Delete all stored data for this shop within 48 hours.+ // This fires 48 hours after the app is uninstalled.+ // See: https://shopify.dev/docs/apps/build/privacy-law-compliance++ return new Response();+};diff --git a/claude-ops/templates/shopify-admin-app/app/shopify.server.ts b/claude-ops/templates/shopify-admin-app/app/shopify.server.tsnew file mode 100644index 00000000..7cb8e538--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/app/shopify.server.ts@@ -0,0 +1,35 @@+import "@shopify/shopify-app-remix/adapters/node";+import {+ ApiVersion,+ AppDistribution,+ shopifyApp,+} from "@shopify/shopify-app-remix/server";+import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";+import prisma from "./db.server";++const shopify = shopifyApp({+ apiKey: process.env.SHOPIFY_API_KEY,+ apiSecretKey: process.env.SHOPIFY_API_SECRET || "",+ apiVersion: ApiVersion.January25,+ scopes: process.env.SCOPES?.split(","),+ appUrl: process.env.SHOPIFY_APP_URL || "",+ authPathPrefix: "/auth",+ sessionStorage: new PrismaSessionStorage(prisma),+ distribution: AppDistribution.AppStore,+ future: {+ unstable_newEmbeddedAuthStrategy: true,+ expiringOfflineAccessTokens: true,+ },+ ...(process.env.SHOP_CUSTOM_DOMAIN+ ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }+ : {}),+});++export default shopify;+export const apiVersion = ApiVersion.January25;+export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;+export const authenticate = shopify.authenticate;+export const unauthenticated = shopify.unauthenticated;+export const login = shopify.login;+export const registerWebhooks = shopify.registerWebhooks;+export const sessionStorage = shopify.sessionStorage;diff --git a/claude-ops/templates/shopify-admin-app/env.d.ts b/claude-ops/templates/shopify-admin-app/env.d.tsnew file mode 100644index 00000000..8d2f9518--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/env.d.ts@@ -0,0 +1,2 @@+/// <reference types="vite/client" />+/// <reference types="@remix-run/node" />diff --git a/claude-ops/templates/shopify-admin-app/extensions/.gitkeep b/claude-ops/templates/shopify-admin-app/extensions/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/claude-ops/templates/shopify-admin-app/package.json b/claude-ops/templates/shopify-admin-app/package.jsonnew file mode 100644index 00000000..f0beb905--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/package.json@@ -0,0 +1,78 @@+{+ "name": "app",+ "private": true,+ "scripts": {+ "build": "remix vite:build",+ "dev": "shopify app dev",+ "config:link": "shopify app config link",+ "generate": "shopify app generate",+ "deploy": "shopify app deploy",+ "config:use": "shopify app config use",+ "env": "shopify app env",+ "start": "remix-serve ./build/server/index.js",+ "docker-start": "npm run setup && npm run start",+ "setup": "prisma generate && prisma migrate deploy",+ "lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",+ "shopify": "shopify",+ "prisma": "prisma",+ "graphql-codegen": "graphql-codegen",+ "vite": "vite"+ },+ "type": "module",+ "engines": {+ "node": ">=20.19 <22 || >=22.12"+ },+ "dependencies": {+ "@prisma/client": "^6.2.1",+ "@remix-run/dev": "^2.16.1",+ "@remix-run/fs-routes": "^2.16.1",+ "@remix-run/node": "^2.16.1",+ "@remix-run/react": "^2.16.1",+ "@remix-run/serve": "^2.16.1",+ "@shopify/app-bridge-react": "^4.1.6",+ "@shopify/polaris": "^12.0.0",+ "@shopify/shopify-app-remix": "^4.1.0",+ "@shopify/shopify-app-session-storage-prisma": "^8.0.0",+ "isbot": "^5.1.0",+ "prisma": "^6.2.1",+ "react": "^18.2.0",+ "react-dom": "^18.2.0",+ "vite-tsconfig-paths": "^5.0.1"+ },+ "devDependencies": {+ "@remix-run/eslint-config": "^2.16.1",+ "@remix-run/route-config": "^2.16.1",+ "@shopify/api-codegen-preset": "^1.1.1",+ "@types/eslint": "^9.6.1",+ "@types/node": "^22.2.0",+ "@types/react": "^18.2.31",+ "@types/react-dom": "^18.2.14",+ "eslint": "^8.42.0",+ "eslint-config-prettier": "^10.0.1",+ "prettier": "^3.2.4",+ "typescript": "^5.2.2",+ "vite": "^6.2.2"+ },+ "workspaces": {+ "packages": [+ "extensions/*"+ ]+ },+ "trustedDependencies": [+ "@shopify/plugin-cloudflare"+ ],+ "resolutions": {+ "@graphql-tools/url-loader": "8.0.16",+ "@graphql-codegen/client-preset": "4.7.0",+ "@graphql-codegen/typescript-operations": "4.5.0",+ "minimatch": "9.0.5",+ "vite": "^6.2.2"+ },+ "overrides": {+ "@graphql-tools/url-loader": "8.0.16",+ "@graphql-codegen/client-preset": "4.7.0",+ "@graphql-codegen/typescript-operations": "4.5.0",+ "minimatch": "9.0.5",+ "vite": "^6.2.2"+ }+}diff --git a/claude-ops/templates/shopify-admin-app/prisma/migrations/20240530213853_create_session_table/migration.sql b/claude-ops/templates/shopify-admin-app/prisma/migrations/20240530213853_create_session_table/migration.sqlnew file mode 100644index 00000000..3f8c6757--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/prisma/migrations/20240530213853_create_session_table/migration.sql@@ -0,0 +1,20 @@+-- CreateTable+CREATE TABLE "Session" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "shop" TEXT NOT NULL,+ "state" TEXT NOT NULL,+ "isOnline" BOOLEAN NOT NULL DEFAULT false,+ "scope" TEXT,+ "expires" DATETIME,+ "accessToken" TEXT NOT NULL,+ "userId" BIGINT,+ "firstName" TEXT,+ "lastName" TEXT,+ "email" TEXT,+ "accountOwner" BOOLEAN NOT NULL DEFAULT false,+ "locale" TEXT,+ "collaborator" BOOLEAN DEFAULT false,+ "emailVerified" BOOLEAN DEFAULT false,+ "refreshToken" TEXT,+ "refreshTokenExpires" DATETIME+);diff --git a/claude-ops/templates/shopify-admin-app/prisma/schema.prisma b/claude-ops/templates/shopify-admin-app/prisma/schema.prismanew file mode 100644index 00000000..4532d098--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/prisma/schema.prisma@@ -0,0 +1,34 @@+// This is your Prisma schema file,+// learn more about it in the docs: https://pris.ly/d/prisma-schema++generator client {+ provider = "prisma-client-js"+}++// Note that some adapters may set a maximum length for the String type by default, please ensure your strings are long+// enough when changing adapters.+// See https://www.prisma.io/docs/orm/reference/prisma-schema-reference#string for more information+datasource db {+ provider = "sqlite"+ url = "file:dev.sqlite"+}++model Session {+ id String @id+ shop String+ state String+ isOnline Boolean @default(false)+ scope String?+ expires DateTime?+ accessToken String+ userId BigInt?+ firstName String?+ lastName String?+ email String?+ accountOwner Boolean @default(false)+ locale String?+ collaborator Boolean? @default(false)+ emailVerified Boolean? @default(false)+ refreshToken String?+ refreshTokenExpires DateTime?+}diff --git a/claude-ops/templates/shopify-admin-app/public/favicon.ico b/claude-ops/templates/shopify-admin-app/public/favicon.iconew file mode 100644index 00000000..8830cf68Binary files /dev/null and b/claude-ops/templates/shopify-admin-app/public/favicon.ico differdiff --git a/claude-ops/templates/shopify-admin-app/shopify.app.toml b/claude-ops/templates/shopify-admin-app/shopify.app.tomlnew file mode 100644index 00000000..2a77fff3--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/shopify.app.toml@@ -0,0 +1,52 @@+# Claude Ops Admin App — Full-scope Shopify admin template+# Generated by claude-ops /ops:setup ecom+# client_id is populated at install time by the setup wizard++client_id = ""++[access_scopes]+scopes = "read_products,write_products,read_orders,write_orders,read_customers,write_customers,read_inventory,write_inventory,read_fulfillments,write_fulfillments,read_shipping,write_shipping,read_analytics,read_reports,read_themes,write_themes,read_content,write_content,read_price_rules,write_price_rules,read_discounts,write_discounts,read_marketing_events,write_marketing_events,read_product_listings,read_collection_listings,read_locations,read_script_tags,write_script_tags,read_assigned_fulfillment_orders,write_assigned_fulfillment_orders,read_merchant_managed_fulfillment_orders,write_merchant_managed_fulfillment_orders,read_third_party_fulfillment_orders,write_third_party_fulfillment_orders,read_gift_cards,write_gift_cards,read_shopify_payments_payouts,read_shopify_payments_disputes,read_translations,write_translations,read_locales,write_locales,read_files,write_files,read_publications,write_publications,read_metaobject_definitions,write_metaobject_definitions,read_metaobjects,write_metaobjects"++[webhooks]+api_version = "2025-01"++ [[webhooks.subscriptions]]+ uri = "/webhooks/app/uninstalled"+ topics = ["app/uninstalled"]++ [[webhooks.subscriptions]]+ topics = ["app/scopes_update"]+ uri = "/webhooks/app/scopes_update"++ [[webhooks.subscriptions]]+ topics = ["orders/create"]+ uri = "/webhooks/orders/create"++ [[webhooks.subscriptions]]+ topics = ["orders/updated"]+ uri = "/webhooks/orders/updated"++ [[webhooks.subscriptions]]+ topics = ["products/update"]+ uri = "/webhooks/products/update"++ [[webhooks.subscriptions]]+ topics = ["inventory_levels/update"]+ uri = "/webhooks/inventory/update"++ [[webhooks.subscriptions]]+ topics = ["fulfillments/create"]+ uri = "/webhooks/fulfillments/create"++ # Compliance webhooks (required for public apps)+ [[webhooks.subscriptions]]+ uri = "/webhooks/customers/data_request"+ compliance_topics = ["customers/data_request"]++ [[webhooks.subscriptions]]+ uri = "/webhooks/customers/redact"+ compliance_topics = ["customers/redact"]++ [[webhooks.subscriptions]]+ uri = "/webhooks/shop/redact"+ compliance_topics = ["shop/redact"]diff --git a/claude-ops/templates/shopify-admin-app/shopify.web.toml b/claude-ops/templates/shopify-admin-app/shopify.web.tomlnew file mode 100644index 00000000..b35c57be--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/shopify.web.toml@@ -0,0 +1,7 @@+name = "remix"+roles = ["frontend", "backend"]+webhooks_path = "/webhooks/app/uninstalled"++[commands]+predev = "npx prisma generate"+dev = "npx prisma migrate deploy && npm exec remix vite:dev"diff --git a/claude-ops/templates/shopify-admin-app/tsconfig.json b/claude-ops/templates/shopify-admin-app/tsconfig.jsonnew file mode 100644index 00000000..7c89723f--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/tsconfig.json@@ -0,0 +1,21 @@+{+ "include": ["env.d.ts", "**/*.ts", "**/*.tsx"],+ "compilerOptions": {+ "lib": ["DOM", "DOM.Iterable", "ES2022"],+ "strict": true,+ "skipLibCheck": true,+ "isolatedModules": true,+ "allowSyntheticDefaultImports": true,+ "removeComments": false,+ "forceConsistentCasingInFileNames": true,+ "noEmit": true,+ "allowJs": true,+ "resolveJsonModule": true,+ "jsx": "react-jsx",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "target": "ES2022",+ "baseUrl": ".",+ "types": ["node"]+ }+}diff --git a/claude-ops/templates/shopify-admin-app/vite.config.ts b/claude-ops/templates/shopify-admin-app/vite.config.tsnew file mode 100644index 00000000..461e716a--- /dev/null+++ b/claude-ops/templates/shopify-admin-app/vite.config.ts@@ -0,0 +1,73 @@+import { vitePlugin as remix } from "@remix-run/dev";+import { installGlobals } from "@remix-run/node";+import { defineConfig, type UserConfig } from "vite";+import tsconfigPaths from "vite-tsconfig-paths";++installGlobals({ nativeFetch: true });++// Related: https://github.com/remix-run/remix/issues/2835#issuecomment-1144102176+// Replace the HOST env var with SHOPIFY_APP_URL so that it doesn't break the remix server. The CLI will eventually+// stop passing in HOST, so we can remove this workaround after the next major release.+if (+ process.env.HOST &&+ (!process.env.SHOPIFY_APP_URL ||+ process.env.SHOPIFY_APP_URL === process.env.HOST)+) {+ process.env.SHOPIFY_APP_URL = process.env.HOST;+ delete process.env.HOST;+}++const host = new URL(process.env.SHOPIFY_APP_URL || "http://localhost")+ .hostname;++let hmrConfig;+if (host === "localhost") {+ hmrConfig = {+ protocol: "ws",+ host: "localhost",+ port: 64999,+ clientPort: 64999,+ };+} else {+ hmrConfig = {+ protocol: "wss",+ host: host,+ port: parseInt(process.env.FRONTEND_PORT!) || 8002,+ clientPort: 443,+ };+}++export default defineConfig({+ server: {+ allowedHosts: [host],+ cors: {+ preflightContinue: true,+ },+ port: Number(process.env.PORT || 3000),+ hmr: hmrConfig,+ fs: {+ // See https://vitejs.dev/config/server-options.html#server-fs-allow for more information+ allow: ["app", "node_modules"],+ },+ },+ plugins: [+ remix({+ ignoredRouteFiles: ["**/.*"],+ future: {+ v3_fetcherPersist: true,+ v3_relativeSplatPath: true,+ v3_throwAbortReason: true,+ v3_lazyRouteDiscovery: true,+ v3_singleFetch: false,+ v3_routeConfig: true,+ },+ }),+ tsconfigPaths(),+ ],+ build: {+ assetsInlineLimit: 0,+ },+ optimizeDeps: {+ include: ["@shopify/app-bridge-react", "@shopify/polaris"],+ },+}) satisfies UserConfig;diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shnew file mode 100755index 00000000..c459eb7f--- /dev/null+++ b/claude-ops/tests/run-all.sh@@ -0,0 +1,61 @@+#!/usr/bin/env bash+# run-all.sh — Runs all claude-ops test suites and reports pass/fail+set -euo pipefail++TESTS_DIR="$(cd "$(dirname "$0")" && pwd)"++total_pass=0+total_fail=0+failed_suites=()++run_suite() {+ local script="$1"+ local name+ name=$(basename "$script")++ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo "Suite: $name"+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++ if bash "$script"; then+ echo "[ PASS ] $name"+ total_pass=$((total_pass+1))+ else+ echo "[ FAIL ] $name"+ total_fail=$((total_fail+1))+ failed_suites+=("$name")+ fi+ echo ""+}++echo ""+echo "claude-ops Test Suite"+echo "Running from: $TESTS_DIR"+echo ""++run_suite "$TESTS_DIR/test-skills-lint.sh"+run_suite "$TESTS_DIR/test-bin-scripts.sh"+run_suite "$TESTS_DIR/test-hooks.sh"+run_suite "$TESTS_DIR/test-template.sh"+run_suite "$TESTS_DIR/test-claude-md.sh"+run_suite "$TESTS_DIR/test-no-secrets.sh"++echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo "SUMMARY"+echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+echo " Suites passed: $total_pass"+echo " Suites failed: $total_fail"++if (( total_fail > 0 )); then+ echo ""+ echo "Failed suites:"+ for s in "${failed_suites[@]}"; do+ echo " - $s"+ done+ echo ""+ exit 1+fi++echo ""+echo "All suites passed."+exit 0diff --git a/claude-ops/tests/test-bin-scripts.sh b/claude-ops/tests/test-bin-scripts.shnew file mode 100755index 00000000..144823ca--- /dev/null+++ b/claude-ops/tests/test-bin-scripts.sh@@ -0,0 +1,100 @@+#!/usr/bin/env bash+# test-bin-scripts.sh — Validates bin/ scripts+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+BIN_DIR="$PLUGIN_ROOT/bin"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++# Collect all bin scripts (skip .mjs and non-executables that are node/python)+script_files=()+while IFS= read -r -d '' f; do+ # Skip .mjs node scripts — they're valid but not bash+ [[ "$f" == *.mjs ]] && continue+ script_files+=("$f")+done < <(find "$BIN_DIR" -maxdepth 1 -type f -print0 2>/dev/null)++if [[ ${#script_files[@]} -eq 0 ]]; then+ echo "FAIL: No scripts found in $BIN_DIR"+ exit 1+fi++echo "Found ${#script_files[@]} bash script(s) in bin/ (excluding .mjs)"+echo ""++for script in "${script_files[@]}"; do+ name=$(basename "$script")+ echo "Checking: bin/$name"++ # 1. Executable bit+ if [[ -x "$script" ]]; then+ ok "is executable"+ else+ err "not executable: $name"+ fi++ # 2. Valid shebang+ shebang=$(head -1 "$script" 2>/dev/null || true)+ if echo "$shebang" | grep -qE "^#!.*(bash|sh|env bash|env sh)"; then+ ok "valid shebang: $shebang"+ else+ err "missing or invalid shebang in $name (got: '$shebang')"+ fi++ # 3. shellcheck (if available)+ if command -v shellcheck &>/dev/null; then+ if shellcheck -S error "$script" 2>/dev/null; then+ ok "shellcheck (errors only) clean"+ else+ err "shellcheck errors in $name (run: shellcheck -S error bin/$name)"+ fi+ else+ echo " SKIP: shellcheck not installed"+ fi++ echo ""+done++# 4. Cross-check: ops-setup-install handles all tools listed in ops-setup-preflight+echo "Cross-check: ops-setup-install vs ops-setup-preflight"+preflight="$BIN_DIR/ops-setup-preflight"+install_script="$BIN_DIR/ops-setup-install"++if [[ -f "$preflight" && -f "$install_script" ]]; then+ # Extract tool names from preflight — lines like: check_tool jq / command -v jq+ preflight_tools=$(grep -oE 'command -v [a-z_-]+' "$preflight" 2>/dev/null | awk '{print $3}' | sort -u || true)+ # Extract tools handled by install script — lines like: jq) / "jq")+ install_tools=$(grep -oE '"?[a-z_-]+"?\)' "$install_script" 2>/dev/null | tr -d '"()' | sort -u || true)++ missing_count=0+ while IFS= read -r tool; do+ [[ -z "$tool" ]] && continue+ if echo "$install_tools" | grep -qx "$tool"; then+ ok "ops-setup-install handles: $tool"+ else+ err "ops-setup-install missing handler for: $tool (found in preflight)"+ missing_count=$((missing_count+1))+ fi+ done <<< "$preflight_tools"++ if [[ -z "$preflight_tools" ]]; then+ echo " SKIP: could not extract tool list from ops-setup-preflight"+ fi+else+ echo " SKIP: ops-setup-preflight or ops-setup-install not found"+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ exit 1+fi+exit 0diff --git a/claude-ops/tests/test-claude-md.sh b/claude-ops/tests/test-claude-md.shnew file mode 100755index 00000000..9d3374a3--- /dev/null+++ b/claude-ops/tests/test-claude-md.sh@@ -0,0 +1,91 @@+#!/usr/bin/env bash+# test-claude-md.sh — Validates CLAUDE.md contains required rules+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+CLAUDE_MD="$PLUGIN_ROOT/CLAUDE.md"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++echo "Checking: CLAUDE.md"+echo ""++# 1. File exists+if [[ ! -f "$CLAUDE_MD" ]]; then+ echo "FAIL: CLAUDE.md not found at $CLAUDE_MD"+ exit 1+fi+ok "CLAUDE.md exists"++# 2. Contains max-4-options rule+# Look for the key constraint about AskUserQuestion and 4 options+if grep -qE "(<=4|max.*4|4.*options|AskUserQuestion)" "$CLAUDE_MD"; then+ ok "contains max-4-options rule reference"+else+ err "missing max-4-options / AskUserQuestion constraint"+fi++# More specific: the actual numeric constraint+if grep -qE "4\s*(items|options)" "$CLAUDE_MD"; then+ ok "contains explicit '4 items/options' constraint"+else+ # Check for <=4 pattern+ if grep -q "<=4" "$CLAUDE_MD"; then+ ok "contains '<=4' constraint"+ else+ err "could not find explicit 4-option limit (<=4 or '4 items')"+ fi+fi++# 3. Contains never-delegate-commands rule+# The rule that says run commands via Bash tool instead of telling users to run them+if grep -qiE "(never delegate|never.*tell.*user.*run|run.*via.*bash|delegate.*terminal)" "$CLAUDE_MD"; then+ ok "contains never-delegate-commands rule"+else+ err "missing never-delegate-commands rule (should instruct to run via Bash tool, not tell user)"+fi++# More specific check+if grep -qE "(Bash tool|run_in_background)" "$CLAUDE_MD"; then+ ok "references Bash tool for command execution"+else+ err "no reference to Bash tool for command execution in CLAUDE.md"+fi++# 4. Has at least 2 numbered/named rules+rule_count=$(grep -cE "^## Rule [0-9]+" "$CLAUDE_MD" 2>/dev/null || true)+if (( rule_count >= 2 )); then+ ok "has $rule_count numbered rules"+else+ err "expected at least 2 numbered rules, found: $rule_count"+fi++# 5. File is not empty+size=$(wc -c < "$CLAUDE_MD")+if (( size > 200 )); then+ ok "CLAUDE.md has substantial content ($size bytes)"+else+ err "CLAUDE.md is suspiciously small ($size bytes)"+fi++# 6. No broken markdown headings (# at start of line followed immediately by text with no space)+bad_headings=$(grep -cE "^#{1,6}[^ #]" "$CLAUDE_MD" 2>/dev/null || true)+if (( bad_headings == 0 )); then+ ok "no malformed headings (missing space after #)"+else+ err "found $bad_headings malformed heading(s) (missing space after #)"+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ exit 1+fi+exit 0diff --git a/claude-ops/tests/test-hooks.sh b/claude-ops/tests/test-hooks.shnew file mode 100755index 00000000..e2890917--- /dev/null+++ b/claude-ops/tests/test-hooks.sh@@ -0,0 +1,130 @@+#!/usr/bin/env bash+# test-hooks.sh — Validates hooks/hooks.json+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+HOOKS_FILE="$PLUGIN_ROOT/hooks/hooks.json"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++echo "Checking: hooks/hooks.json"+echo ""++# 1. File exists+if [[ ! -f "$HOOKS_FILE" ]]; then+ echo "FAIL: hooks/hooks.json not found"+ exit 1+fi+ok "hooks.json exists"++# 2. Valid JSON+if command -v jq &>/dev/null; then+ if jq empty "$HOOKS_FILE" 2>/dev/null; then+ ok "valid JSON (jq)"+ else+ err "invalid JSON in hooks.json"+ exit 1+ fi+elif command -v python3 &>/dev/null; then+ if python3 -c "import json,sys; json.load(open('$HOOKS_FILE'))" 2>/dev/null; then+ ok "valid JSON (python3)"+ else+ err "invalid JSON in hooks.json"+ exit 1+ fi+else+ echo " SKIP: neither jq nor python3 available for JSON validation"+fi++# 3. All referenced scripts exist+echo ""+echo "Checking referenced scripts..."++# Extract all command values from hooks.json+if command -v jq &>/dev/null; then+ commands=$(jq -r '.. | objects | .command? // empty' "$HOOKS_FILE" 2>/dev/null || true)+else+ # Fallback: grep for "command": lines+ commands=$(grep '"command"' "$HOOKS_FILE" | sed 's/.*"command"[[:space:]]*:[[:space:]]*"\(.*\)".*/\1/' || true)+fi++while IFS= read -r cmd; do+ [[ -z "$cmd" ]] && continue++ # Extract the script path — first word after 'bash ' or the first token if executable+ # Handle: "bash ${CLAUDE_PLUGIN_ROOT}/bin/foo", "${CLAUDE_PLUGIN_ROOT}/bin/foo"+ script_ref=$(echo "$cmd" | grep -oE '\$\{CLAUDE_PLUGIN_ROOT\}/[^ ]+' | head -1 || true)++ if [[ -n "$script_ref" ]]; then+ # Resolve placeholder+ resolved="${script_ref/\$\{CLAUDE_PLUGIN_ROOT\}/$PLUGIN_ROOT}"+ # Strip any trailing shell tokens like 2>/dev/null+ resolved=$(echo "$resolved" | awk '{print $1}')+ if [[ -f "$resolved" ]]; then+ ok "referenced script exists: ${resolved#$PLUGIN_ROOT/}"+ else+ err "referenced script missing: ${resolved#$PLUGIN_ROOT/}"+ fi+ else+ ok "command has no CLAUDE_PLUGIN_ROOT path reference (skipping path check): $cmd"+ fi+done <<< "$commands"++# 4. Hook types are valid+echo ""+echo "Checking hook types..."++if command -v jq &>/dev/null; then+ types=$(jq -r '.. | objects | .type? // empty' "$HOOKS_FILE" 2>/dev/null | sort -u || true)+ valid_types=("command")+ while IFS= read -r htype; do+ [[ -z "$htype" ]] && continue+ valid=false+ for vt in "${valid_types[@]}"; do+ [[ "$htype" == "$vt" ]] && valid=true && break+ done+ if $valid; then+ ok "hook type is valid: $htype"+ else+ err "invalid hook type: $htype (expected: command)"+ fi+ done <<< "$types"+else+ echo " SKIP: jq not available for hook type validation"+fi++# 5. Top-level hook events are valid Claude Code hook events+echo ""+echo "Checking hook event names..."++valid_events=("SessionStart" "SessionEnd" "PreToolUse" "PostToolUse" "Stop" "SubagentStop" "Notification")++if command -v jq &>/dev/null; then+ events=$(jq -r '.hooks | keys[]' "$HOOKS_FILE" 2>/dev/null || true)+ while IFS= read -r event; do+ [[ -z "$event" ]] && continue+ valid=false+ for ve in "${valid_events[@]}"; do+ [[ "$event" == "$ve" ]] && valid=true && break+ done+ if $valid; then+ ok "hook event is valid: $event"+ else+ err "unrecognized hook event: $event"+ fi+ done <<< "$events"+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ exit 1+fi+exit 0diff --git a/claude-ops/tests/test-no-secrets.sh b/claude-ops/tests/test-no-secrets.shnew file mode 100755index 00000000..9b3d6506--- /dev/null+++ b/claude-ops/tests/test-no-secrets.sh@@ -0,0 +1,114 @@+#!/usr/bin/env bash+# test-no-secrets.sh — Scans all files for leaked secrets/tokens/personal data+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1 — $2"; fail=$((fail+1)); }++echo "Scanning for secrets and personal data in: $PLUGIN_ROOT"+echo ""++# Directories/files to exclude from scanning+EXCLUDE_DIRS=(+ "node_modules"+ ".git"+ "tests"+)++build_exclude_args() {+ local args=()+ for d in "${EXCLUDE_DIRS[@]}"; do+ args+=("--exclude-dir=$d")+ done+ echo "${args[@]}"+}++EXCLUDE_ARGS=$(build_exclude_args)++# Helper: scan for a pattern, return matches (excluding placeholder/example patterns)+scan_pattern() {+ local label="$1"+ local pattern="$2"+ local allow_pattern="${3:-}" # optional grep -v pattern for allowed false positives++ local results+ # shellcheck disable=SC2086+ results=$(grep -rE "$pattern" $EXCLUDE_ARGS \+ --include="*.sh" --include="*.md" --include="*.json" \+ --include="*.toml" --include="*.ts" --include="*.js" \+ --include="*.mjs" --include="*.yaml" --include="*.yml" \+ --include="*.env" --include="*.txt" \+ "$PLUGIN_ROOT" 2>/dev/null || true)++ # Filter out example/placeholder lines+ results=$(echo "$results" | grep -vE "(example|placeholder|your[-_]|<[A-Z_]+>|\[YOUR_|TODO|REPLACE|fake|dummy|test-token|sk_test_EXAMPLE)" || true)++ # Apply additional allowlist if provided+ if [[ -n "$allow_pattern" && -n "$results" ]]; then+ results=$(echo "$results" | grep -vE "$allow_pattern" || true)+ fi++ # Remove empty lines+ results=$(echo "$results" | grep -v "^$" || true)++ if [[ -n "$results" ]]; then+ local count+ count=$(echo "$results" | wc -l | tr -d ' ')+ err "$label" "$count match(es) found"+ echo "$results" | head -5 | sed 's/^/ /'+ return 1+ else+ ok "no $label found"+ return 0+ fi+}++# Stripe secret keys+scan_pattern "Stripe secret keys (sk_live_)" 'sk_live_[a-zA-Z0-9]{20,}'++# Stripe publishable keys+scan_pattern "Stripe publishable keys (pk_live_)" 'pk_live_[a-zA-Z0-9]{20,}'++# Shopify tokens+scan_pattern "Shopify tokens (shppa_, shpca_, shpat_)" 'shp(pa|ca|at)_[a-zA-Z0-9]{20,}'++# Slack tokens+scan_pattern "Slack tokens (xoxb-, xoxp-)" 'xox[bp]-[0-9]+-[a-zA-Z0-9-]+'++# Google API keys+scan_pattern "Google API keys (AIza)" 'AIza[0-9A-Za-z_-]{35}'++# GitHub tokens+scan_pattern "GitHub tokens (ghp_, gho_, ghs_)" 'gh[phos]_[a-zA-Z0-9]{36,}'++# Generic secret key patterns+scan_pattern "generic secret key patterns (gsk_)" 'gsk_[a-zA-Z0-9]{20,}'++# OpenAI tokens+scan_pattern "OpenAI tokens (sk-)" 'sk-[a-zA-Z0-9]{40,}' 'sk-\*|sk-proj-\*|sk-test'++# Personal email addresses (project-domain.ai, specific domains)+scan_pattern "project-specific email addresses" '[a-zA-Z0-9._%+-]+@project-domain\.ai' \+ '(abeeha|example|your-|<[A-Z]|\[|\]|#.*@)'++# AWS secret patterns+scan_pattern "AWS secret access keys" '(?i)aws.{0,20}secret.{0,20}[A-Za-z0-9/+=]{40}'++# Generic high-entropy tokens with common prefixes+scan_pattern "org_ prefixed tokens (often API keys)" 'org_[a-zA-Z0-9]{20,}'++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ echo "ACTION: Remove or rotate any real secrets found above."+ exit 1+fi+exit 0diff --git a/claude-ops/tests/test-skills-lint.sh b/claude-ops/tests/test-skills-lint.shnew file mode 100755index 00000000..7007ca25--- /dev/null+++ b/claude-ops/tests/test-skills-lint.sh@@ -0,0 +1,128 @@+#!/usr/bin/env bash+# test-skills-lint.sh — Validates all SKILL.md files in skills/+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+SKILLS_DIR="$PLUGIN_ROOT/skills"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++VALID_TOOLS=("Bash" "Read" "Write" "Edit" "Grep" "Glob" "Skill" "Agent" "AskUserQuestion" "WebSearch" "WebFetch" "TodoRead" "TodoWrite" "NotebookRead" "NotebookEdit" "mcp__" "Task")++skill_files=()+while IFS= read -r -d '' f; do+ skill_files+=("$f")+done < <(find "$SKILLS_DIR" -name "SKILL.md" -print0 2>/dev/null)++if [[ ${#skill_files[@]} -eq 0 ]]; then+ echo "FAIL: No SKILL.md files found in $SKILLS_DIR"+ exit 1+fi++echo "Found ${#skill_files[@]} SKILL.md file(s)"+echo ""++for skill_file in "${skill_files[@]}"; do+ rel="${skill_file#$PLUGIN_ROOT/}"+ echo "Checking: $rel"++ # Extract frontmatter (between first and second ---)+ frontmatter=$(awk '/^---/{c++; if(c==2)exit} c==1' "$skill_file")++ # 1. Has required frontmatter fields: name, description, allowed-tools+ if echo "$frontmatter" | grep -q "^name:"; then+ ok "has 'name' field"+ else+ err "missing 'name' field in frontmatter"+ fi++ if echo "$frontmatter" | grep -q "^description:"; then+ ok "has 'description' field"+ else+ err "missing 'description' field in frontmatter"+ fi++ if echo "$frontmatter" | grep -q "^allowed-tools:"; then+ ok "has 'allowed-tools' field"+ else+ err "missing 'allowed-tools' field in frontmatter"+ fi++ # 2. No AskUserQuestion option lists > 4 items+ # Look for option arrays that may exceed 4 items by counting consecutive list items after "options:"+ max_options=0+ in_options=0+ count=0+ while IFS= read -r line; do+ if echo "$line" | grep -qE "options\s*:"; then+ in_options=1+ count=0+ elif [[ $in_options -eq 1 ]]; then+ if echo "$line" | grep -qE "^\s*-\s+"; then+ count=$((count+1))+ if (( count > max_options )); then+ max_options=$count+ fi+ elif echo "$line" | grep -qE "^\s*[a-zA-Z]" && ! echo "$line" | grep -qE "^\s*-"; then+ in_options=0+ count=0+ fi+ fi+ done < "$skill_file"++ if (( max_options > 4 )); then+ err "AskUserQuestion options list has $max_options items (max 4) in $rel"+ else+ ok "AskUserQuestion option count OK (max found: $max_options)"+ fi++ # 3. No hardcoded personal data (emails, tokens, personal names)+ # Allow placeholder patterns like [email protected] or [email protected]+ if grep -qE "[a-zA-Z0-9._%+-]+@(gmail|yahoo|hotmail|project-domain|lifecycle)\.(com|ai|io)" "$skill_file" 2>/dev/null; then+ # Allow clearly marked examples/placeholders+ bad=$(grep -E "[a-zA-Z0-9._%+-]+@(gmail|yahoo|hotmail|project-domain|lifecycle)\.(com|ai|io)" "$skill_file" | grep -vE "(example|placeholder|your-|<|>|\[|\]|#)" || true)+ if [[ -n "$bad" ]]; then+ err "possible hardcoded email in $rel: $bad"+ else+ ok "no hardcoded personal emails (example patterns OK)"+ fi+ else+ ok "no hardcoded personal emails"+ fi++ # Check for token patterns — require a realistic suffix (20+ alnum chars) after prefix+ # This avoids false positives on documentation phrases like 'Key starts with "gsk_"'+ token_hits=$(grep -E "(sk_live_[A-Za-z0-9]{20,}|sk_test_[A-Za-z0-9]{20,}|shp(pa|ca|at)_[A-Za-z0-9]{20,}|xox[bp]-[0-9]+-[A-Za-z0-9-]+|gsk_[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{36,})" "$skill_file" 2>/dev/null || true)+ if [[ -n "$token_hits" ]]; then+ err "possible hardcoded token/secret in $rel: $(echo "$token_hits" | head -1)"+ else+ ok "no hardcoded tokens"+ fi++ # 4. Tools referenced in skill body match allowed-tools+ allowed_section=$(echo "$frontmatter" | awk '/^allowed-tools:/,/^[a-z]/' | grep -E "^\s+-\s+" | sed 's/.*- //' || true)+ ok "allowed-tools declared (tool-body cross-check is advisory)"++ # 5. No unclosed code fences+ fence_count=$(grep -c '^\s*```' "$skill_file" 2>/dev/null || true)+ if (( fence_count % 2 != 0 )); then+ err "odd number of code fences ($fence_count) — possible unclosed block in $rel"+ else+ ok "code fences balanced ($fence_count)"+ fi++ echo ""+done++echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ exit 1+fi+exit 0diff --git a/claude-ops/tests/test-template.sh b/claude-ops/tests/test-template.shnew file mode 100755index 00000000..0e85adba--- /dev/null+++ b/claude-ops/tests/test-template.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# test-template.sh — Validates Shopify admin app template+set -euo pipefail++PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+TEMPLATE_DIR="$PLUGIN_ROOT/templates/shopify-admin-app"++pass=0+fail=0++ok() { echo " PASS: $1"; pass=$((pass+1)); }+err() { echo " FAIL: $1"; fail=$((fail+1)); }++echo "Checking: templates/shopify-admin-app/"+echo ""++# 1. Template directory exists+if [[ ! -d "$TEMPLATE_DIR" ]]; then+ echo "FAIL: templates/shopify-admin-app/ not found"+ exit 1+fi+ok "template directory exists"++# 2. shopify.app.toml exists+TOML="$TEMPLATE_DIR/shopify.app.toml"+if [[ -f "$TOML" ]]; then+ ok "shopify.app.toml exists"+else+ err "shopify.app.toml missing"+fi++# 3. shopify.app.toml has scopes+if [[ -f "$TOML" ]]; then+ if grep -q "scopes" "$TOML"; then+ ok "shopify.app.toml has scopes"+ else+ err "shopify.app.toml missing scopes declaration"+ fi++ # 4. scopes line has actual scope values (not empty)+ scopes_line=$(grep "^scopes" "$TOML" | head -1 || true)+ if echo "$scopes_line" | grep -qE 'scopes\s*=\s*"[^"]+'; then+ ok "scopes is non-empty"+ else+ err "scopes appears to be empty in shopify.app.toml"+ fi++ # 5. client_id should be empty (template placeholder, not hardcoded)+ client_id_line=$(grep "^client_id" "$TOML" | head -1 || true)+ if [[ -n "$client_id_line" ]]; then+ # Should be empty string or unset for a template+ if echo "$client_id_line" | grep -qE '^client_id\s*=\s*""'; then+ ok "client_id is empty (correct for template)"+ else+ err "client_id appears to be hardcoded: $client_id_line"+ fi+ else+ ok "client_id not present (template will set at install time)"+ fi+fi++# 6. package.json exists+PKG="$TEMPLATE_DIR/package.json"+if [[ -f "$PKG" ]]; then+ ok "package.json exists"+else+ err "package.json missing"+fi++# 7. package.json is valid JSON+if [[ -f "$PKG" ]]; then+ if command -v jq &>/dev/null; then+ if jq empty "$PKG" 2>/dev/null; then+ ok "package.json is valid JSON"+ else+ err "package.json is invalid JSON"+ fi+ elif command -v python3 &>/dev/null; then+ if python3 -c "import json,sys; json.load(open('$PKG'))" 2>/dev/null; then+ ok "package.json is valid JSON (python3)"+ else+ err "package.json is invalid JSON"+ fi+ else+ echo " SKIP: no JSON validator available for package.json"+ fi++ # 8. package.json has name field+ if command -v jq &>/dev/null; then+ name=$(jq -r '.name // empty' "$PKG" 2>/dev/null || true)+ if [[ -n "$name" ]]; then+ ok "package.json has name: $name"+ else+ err "package.json missing 'name' field"+ fi++ # 9. package.json has scripts+ scripts=$(jq -r '.scripts // empty' "$PKG" 2>/dev/null || true)+ if [[ -n "$scripts" ]]; then+ ok "package.json has scripts section"+ else+ err "package.json missing 'scripts' section"+ fi+ fi++ # 10. No hardcoded client_id in package.json (should not contain shp_ or actual client IDs)+ if grep -qE '"client_id"\s*:\s*"[a-f0-9-]{30,}"' "$PKG" 2>/dev/null; then+ err "package.json contains a hardcoded client_id value"+ else+ ok "package.json has no hardcoded client_id"+ fi+fi++# 11. shopify.web.toml exists (if present, validate it has [roles])+WEB_TOML="$TEMPLATE_DIR/shopify.web.toml"+if [[ -f "$WEB_TOML" ]]; then+ ok "shopify.web.toml exists"+ if grep -q "\[" "$WEB_TOML"; then+ ok "shopify.web.toml has section headers"+ else+ err "shopify.web.toml appears empty or malformed"+ fi+fi++echo ""+echo "---"+echo "Results: $pass passed, $fail failed"+echo ""++if (( fail > 0 )); then+ exit 1+fi+exit 0