Skip to content

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

feat(cross-os): B3 — pkg managers, daemon registration, portability, opener

Claudeae55fa39112d
diff --git a/claude-ops/bin/ops-setup-install b/claude-ops/bin/ops-setup-install
index 02a0cb07..2c061135 100755
--- a/claude-ops/bin/ops-setup-install
+++ b/claude-ops/bin/ops-setup-install
@@ -1,80 +1,225 @@
#!/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
+# Usage: ops-setup-install [--dry-run] [--json] [--list-pkg-mgr] <tool> [<tool>...]
+# Tools: jq git gh aws node brew doppler wacli gog sentry-cli expect
set -euo pipefail
-PLATFORM="$(uname -s | tr '[:upper:]' '[:lower:]')"
+# ─── Source the os-detect helper (cross-OS pkg mgr detection) ───────────────
+SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+LIB_OS_DETECT="$SCRIPT_DIR/lib/os-detect.sh"
+if [ -r "$LIB_OS_DETECT" ]; then
+ # shellcheck source=../lib/os-detect.sh
+ . "$LIB_OS_DETECT"
+fi
-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
+DRY_RUN=0
+JSON=0
+LIST_PKG_MGR=0
+TOOLS=()
+
+# ─── CLI arg parsing (preserves legacy positional tool args) ────────────────
+for arg in "$@"; do
+ case "$arg" in
+ --dry-run) DRY_RUN=1 ;;
+ --json) JSON=1 ;;
+ --list-pkg-mgr) LIST_PKG_MGR=1 ;;
+ --tool=*) TOOLS+=("${arg#--tool=}") ;;
+ -h|--help)
+ sed -n '2,4p' "$0" | sed 's/^# \{0,1\}//'
+ exit 0 ;;
+ --*) echo "✗ Unknown flag: $arg" >&2; exit 2 ;;
+ *) TOOLS+=("$arg") ;;
+ esac
+done
+
+# ─── Debug: --list-pkg-mgr prints OS + pkg_mgr + sample install cmd ─────────
+if [ "$LIST_PKG_MGR" -eq 1 ]; then
+ os="unknown"; mgr=""; cmd=""
+ if declare -F ops_os >/dev/null 2>&1; then os="$(ops_os)"; fi
+ if declare -F ops_pkg_mgr >/dev/null 2>&1; then mgr="$(ops_pkg_mgr)"; fi
+ if declare -F ops_pkg_install_cmd >/dev/null 2>&1; then cmd="$(ops_pkg_install_cmd jq 2>/dev/null || echo '')"; fi
+ echo "os=$os pkg_mgr=$mgr cmd=\"$cmd\""
+ exit 0
+fi
+
+# ─── Package-name translation table ─────────────────────────────────────────
+# Many tools have different package names across distros. Given a logical
+# "tool" name + the detected pkg manager, echo the right package name.
+# Defaults to $tool if no mapping exists.
+resolve_pkg_name() {
+ local tool="$1" mgr="$2"
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) install_gog ;;
- *) echo "✗ Unknown tool: $tool" >&2; return 1 ;;
+ jq|git|expect|brew) echo "$tool" ;;
+ gh)
+ case "$mgr" in
+ pacman) echo "github-cli" ;;
+ winget) echo "GitHub.cli" ;;
+ *) echo "gh" ;;
+ esac ;;
+ aws)
+ case "$mgr" in
+ brew|apt-get|dnf|zypper|apk) echo "awscli" ;;
+ pacman) echo "aws-cli" ;;
+ winget) echo "Amazon.AWSCLI" ;;
+ choco) echo "awscli" ;;
+ scoop) echo "aws" ;;
+ *) echo "awscli" ;;
+ esac ;;
+ node)
+ case "$mgr" in
+ brew) echo "node" ;;
+ apt-get|dnf|pacman|zypper|apk) echo "nodejs" ;;
+ winget) echo "OpenJS.NodeJS.LTS" ;;
+ choco) echo "nodejs-lts" ;;
+ scoop) echo "nodejs-lts" ;;
+ *) echo "nodejs" ;;
+ esac ;;
+ gog)
+ case "$mgr" in
+ brew) echo "gogcli" ;; # also: steipete/tap/gogcli if tapped
+ pacman) echo "gogcli" ;; # typically via yay/AUR
+ winget) echo "steipete.gogcli" ;;
+ *) echo "gogcli" ;;
+ esac ;;
+ *) echo "$tool" ;;
esac
}
-# install_gog — try npm, then bun, then source-clone (private repo).
-# Returns 0 on success, 2 on failure (with manual instructions printed).
-install_gog() {
- if command -v npm >/dev/null 2>&1 && npm install -g @example/gog >/dev/null 2>&1; then
- echo "✓ gog installed via npm"
- return 0
- fi
- if command -v bun >/dev/null 2>&1 && bun install -g @example/gog >/dev/null 2>&1; then
- echo "✓ gog installed via bun"
- return 0
- fi
- if command -v git >/dev/null 2>&1 && \
- git clone https://github.com/example/gog "$HOME/.gog" >/dev/null 2>&1 && \
- ( cd "$HOME/.gog" && ./install.sh >/dev/null 2>&1 ); then
- echo "✓ gog installed from source (~/.gog)"
- return 0
+# ─── install_pkg: prefer ops_pkg_install_cmd, fall back to legacy ───────────
+install_pkg() {
+ local pkg="$1" cmd
+ if declare -F ops_pkg_install_cmd >/dev/null 2>&1; then
+ cmd="$(ops_pkg_install_cmd "$pkg")" || {
+ echo "✗ no package manager detected for this OS; install $pkg manually" >&2
+ return 1
+ }
+ if [ -z "$cmd" ]; then
+ echo "✗ no package manager detected for this OS; install $pkg manually" >&2
+ return 1
+ fi
+ echo "+ $cmd"
+ if [ "$DRY_RUN" -eq 0 ]; then
+ eval "$cmd"
+ fi
+ else
+ # Legacy path: preserve existing behavior for mid-upgrade users.
+ case "$(uname -s)" in
+ Darwin*) [ "$DRY_RUN" -eq 0 ] && brew install "$pkg" || echo "+ brew install $pkg" ;;
+ Linux*) [ "$DRY_RUN" -eq 0 ] && sudo apt-get install -y "$pkg" || echo "+ sudo apt-get install -y $pkg" ;;
+ *) echo "✗ unsupported OS: $(uname -s)" >&2; return 1 ;;
+ esac
fi
- echo "✗ Could not install gog. Options:" >&2
- echo " 1. Ask Sam (internal team) for the latest release binary" >&2
- echo " 2. Request access to github.com/example/gog" >&2
- echo " 3. Use the Gmail MCP fallback (read-only, drafts only)" >&2
- return 2
}
-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
+# ─── Special-case tools that aren't on a package manager ────────────────────
+# Some tools require custom install paths (install scripts, npm, source).
+# Returns 0 on success, 1 on hard failure, 2 when user must install manually.
+install_special() {
+ local tool="$1" os=""
+ if declare -F ops_os >/dev/null 2>&1; then os="$(ops_os)"; fi
+
+ case "$tool" in
+ doppler)
+ # Doppler ships an official install script; use pkg mgr where it exists.
+ local mgr=""
+ if declare -F ops_pkg_mgr >/dev/null 2>&1; then mgr="$(ops_pkg_mgr)"; fi
+ case "$mgr" in
+ brew) echo "+ brew install dopplerhq/cli/doppler"
+ [ "$DRY_RUN" -eq 0 ] && brew install dopplerhq/cli/doppler ;;
+ scoop) echo "+ scoop bucket add doppler https://github.com/DopplerHQ/scoop-doppler.git && scoop install doppler"
+ [ "$DRY_RUN" -eq 0 ] && { scoop bucket add doppler https://github.com/DopplerHQ/scoop-doppler.git 2>/dev/null || true; scoop install doppler; } ;;
+ winget) echo "+ winget install -e --id Doppler.Doppler"
+ [ "$DRY_RUN" -eq 0 ] && winget install -e --id Doppler.Doppler ;;
+ *) echo "+ curl -Ls https://cli.doppler.com/install.sh | sh"
+ [ "$DRY_RUN" -eq 0 ] && curl -Ls https://cli.doppler.com/install.sh | sh ;;
+ esac
+ return 0 ;;
+ sentry-cli)
+ # Preferred install path is npm (cross-platform, no pkg mgr needed).
+ if [ "$os" = "macos" ] && command -v brew >/dev/null 2>&1; then
+ echo "+ brew install getsentry/tools/sentry-cli"
+ [ "$DRY_RUN" -eq 0 ] && brew install getsentry/tools/sentry-cli
+ return 0
+ fi
+ if command -v npm >/dev/null 2>&1; then
+ echo "+ npm install -g @sentry/cli"
+ [ "$DRY_RUN" -eq 0 ] && npm install -g @sentry/cli
+ return 0
+ fi
+ echo "○ sentry-cli needs npm or Homebrew — install Node first, then retry." >&2
+ return 2 ;;
+ wacli)
+ # wacli isn't on any package manager yet — point users to source install.
+ echo "○ wacli is not on any package manager — install from source:" >&2
+ echo " git clone https://github.com/wacli/wacli && cd wacli && ./install.sh" >&2
+ return 2 ;;
+ brew)
+ # Homebrew has its own bootstrap installer.
+ echo "+ /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
+ if [ "$DRY_RUN" -eq 0 ]; then
+ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
+ fi
+ return 0 ;;
+ *) return 127 ;; # 127 = "not a special case; caller should use install_pkg"
+ esac
+}
+
+# ─── Per-tool install driver ────────────────────────────────────────────────
+install_tool() {
+ local tool="$1" mgr="" pkg rc
+ if declare -F ops_pkg_mgr >/dev/null 2>&1; then mgr="$(ops_pkg_mgr)"; fi
+
+ # Try special-case installers first (doppler, sentry-cli, wacli, brew).
+ install_special "$tool"
+ rc=$?
+ if [ "$rc" -ne 127 ]; then
+ return "$rc"
fi
+
+ # Default path: resolve pkg name + invoke pkg manager.
+ pkg="$(resolve_pkg_name "$tool" "$mgr")"
+ install_pkg "$pkg"
}
-for tool in "$@"; do
+# ─── JSON result accumulator ────────────────────────────────────────────────
+json_results=()
+
+# ─── Main loop ──────────────────────────────────────────────────────────────
+if [ "${#TOOLS[@]}" -eq 0 ]; then
+ echo "✗ No tools specified. Usage: $(basename "$0") [--dry-run] <tool>..." >&2
+ exit 2
+fi
+
+overall_rc=0
+for tool in "${TOOLS[@]}"; do
if command -v "$tool" >/dev/null 2>&1; then
echo "✓ $tool already installed"
+ json_results+=("{\"tool\":\"$tool\",\"status\":\"present\"}")
continue
fi
echo "⏳ Installing $tool..."
- case "$PLATFORM" in
- darwin) install_mac "$tool" ;;
- linux) install_linux "$tool" ;;
- *) echo "✗ Unsupported platform: $PLATFORM" >&2; exit 1 ;;
- esac
+ if install_tool "$tool"; then
+ echo "✓ $tool installed"
+ json_results+=("{\"tool\":\"$tool\",\"status\":\"installed\"}")
+ else
+ rc=$?
+ if [ "$rc" -eq 2 ]; then
+ json_results+=("{\"tool\":\"$tool\",\"status\":\"manual\"}")
+ else
+ json_results+=("{\"tool\":\"$tool\",\"status\":\"failed\"}")
+ overall_rc=1
+ fi
+ fi
done
+
+# ─── Optional JSON output (for setup skill to parse) ────────────────────────
+if [ "$JSON" -eq 1 ]; then
+ printf '['
+ for i in "${!json_results[@]}"; do
+ [ "$i" -gt 0 ] && printf ','
+ printf '%s' "${json_results[$i]}"
+ done
+ printf ']\n'
+fi
+
+exit "$overall_rc"
diff --git a/claude-ops/lib/opener.mjs b/claude-ops/lib/opener.mjs
new file mode 100644
index 00000000..155ca0ea
--- /dev/null
+++ b/claude-ops/lib/opener.mjs
@@ -0,0 +1,216 @@
+// opener.mjs
+//
+// Node ESM mirror of lib/opener.sh — cross-OS helpers for launching URLs,
+// files, and directories in the user's default handler. Zero npm deps; relies
+// on the sibling os-detect.mjs for platform resolution.
+//
+// Usage as a module:
+// import { openUrl, openDir, openTarget } from "./opener.mjs";
+// await openUrl("https://example.com");
+//
+// Usage as a CLI:
+// node lib/opener.mjs url https://example.com
+// node lib/opener.mjs dir /path/to/folder
+// node lib/opener.mjs open anything
+//
+// Design notes:
+// - Spawned processes are detached + unrefed so parent exits cleanly even
+// if the opener lingers (common with xdg-open forking a browser).
+// - We do NOT try to detect whether the URL is already open somewhere; that
+// is intentionally out of scope.
+// - On Windows we spawn `cmd.exe /c start "" <target>` — the empty quoted
+// string is `start`'s title placeholder; without it, a path/URL
+// containing spaces gets eaten as the window title.
+
+import { spawn, spawnSync } from "node:child_process";
+import { promises as fsp } from "node:fs";
+import process from "node:process";
+import { osId, opener } from "./os-detect.mjs";
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Mirror of hasBin() in os-detect.mjs, repeated locally so this module stays
+ * self-contained and doesn't pull private helpers out of the sibling file.
+ * @param {string} name
+ * @returns {boolean}
+ */
+function hasBin(name) {
+ try {
+ if (process.platform === "win32") {
+ return spawnSync("where.exe", [name], { stdio: "ignore" }).status === 0;
+ }
+ return (
+ spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
+ stdio: "ignore",
+ }).status === 0
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Resolve the opener command, preferring os-detect.mjs's `opener()` and
+ * falling back to a hardcoded cascade if that returns null.
+ * @returns {string|null}
+ */
+function resolveOpener() {
+ const detected = opener();
+ if (detected) return detected;
+
+ if (hasBin("open")) return "open";
+ if (hasBin("wslview")) return "wslview";
+ if (hasBin("xdg-open")) return "xdg-open";
+ if (hasBin("cmd.exe")) return "cmd.exe /c start";
+ return null;
+}
+
+/**
+ * Split a command string like "cmd.exe /c start" into [program, ...args].
+ * Returns null for empty input.
+ * @param {string} cmd
+ * @returns {[string, string[]]|null}
+ */
+function splitCmd(cmd) {
+ if (!cmd) return null;
+ const parts = cmd.trim().split(/\s+/);
+ const [program, ...args] = parts;
+ return [program, args];
+}
+
+/**
+ * Log a breadcrumb to stderr in the same shape as opener.sh.
+ * @param {string} cmd
+ * @param {string} target
+ */
+function logOpen(cmd, target) {
+ process.stderr.write(`opener: using ${cmd} for ${target}\n`);
+}
+
+// ---------------------------------------------------------------------------
+// Public API
+// ---------------------------------------------------------------------------
+
+/**
+ * Open an arbitrary target (URL, file, dir) in the host's default handler.
+ * @param {string} target
+ * @returns {Promise<{ok: boolean, command: string|null, target: string}>}
+ */
+export async function openTarget(target) {
+ if (!target) {
+ process.stderr.write("opener: missing target\n");
+ return { ok: false, command: null, target: "" };
+ }
+
+ const cmd = resolveOpener();
+ if (!cmd) {
+ process.stderr.write("opener: no URL opener available on this host\n");
+ return { ok: false, command: null, target };
+ }
+
+ logOpen(cmd, target);
+
+ try {
+ // Windows: always use `cmd.exe /c start "" <target>` with the empty title.
+ const isWindowsStart =
+ cmd === "cmd.exe /c start" ||
+ osId() === "windows" ||
+ process.platform === "win32";
+
+ if (isWindowsStart && cmd.includes("start")) {
+ const child = spawn("cmd.exe", ["/c", "start", "", target], {
+ detached: true,
+ stdio: "ignore",
+ windowsVerbatimArguments: false,
+ });
+ child.unref();
+ return { ok: true, command: cmd, target };
+ }
+
+ const split = splitCmd(cmd);
+ if (!split) {
+ return { ok: false, command: cmd, target };
+ }
+ const [program, extraArgs] = split;
+ const child = spawn(program, [...extraArgs, target], {
+ detached: true,
+ stdio: "ignore",
+ });
+ child.unref();
+ return { ok: true, command: cmd, target };
+ } catch (err) {
+ process.stderr.write(`opener: spawn failed: ${err?.message || err}\n`);
+ return { ok: false, command: cmd, target };
+ }
+}
+
+/**
+ * Open a URL. Scheme is validated — only http(s), mailto:, tel: are accepted.
+ * @param {string} url
+ * @returns {Promise<{ok: boolean, command: string|null, target: string}>}
+ */
+export async function openUrl(url) {
+ if (!url) {
+ process.stderr.write("opener: missing url\n");
+ return { ok: false, command: null, target: "" };
+ }
+ if (!/^https?:\/\/|^mailto:|^tel:/.test(url)) {
+ process.stderr.write(`opener: refusing to open non-URL scheme: ${url}\n`);
+ return { ok: false, command: null, target: url };
+ }
+ return openTarget(url);
+}
+
+/**
+ * Open a directory. Path is validated for existence and must be a directory.
+ * @param {string} pathStr
+ * @returns {Promise<{ok: boolean, command: string|null, target: string}>}
+ */
+export async function openDir(pathStr) {
+ if (!pathStr) {
+ process.stderr.write("opener: missing directory path\n");
+ return { ok: false, command: null, target: "" };
+ }
+ try {
+ const st = await fsp.stat(pathStr);
+ if (!st.isDirectory()) {
+ process.stderr.write(`opener: not a directory: ${pathStr}\n`);
+ return { ok: false, command: null, target: pathStr };
+ }
+ } catch {
+ process.stderr.write(`opener: directory does not exist: ${pathStr}\n`);
+ return { ok: false, command: null, target: pathStr };
+ }
+ return openTarget(pathStr);
+}
+
+// ---------------------------------------------------------------------------
+// CLI entry
+// ---------------------------------------------------------------------------
+
+const invokedDirectly =
+ process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
+
+if (invokedDirectly) {
+ const [, , sub, ...rest] = process.argv;
+ const target = rest[0] || "";
+ let result;
+ switch (sub) {
+ case "open":
+ result = await openTarget(target);
+ break;
+ case "url":
+ result = await openUrl(target);
+ break;
+ case "dir":
+ result = await openDir(target);
+ break;
+ default:
+ process.stderr.write("usage: opener.mjs {open|url|dir} <target>\n");
+ process.exit(2);
+ }
+ process.exit(result.ok ? 0 : 1);
+}
diff --git a/claude-ops/lib/opener.sh b/claude-ops/lib/opener.sh
new file mode 100644
index 00000000..70735c99
--- /dev/null
+++ b/claude-ops/lib/opener.sh
@@ -0,0 +1,135 @@
+#!/usr/bin/env bash
+# opener.sh — Cross-OS URL / file / directory opener for claude-ops.
+#
+# Thin wrapper around os-detect.sh's `ops_opener` that actually spawns the
+# resolved command and handles the edge cases each host platform cares about.
+# Safe to source or invoke directly.
+#
+# Sourced usage:
+# source "$(dirname "$0")/../lib/opener.sh"
+# ops_open_url "https://example.com"
+#
+# CLI usage:
+# bash opener.sh url https://example.com
+# bash opener.sh dir /path/to/folder
+# bash opener.sh open anything
+#
+# Design notes:
+# - Never blocks: commands are spawned in the background with stdin/stdout
+# detached so OAuth prompts and browser launches don't hang the caller.
+# - Logs the resolved command to stderr for debuggability.
+# - Returns non-zero on missing opener or validation failures; callers can
+# decide whether that's fatal.
+
+# ─── Re-source guard ────────────────────────────────────────────────────────
+if [[ -n "${__OPS_OPENER_SH_LOADED__:-}" ]]; then
+ return 0 2>/dev/null || exit 0
+fi
+__OPS_OPENER_SH_LOADED__=1
+
+# Only tighten shell options when run directly; preserve caller's env when sourced.
+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
+ set -euo pipefail
+fi
+
+# ─── Pull in os-detect.sh (for ops_opener / ops_os) ─────────────────────────
+if [[ -z "${__OPS_OS_DETECT_SH_LOADED__:-}" ]]; then
+ # shellcheck source=./os-detect.sh
+ source "$(dirname "${BASH_SOURCE[0]}")/os-detect.sh"
+fi
+
+# ─── __ops_open_log: stderr breadcrumb for debugging ────────────────────────
+__ops_open_log() {
+ printf 'opener: using %s for %s\n' "$1" "$2" >&2
+}
+
+# ─── __ops_resolve_opener: pick a command, honoring os-detect first ─────────
+# Echoes the full opener command string, or empty if none.
+__ops_resolve_opener() {
+ local cmd=""
+ cmd="$(ops_opener 2>/dev/null || true)"
+ if [[ -n "$cmd" ]]; then
+ echo "$cmd"
+ return 0
+ fi
+ # Hardcoded fallback cascade — first one that exists wins.
+ if command -v open >/dev/null 2>&1; then echo "open"; return 0; fi
+ if command -v wslview >/dev/null 2>&1; then echo "wslview"; return 0; fi
+ if command -v xdg-open >/dev/null 2>&1; then echo "xdg-open"; return 0; fi
+ if command -v cmd.exe >/dev/null 2>&1; then echo "cmd.exe /c start"; return 0; fi
+ echo ""
+ return 1
+}
+
+# ─── ops_open: open any target in the host's default handler ────────────────
+# Usage: ops_open <target>
+# Returns 0 on spawn success, 1 on any failure.
+ops_open() {
+ local target="${1:-}"
+ if [[ -z "$target" ]]; then
+ echo "opener: missing target" >&2
+ return 1
+ fi
+
+ local cmd
+ if ! cmd="$(__ops_resolve_opener)" || [[ -z "$cmd" ]]; then
+ echo "opener: no URL opener available on this host" >&2
+ return 1
+ fi
+
+ __ops_open_log "$cmd" "$target"
+
+ # "cmd.exe /c start" needs a title placeholder so targets with spaces don't
+ # get mis-parsed as the window title.
+ if [[ "$cmd" == "cmd.exe /c start" ]]; then
+ cmd.exe /c start "" "$target" >/dev/null 2>&1 &
+ return 0
+ fi
+
+ # Split on whitespace to support multi-token commands. `exec`-less background.
+ # shellcheck disable=SC2086
+ $cmd "$target" >/dev/null 2>&1 &
+ return 0
+}
+
+# ─── ops_open_url: URL-only variant with scheme validation ──────────────────
+ops_open_url() {
+ local url="${1:-}"
+ if [[ -z "$url" ]]; then
+ echo "opener: missing url" >&2
+ return 1
+ fi
+ if [[ ! "$url" =~ ^https?://|^mailto:|^tel: ]]; then
+ echo "opener: refusing to open non-URL scheme: $url" >&2
+ return 1
+ fi
+ ops_open "$url"
+}
+
+# ─── ops_open_dir: directory-only variant with existence check ──────────────
+ops_open_dir() {
+ local dir="${1:-}"
+ if [[ -z "$dir" ]]; then
+ echo "opener: missing directory path" >&2
+ return 1
+ fi
+ if [[ ! -e "$dir" ]]; then
+ echo "opener: directory does not exist: $dir" >&2
+ return 1
+ fi
+ if [[ ! -d "$dir" ]]; then
+ echo "opener: not a directory: $dir" >&2
+ return 1
+ fi
+ ops_open "$dir"
+}
+
+# ─── CLI entry ──────────────────────────────────────────────────────────────
+if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
+ case "${1:-}" in
+ open) shift; ops_open "$@" ;;
+ url) shift; ops_open_url "$@" ;;
+ dir) shift; ops_open_dir "$@" ;;
+ *) echo "usage: opener.sh {open|url|dir} <target>" >&2; exit 2 ;;
+ esac
+fi
diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.sh
index 7d5ffd24..ce37f0d6 100755
--- a/claude-ops/scripts/ops-daemon.sh
+++ b/claude-ops/scripts/ops-daemon.sh
@@ -1,9 +1,15 @@
#!/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
+# daemon registration: launchd on macOS, systemd on Linux, Task Scheduler on Windows
set -euo pipefail
+# ── OS detection (sourced) ────────────────────────────────────────────────
+# Resolves to the claude-ops plugin root (parent of scripts/).
+SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+# shellcheck disable=SC1091
+[ -r "$SCRIPT_DIR/lib/os-detect.sh" ] && . "$SCRIPT_DIR/lib/os-detect.sh"
+
DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
LOG_DIR="$DATA_DIR/logs"
LOG="$LOG_DIR/ops-daemon.log"
@@ -15,11 +21,45 @@ DAEMON_START=$(date +%s)
mkdir -p "$LOG_DIR"
mkdir -p "$DATA_DIR/cache"
+# ── Portable shim helpers (GNU vs BSD) ───────────────────────────────────
+# _file_size: echoes byte size of a file. GNU `stat -c%s` vs BSD `stat -f%z`.
+_file_size() {
+ if stat --version >/dev/null 2>&1; then
+ stat -c%s "$1" # GNU (Linux, Cygwin, busybox w/ coreutils)
+ else
+ stat -f%z "$1" # BSD (macOS, *BSD)
+ fi
+}
+
+# _date_days_ago: echoes a date N days before now in the given format.
+# $1 = days (positive integer)
+# $2 = date format string (default: +%Y-%m-%d)
+_date_days_ago() {
+ local days="$1"
+ local fmt="${2:-+%Y-%m-%d}"
+ if date -d "1 day ago" >/dev/null 2>&1; then
+ date -d "$days days ago" "$fmt" # GNU
+ else
+ date -v-"${days}"d "$fmt" # BSD
+ fi
+}
+
+# _date_from_epoch: echoes ISO-8601 UTC for an epoch timestamp.
+# $1 = epoch seconds
+_date_from_epoch() {
+ local epoch="$1"
+ if date --version >/dev/null 2>&1; then
+ date -u -d "@$epoch" +%Y-%m-%dT%H:%M:%SZ # GNU
+ else
+ date -u -r "$epoch" +%Y-%m-%dT%H:%M:%SZ # BSD
+ fi
+}
+
# ── 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
+ if [[ -f "$LOG" ]] && [[ $(_file_size "$LOG" 2>/dev/null || echo 0) -gt $MAX_LOG_SIZE ]]; then
mv "$LOG" "$LOG.old"
log "LOG: rotated (exceeded 2MB)"
fi
@@ -222,8 +262,8 @@ write_daemon_health() {
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 "")
+ [[ -n "$next_run" ]] && next_iso=$(_date_from_epoch "$next_run" 2>/dev/null || echo "")
+ [[ -n "$last_run" ]] && last_iso=$(_date_from_epoch "$last_run" 2>/dev/null || echo "")
services_json+="\"$name\": {\"status\": \"$status\", \"next_run\": \"$next_iso\", \"last_run\": \"$last_iso\"}"
else
local pid_val
@@ -434,7 +474,7 @@ except: print('')
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 "
+ new_count=$(wacli messages list --after="${last_ts:-$(_date_days_ago 1 +%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 []
@@ -602,6 +642,225 @@ PYEOF
log "BRAIN: project health cache updated"
}
+# ── Daemon registration (cross-OS) ────────────────────────────────────────
+# On macOS we load a launchd agent; on Linux a systemd --user unit + timer;
+# on Windows a Task Scheduler (schtasks) entry. Each path is best-effort and
+# returns a non-zero exit if the host service manager isn't reachable — the
+# caller (setup.sh / user) can decide how to surface the warning.
+
+# Resolve plugin-root-relative paths for daemon scripts (so the unit files
+# embed absolute paths that still work when invoked by another user context).
+OPS_DAEMON_SCRIPT="$SCRIPT_DIR/scripts/ops-daemon.sh"
+OPS_KEEPALIVE_SCRIPT="$SCRIPT_DIR/scripts/wacli-keepalive.sh"
+
+install_daemon_launchd() {
+ command -v launchctl >/dev/null 2>&1 || {
+ echo "install_daemon_launchd: launchctl not found on PATH" >&2
+ return 1
+ }
+ local agents_dir="$HOME/Library/LaunchAgents"
+ mkdir -p "$agents_dir"
+
+ local daemon_plist_src="$SCRIPT_DIR/scripts/com.claude-ops.daemon.plist"
+ local keepalive_plist_src="$SCRIPT_DIR/scripts/com.claude-ops.wacli-keepalive.plist"
+ local daemon_plist_dst="$agents_dir/com.claude-ops.daemon.plist"
+ local keepalive_plist_dst="$agents_dir/com.claude-ops.wacli-keepalive.plist"
+
+ # Substitute placeholders while copying.
+ if [[ -f "$daemon_plist_src" ]]; then
+ sed \
+ -e "s|__DAEMON_SCRIPT_PATH__|$OPS_DAEMON_SCRIPT|g" \
+ -e "s|__LOG_DIR__|$LOG_DIR|g" \
+ -e "s|__HOME__|$HOME|g" \
+ "$daemon_plist_src" > "$daemon_plist_dst"
+ launchctl unload -w "$daemon_plist_dst" 2>/dev/null || true
+ launchctl load -w "$daemon_plist_dst"
+ log "INSTALL(launchd): loaded $daemon_plist_dst"
+ fi
+
+ if [[ -f "$keepalive_plist_src" ]]; then
+ sed \
+ -e "s|__KEEPALIVE_SCRIPT_PATH__|$OPS_KEEPALIVE_SCRIPT|g" \
+ -e "s|__LOG_DIR__|$LOG_DIR|g" \
+ -e "s|__HOME__|$HOME|g" \
+ "$keepalive_plist_src" > "$keepalive_plist_dst"
+ launchctl unload -w "$keepalive_plist_dst" 2>/dev/null || true
+ launchctl load -w "$keepalive_plist_dst"
+ log "INSTALL(launchd): loaded $keepalive_plist_dst"
+ fi
+}
+
+uninstall_daemon_launchd() {
+ command -v launchctl >/dev/null 2>&1 || {
+ echo "uninstall_daemon_launchd: launchctl not found on PATH" >&2
+ return 1
+ }
+ local agents_dir="$HOME/Library/LaunchAgents"
+ local f
+ for f in com.claude-ops.daemon.plist com.claude-ops.wacli-keepalive.plist; do
+ if [[ -f "$agents_dir/$f" ]]; then
+ launchctl unload -w "$agents_dir/$f" 2>/dev/null || true
+ rm -f "$agents_dir/$f"
+ log "UNINSTALL(launchd): removed $agents_dir/$f"
+ fi
+ done
+}
+
+install_daemon_systemd() {
+ command -v systemctl >/dev/null 2>&1 || {
+ echo "install_daemon_systemd: systemctl not found on PATH" >&2
+ return 1
+ }
+ local unit_dir="$HOME/.config/systemd/user"
+ mkdir -p "$unit_dir"
+
+ # Main daemon: a oneshot service triggered by a 5-minute timer that runs
+ # ops-daemon.sh in single-pass mode (--run-once). This mirrors the
+ # ThrottleInterval/KeepAlive behavior of the launchd plist without holding
+ # a persistent bash process in user-session memory between firings.
+ cat > "$unit_dir/claude-ops.service" <<EOF
+[Unit]
+Description=claude-ops background brain (ops-daemon single pass)
+After=default.target
+
+[Service]
+Type=oneshot
+ExecStart=/usr/bin/env bash $OPS_DAEMON_SCRIPT --run-once
+StandardOutput=append:$LOG_DIR/ops-daemon-stdout.log
+StandardError=append:$LOG_DIR/ops-daemon-stderr.log
+Environment=HOME=$HOME
+EOF
+
+ cat > "$unit_dir/claude-ops.timer" <<EOF
+[Unit]
+Description=Fire claude-ops ops-daemon every 5 minutes
+After=default.target
+
+[Timer]
+OnBootSec=30s
+OnUnitActiveSec=5min
+AccuracySec=30s
+Unit=claude-ops.service
+
+[Install]
+WantedBy=timers.target
+EOF
+
+ # wacli-keepalive: persistent service (Restart=always) — no timer needed.
+ cat > "$unit_dir/claude-ops-wacli-keepalive.service" <<EOF
+[Unit]
+Description=claude-ops wacli keepalive
+After=default.target
+
+[Service]
+Type=simple
+ExecStart=/usr/bin/env bash $OPS_KEEPALIVE_SCRIPT
+Restart=always
+RestartSec=60
+StandardOutput=append:$LOG_DIR/wacli-launchd-stdout.log
+StandardError=append:$LOG_DIR/wacli-launchd-stderr.log
+Environment=HOME=$HOME
+
+[Install]
+WantedBy=default.target
+EOF
+
+ systemctl --user daemon-reload
+ systemctl --user enable --now claude-ops.timer
+ systemctl --user enable --now claude-ops-wacli-keepalive.service || true
+ log "INSTALL(systemd): enabled claude-ops.timer + claude-ops-wacli-keepalive.service"
+}
+
+uninstall_daemon_systemd() {
+ command -v systemctl >/dev/null 2>&1 || {
+ echo "uninstall_daemon_systemd: systemctl not found on PATH" >&2
+ return 1
+ }
+ local unit_dir="$HOME/.config/systemd/user"
+ systemctl --user disable --now claude-ops.timer 2>/dev/null || true
+ systemctl --user disable --now claude-ops.service 2>/dev/null || true
+ systemctl --user disable --now claude-ops-wacli-keepalive.service 2>/dev/null || true
+ rm -f "$unit_dir/claude-ops.service" \
+ "$unit_dir/claude-ops.timer" \
+ "$unit_dir/claude-ops-wacli-keepalive.service"
+ systemctl --user daemon-reload 2>/dev/null || true
+ log "UNINSTALL(systemd): removed claude-ops units"
+}
+
+install_daemon_schtasks() {
+ # Windows best-effort: prefer bash.exe (Git Bash / WSL bash) since the daemon
+ # is a bash script. If unavailable, fall back to pwsh wrapper. Users on real
+ # WSL should prefer install_daemon_systemd from inside the WSL shell — it
+ # gives proper timer semantics instead of Task Scheduler's 5-minute floor.
+ local schtasks_bin
+ if command -v schtasks >/dev/null 2>&1; then
+ schtasks_bin="schtasks"
+ elif command -v schtasks.exe >/dev/null 2>&1; then
+ schtasks_bin="schtasks.exe"
+ else
+ echo "install_daemon_schtasks: schtasks not found on PATH" >&2
+ return 1
+ fi
+
+ local run_cmd
+ if command -v bash.exe >/dev/null 2>&1 || command -v bash >/dev/null 2>&1; then
+ run_cmd="bash.exe $OPS_DAEMON_SCRIPT --run-once"
+ else
+ # pwsh wrapper fallback — expects the user to have bash reachable inside
+ # the invoked shell (WSL default, Git Bash, etc.).
+ run_cmd="pwsh.exe -NoProfile -File $SCRIPT_DIR/scripts/ops-daemon-wrapper.ps1"
+ fi
+
+ "$schtasks_bin" /Create /F /SC MINUTE /MO 5 \
+ /TN "ClaudeOpsDaemon" \
+ /TR "$run_cmd" \
+ || { echo "install_daemon_schtasks: schtasks /Create failed" >&2; return 1; }
+
+ local keepalive_cmd="bash.exe $OPS_KEEPALIVE_SCRIPT"
+ "$schtasks_bin" /Create /F /SC MINUTE /MO 1 \
+ /TN "ClaudeOpsWacliKeepalive" \
+ /TR "$keepalive_cmd" \
+ || true
+ log "INSTALL(schtasks): registered ClaudeOpsDaemon + ClaudeOpsWacliKeepalive"
+}
+
+uninstall_daemon_schtasks() {
+ local schtasks_bin
+ if command -v schtasks >/dev/null 2>&1; then
+ schtasks_bin="schtasks"
+ elif command -v schtasks.exe >/dev/null 2>&1; then
+ schtasks_bin="schtasks.exe"
+ else
+ echo "uninstall_daemon_schtasks: schtasks not found on PATH" >&2
+ return 1
+ fi
+ "$schtasks_bin" /Delete /F /TN "ClaudeOpsDaemon" 2>/dev/null || true
+ "$schtasks_bin" /Delete /F /TN "ClaudeOpsWacliKeepalive" 2>/dev/null || true
+ log "UNINSTALL(schtasks): removed ClaudeOpsDaemon + ClaudeOpsWacliKeepalive"
+}
+
+install_daemon() {
+ local os
+ os="$(ops_os 2>/dev/null || uname -s)"
+ case "$os" in
+ macos|Darwin*) install_daemon_launchd ;;
+ debian|fedora|arch|suse|alpine|linux|wsl|Linux*) install_daemon_systemd ;;
+ windows|MINGW*|MSYS*|CYGWIN*) install_daemon_schtasks ;;
+ *) echo "install_daemon: unsupported OS '$os' for daemon registration" >&2; return 1 ;;
+ esac
+}
+
+uninstall_daemon() {
+ local os
+ os="$(ops_os 2>/dev/null || uname -s)"
+ case "$os" in
+ macos|Darwin*) uninstall_daemon_launchd ;;
+ debian|fedora|arch|suse|alpine|linux|wsl|Linux*) uninstall_daemon_systemd ;;
+ windows|MINGW*|MSYS*|CYGWIN*) uninstall_daemon_schtasks ;;
+ *) echo "uninstall_daemon: unsupported OS '$os' for daemon registration" >&2; return 1 ;;
+ esac
+}
+
# ── Graceful shutdown ─────────────────────────────────────────────────────
cleanup() {
log "SHUTDOWN: SIGTERM received — stopping all services"
@@ -616,8 +875,54 @@ cleanup() {
trap cleanup SIGTERM SIGINT
+# ── CLI dispatch ──────────────────────────────────────────────────────────
+# Flags are positional and mutually exclusive-ish. When none are given we
+# fall through to the classic "enter monitor loop" behavior so the existing
+# launchd plist (which invokes `bash ops-daemon.sh` with no arguments) keeps
+# working unchanged.
+OPS_RUN_ONCE=0
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --os)
+ # Print the detected OS bucket (for setup scripts & debugging).
+ ops_os 2>/dev/null || uname -s
+ exit 0
+ ;;
+ --install)
+ install_daemon
+ exit $?
+ ;;
+ --uninstall)
+ uninstall_daemon
+ exit $?
+ ;;
+ --run-once)
+ # Single-pass execution: for systemd timer / schtasks invocations that
+ # fire the daemon periodically instead of keeping it resident.
+ OPS_RUN_ONCE=1
+ shift
+ ;;
+ -h|--help)
+ cat <<EOF
+Usage: $(basename "$0") [--os|--install|--uninstall|--run-once]
+ (no args) Start the resident daemon monitor loop (launchd-compatible).
+ --os Print the detected OS bucket and exit.
+ --install Register the daemon with the host service manager
+ (launchd on macOS, systemd --user on Linux, schtasks on Windows).
+ --uninstall Remove the host service manager registration.
+ --run-once Run one intelligence + health pass and exit (for timer-based hosts).
+EOF
+ exit 0
+ ;;
+ *)
+ echo "Unknown argument: $1 (try --help)" >&2
+ exit 2
+ ;;
+ esac
+done
+
# ── Main ──────────────────────────────────────────────────────────────────
-log "START: ops-daemon pid=$$ starting"
+log "START: ops-daemon pid=$$ starting (run_once=$OPS_RUN_ONCE)"
rotate_log
if ! load_services_config; then
@@ -625,7 +930,9 @@ if ! load_services_config; then
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
+ # In --run-once mode we exit after writing the health file; otherwise
+ # sleep forever until SIGTERM (launchd/systemd simple-mode keeps us alive).
+ if [[ $OPS_RUN_ONCE -eq 1 ]]; then exit 0; fi
while true; do sleep 30; done
fi
@@ -683,5 +990,14 @@ while true; do
prefetch_project_health # Every 10 min: git/branch status per registered repo
write_daemon_health
+
+ # In --run-once mode we return after a single intelligence + health pass
+ # so timer-driven hosts (systemd .timer, Task Scheduler) don't accumulate
+ # overlapping long-lived daemon processes.
+ if [[ $OPS_RUN_ONCE -eq 1 ]]; then
+ log "RUN-ONCE: single pass complete — exiting"
+ exit 0
+ fi
+
sleep 30
done
diff --git a/claude-ops/scripts/ops-memory-extractor.sh b/claude-ops/scripts/ops-memory-extractor.sh
index e13839db..5ef84464 100755
--- a/claude-ops/scripts/ops-memory-extractor.sh
+++ b/claude-ops/scripts/ops-memory-extractor.sh
@@ -4,6 +4,17 @@
# Runs every 30 min via ops-daemon cron service.
set -euo pipefail
+# ── Portable shell helpers ────────────────────────────────────────────────────
+_date_days_ago() {
+ # Portable: echoes "N days ago" in the given format (default YYYY-MM-DD)
+ local days=$1 fmt=${2:-+%Y-%m-%d}
+ if date -d "$days days ago" "$fmt" >/dev/null 2>&1; then
+ date -d "$days days ago" "$fmt" # GNU coreutils (Linux, Windows/Git Bash)
+ else
+ date -v-"${days}"d "$fmt" # BSD (macOS)
+ fi
+}
+
# ── Config ────────────────────────────────────────────────────────────────────
MEMORIES_DIR="${HOME}/.claude/plugins/data/ops-ops-marketplace/memories"
HEALTH_FILE="${MEMORIES_DIR}/.health"
@@ -57,7 +68,7 @@ resolve_api_key() {
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")
+ yesterday=$(TZ=UTC _date_days_ago 1 "+%Y-%m-%d")
# WhatsApp via wacli
if command -v wacli &>/dev/null; then