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(pocket): decision-log hook + ops-pocket-decisions.py (preserve deployed-only work) (#369)

Aurora Capitalf4061bbafc6c
diff --git a/claude-ops/scripts/ops-pocket-decisions.py b/claude-ops/scripts/ops-pocket-decisions.py
new file mode 100644
index 00000000..d1d125d6
--- /dev/null
+++ b/claude-ops/scripts/ops-pocket-decisions.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""ops-pocket-decisions — append-only decision log for the Pocket pipeline.
+
+Every classification decision (triage ACT/DRAFT/DROP/ASK, and every
+ingest-time event-seen-but-no-triage) lands here so Sam can audit what
+Pocket reviewed even when it decided not to act.
+
+Path: <POCKET_STATE_DIR>/decisions/YYYY-MM-DD.jsonl
+"""
+
+from __future__ import annotations
+import json
+import os
+from datetime import datetime, timezone
+from pathlib import Path
+
+HOME = Path(os.path.expanduser("~"))
+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))
+DECISIONS_DIR = STATE_DIR / "decisions"
+
+
+def write_decision(d: dict) -> None:
+ DECISIONS_DIR.mkdir(parents=True, exist_ok=True)
+ # UTC to stay consistent with the webhook journal (date -u); the date bucket
+ # below slices ts[:10], so a local tz would split a UTC day across two files.
+ ts = d.get("ts") or datetime.now(timezone.utc).isoformat()
+ d["ts"] = ts
+ date = ts[:10]
+ with open(DECISIONS_DIR / f"{date}.jsonl", "a") as f:
+ f.write(json.dumps(d) + "\n")
+
+
+def make(
+ event_type: str,
+ recording_id: str = "",
+ title: str = "",
+ summary_excerpt: str = "",
+ classification: str = "REVIEWED",
+ confidence: float = 1.0,
+ reasoning: str = "",
+ action_taken: str | None = None,
+ downstream_agent_id: str | None = None,
+ notion_page_id: str | None = None,
+ notion_page_url: str | None = None,
+ is_long: bool = False,
+ model: str = "",
+ payload_bytes: int = 0,
+) -> dict:
+ return {
+ "ts": datetime.now(timezone.utc).isoformat(),
+ "recording_id": recording_id,
+ "event_type": event_type,
+ "title": title,
+ "summary_excerpt": summary_excerpt[:280],
+ "classification": classification,
+ "confidence": confidence,
+ "reasoning": reasoning,
+ "action_taken": action_taken,
+ "downstream_agent_id": downstream_agent_id,
+ "notion_page_id": notion_page_id,
+ "notion_page_url": notion_page_url,
+ "is_long": is_long,
+ "model": model,
+ "payload_bytes": payload_bytes,
+ }
diff --git a/claude-ops/scripts/ops-pocket-triage.py b/claude-ops/scripts/ops-pocket-triage.py
index 1c474c3f..cf912a83 100755
--- a/claude-ops/scripts/ops-pocket-triage.py
+++ b/claude-ops/scripts/ops-pocket-triage.py
@@ -41,6 +41,7 @@ Files (under POCKET_STATE_DIR):
review.jsonl OUT — ASK queue for Sam
triage-decisions.jsonl OUT — full audit of every decision + thinking
"""
+
from __future__ import annotations
import json
@@ -58,11 +59,24 @@ LOG_PREFIX = "[ops-pocket-triage]"
# === Phase 2 hook: decision log =====================================
try:
import importlib.util as _ilu
- _dec_spec = _ilu.spec_from_file_location("_pkt_decisions", "/opt/pocket-mcp/pipeline/ops-pocket-decisions.py")
+
+ _SCRIPTS = Path(
+ os.environ.get("POCKET_SCRIPTS_DIR", str(Path(__file__).resolve().parent))
+ )
+ _dec_spec = _ilu.spec_from_file_location(
+ "_pkt_decisions", _SCRIPTS / "ops-pocket-decisions.py"
+ )
_dec_mod = _ilu.module_from_spec(_dec_spec)
_dec_spec.loader.exec_module(_dec_mod)
except Exception as _e:
_dec_mod = None
+ # Don't crash triage if the decision log can't load, but DO signal it —
+ # silent loss of the audit trail should be visible to the operator.
+ print(
+ f"WARN ops-pocket-triage: decision log unavailable ({_e!r}); "
+ "decisions will NOT be audited this run",
+ file=sys.stderr,
+ )
# ====================================================================
HOME = Path(os.path.expanduser("~"))
@@ -77,10 +91,12 @@ HOME = Path(os.path.expanduser("~"))
# This file is in user state and must NOT be committed to source control.
# If the file is missing, generic placeholders are used (no crash).
# ---------------------------------------------------------------------------
-_USER_CONTEXT_PATH = Path(os.environ.get(
- "POCKET_USER_CONTEXT",
- HOME / ".claude/state/pocket/user-context.json",
-))
+_USER_CONTEXT_PATH = Path(
+ os.environ.get(
+ "POCKET_USER_CONTEXT",
+ HOME / ".claude/state/pocket/user-context.json",
+ )
+)
try:
_ctx = json.loads(_USER_CONTEXT_PATH.read_text())
_OWNER_NAME: str = _ctx.get("owner_name") or "the user"
@@ -205,7 +221,9 @@ def triage_one(task: dict) -> dict:
than Opus so this rarely fires at all."""
decision = _triage_once(task)
if RETRY_ON_RATE_LIMIT and _is_rate_limited(decision):
- log(f"rate-limited on first attempt; backing off {RATE_LIMIT_BACKOFF_SECS}s then retrying once")
+ log(
+ f"rate-limited on first attempt; backing off {RATE_LIMIT_BACKOFF_SECS}s then retrying once"
+ )
time.sleep(RATE_LIMIT_BACKOFF_SECS)
retry = _triage_once(task)
retry["_retried_after_rate_limit"] = True
@@ -224,41 +242,56 @@ def _triage_once(task: dict) -> dict:
f"{SYSTEM_PROMPT}\n\n"
f"---\n\n"
f"Candidate inferred task to triage:\n\n"
- f"Title: {task.get('title','(none)')}\n"
- f"Priority hint: {task.get('priority','(none)')}\n"
- f"Confidence (from Haiku inference): {task.get('confidence','(none)')}\n"
- f"Context from recording: {task.get('context','(none)')}\n"
- f"Source recording id: {task.get('recording_id','(none)')}\n"
- f"Captured at: {task.get('captured_at','(none)')}\n\n"
+ f"Title: {task.get('title', '(none)')}\n"
+ f"Priority hint: {task.get('priority', '(none)')}\n"
+ f"Confidence (from Haiku inference): {task.get('confidence', '(none)')}\n"
+ f"Context from recording: {task.get('context', '(none)')}\n"
+ f"Source recording id: {task.get('recording_id', '(none)')}\n"
+ f"Captured at: {task.get('captured_at', '(none)')}\n\n"
f"Think carefully then output ONLY the JSON object — no prose, no markdown fences."
)
claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))
env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}
- cmd = [claude_bin, "--dangerously-skip-permissions",
- "--model", MODEL, "-p", user_msg]
+ cmd = [
+ claude_bin,
+ "--dangerously-skip-permissions",
+ "--model",
+ MODEL,
+ "-p",
+ user_msg,
+ ]
try:
proc = subprocess.run(
- cmd, env=env, capture_output=True, text=True, timeout=180,
+ cmd,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=180,
)
except subprocess.TimeoutExpired:
return {
- "verdict": "ASK", "confidence": 0.0,
+ "verdict": "ASK",
+ "confidence": 0.0,
"reasoning": "claude -p timed out after 180s; defaulted to ASK.",
- "scoped_task_description": "", "concerns": ["timeout"],
+ "scoped_task_description": "",
+ "concerns": ["timeout"],
"_error": "timeout",
}
except Exception as e:
return {
- "verdict": "ASK", "confidence": 0.0,
+ "verdict": "ASK",
+ "confidence": 0.0,
"reasoning": f"claude -p invocation failed: {type(e).__name__}; defaulted to ASK.",
- "scoped_task_description": "", "concerns": [str(e)[:160]],
+ "scoped_task_description": "",
+ "concerns": [str(e)[:160]],
"_error": "spawn_failed",
}
if proc.returncode != 0:
return {
- "verdict": "ASK", "confidence": 0.0,
+ "verdict": "ASK",
+ "confidence": 0.0,
"reasoning": f"claude -p exited {proc.returncode}; defaulted to ASK.",
"scoped_task_description": "",
"concerns": [proc.stderr.strip()[:160] or proc.stdout.strip()[:160]],
@@ -270,6 +303,7 @@ def _triage_once(task: dict) -> dict:
# Strip markdown fences if any
if text_out.startswith("```"):
import re as _re
+
text_out = _re.sub(r"^```(?:json)?\s*", "", text_out)
text_out = _re.sub(r"\s*```$", "", text_out)
@@ -278,9 +312,11 @@ def _triage_once(task: dict) -> dict:
except json.JSONDecodeError:
log(f"Opus returned bad JSON: {text_out[:200]}")
decision = {
- "verdict": "ASK", "confidence": 0.0,
+ "verdict": "ASK",
+ "confidence": 0.0,
"reasoning": "Opus output unparseable; defaulting to ASK.",
- "scoped_task_description": "", "concerns": [f"bad json: {text_out[:80]}"],
+ "scoped_task_description": "",
+ "concerns": [f"bad json: {text_out[:80]}"],
}
decision["_thinking"] = thinking_text.strip()[:4000]
decision["_model"] = MODEL
@@ -304,8 +340,12 @@ def _id_already_routed(task_id: str) -> str | None:
"""
if not task_id:
return None
- for label, p in (("TASKS", TASKS), ("DRAFTS", DRAFTS),
- ("DROPPED", DROPPED), ("REVIEW", REVIEW)):
+ for label, p in (
+ ("TASKS", TASKS),
+ ("DRAFTS", DRAFTS),
+ ("DROPPED", DROPPED),
+ ("REVIEW", REVIEW),
+ ):
if not p.exists():
continue
try:
@@ -346,7 +386,9 @@ def route(task: dict, decision: dict) -> str:
if verdict == "ACT":
# Promote: use scoped description if provided, keep original context
if decision.get("scoped_task_description"):
- routed["title"] = decision["scoped_task_description"][:140] or routed.get("title")
+ routed["title"] = decision["scoped_task_description"][:140] or routed.get(
+ "title"
+ )
routed["kind"] = "task" # supervisor treats these like manual tasks
routed["promoted_from"] = "inferred"
append_jsonl(TASKS, routed)
@@ -398,27 +440,34 @@ def main() -> int:
decision = triage_one(task)
verdict = route(task, decision)
counts[verdict] = counts.get(verdict, 0) + 1
- log(f"[{i}/{len(tasks)}] verdict={verdict} conf={decision.get('confidence')} — {decision.get('reasoning','')[:120]}")
+ log(
+ f"[{i}/{len(tasks)}] verdict={verdict} conf={decision.get('confidence')} — {decision.get('reasoning', '')[:120]}"
+ )
# Audit log every decision with full thinking
- append_jsonl(AUDIT, {
- "ts": now_iso(),
- "task": task,
- "decision": decision,
- "routed_to": verdict,
- })
- if _dec_mod:
+ append_jsonl(
+ AUDIT,
+ {
+ "ts": now_iso(),
+ "task": task,
+ "decision": decision,
+ "routed_to": verdict,
+ },
+ )
+ if _dec_mod and not DRY_RUN:
try:
- _dec_mod.write_decision(_dec_mod.make(
- event_type=task.get("source", "triage"),
- recording_id=task.get("recording_id", ""),
- title=task.get("title") or task.get("recording_title", ""),
- summary_excerpt=task.get("context", "") or "",
- classification=verdict,
- confidence=float(decision.get("confidence", 0) or 0),
- reasoning=str(decision.get("reasoning", ""))[:1500],
- action_taken=verdict,
- model=MODEL,
- ))
+ _dec_mod.write_decision(
+ _dec_mod.make(
+ event_type=task.get("source", "triage"),
+ recording_id=task.get("recording_id", ""),
+ title=task.get("title") or task.get("recording_title", ""),
+ summary_excerpt=task.get("context", "") or "",
+ classification=verdict,
+ confidence=float(decision.get("confidence", 0) or 0),
+ reasoning=str(decision.get("reasoning", ""))[:1500],
+ action_taken=verdict,
+ model=MODEL,
+ )
+ )
except Exception as _e:
log(f"decision log skip: {_e}")
diff --git a/claude-ops/scripts/webhook-receiver/README.md b/claude-ops/scripts/webhook-receiver/README.md
new file mode 100644
index 00000000..9e8ad305
--- /dev/null
+++ b/claude-ops/scripts/webhook-receiver/README.md
@@ -0,0 +1,34 @@
+# Pocket webhook receiver (version-controlled source)
+
+These two files run the **front door** of the Pocket pipeline on
+`dev-sandbox-fra`. They were previously **deployed only** to `/opt/pocket-mcp/`
+with no copy in git; this directory is now the version-controlled **source of
+truth** and the deployed copies should be (re)deployed from here via the steps
+below. Filenames are preserved because `app.py` references its handler by the
+absolute deployed path. The deployed `/opt/pocket-mcp/` copies may lag this
+source until the next deploy — re-run the deploy steps after changes.
+
+| File | Deployed path | Role |
+|---|---|---|
+| `app.py` | `/opt/pocket-mcp/app.py` | FastAPI receiver. Verifies HMAC signature, dedupes via SQLite (`/var/lib/pocket-webhook/seen.db`), enforces a 5-min replay window, then hands each event to the handler. Runs under `pocket-webhook.service` (root). |
+| `on-memory.sh` | `/opt/pocket-mcp/on-memory.sh` | Handler invoked by `app.py`. Journals every event to `/var/lib/pocket-webhook/journal/events.jsonl`, then feeds it into the real-time triage ingest (`ops-pocket-webhook-ingest.py`) as `ec2-user`. |
+
+## Deploy / restore
+
+```sh
+sudo cp app.py /opt/pocket-mcp/app.py
+sudo cp on-memory.sh /opt/pocket-mcp/on-memory.sh
+sudo chmod +x /opt/pocket-mcp/on-memory.sh
+sudo systemctl restart pocket-webhook.service
+```
+
+`app.py` expects:
+- `SECRET_FILE` = `/etc/pocket-webhook/secret` (HMAC shared secret)
+- handler at `/opt/pocket-mcp/on-memory.sh`
+- writable `/var/log/pocket-webhook/` and `/var/lib/pocket-webhook/`
+
+> Originally captured 2026-05-29 from the live `/opt/pocket-mcp/` deployment.
+> This source has since received review-hardening fixes (fail-closed auth,
+> dedup-claim release on dispatch failure, path-sanitized journal names,
+> seconds/ms timestamp handling, journal retention) and may differ from the
+> currently-running files until redeployed via the steps above.
diff --git a/claude-ops/scripts/webhook-receiver/app.py b/claude-ops/scripts/webhook-receiver/app.py
new file mode 100644
index 00000000..07797c64
--- /dev/null
+++ b/claude-ops/scripts/webhook-receiver/app.py
@@ -0,0 +1,202 @@
+"""Pocket webhook receiver — verifies HMAC, dedupes, hands off to local executor."""
+
+import hashlib
+import hmac
+import json
+import logging
+import os
+import sqlite3
+import subprocess
+import threading
+import time
+from contextlib import contextmanager
+from pathlib import Path
+
+from fastapi import FastAPI, Header, HTTPException, Request
+from fastapi.responses import JSONResponse, PlainTextResponse
+
+LOG_PATH = "/var/log/pocket-webhook/webhook.log"
+DEDUP_DB = "/var/lib/pocket-webhook/seen.db"
+HANDLER = "/opt/pocket-mcp/on-memory.sh"
+SECRET_FILE = "/etc/pocket-webhook/secret"
+MAX_SKEW_SEC = 300 # 5 min replay window
+# Keep dedup claims long enough to cover Pocket retries, but bound disk growth.
+SEEN_RETENTION_SEC = 7 * 24 * 3600 # 7 days
+# Below this magnitude a Unix timestamp is plainly seconds, not milliseconds.
+_TS_MS_THRESHOLD = 10_000_000_000
+
+Path(LOG_PATH).parent.mkdir(parents=True, exist_ok=True)
+Path(DEDUP_DB).parent.mkdir(parents=True, exist_ok=True)
+
+logging.basicConfig(
+ filename=LOG_PATH,
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(message)s",
+)
+log = logging.getLogger("pocket-webhook")
+
+app = FastAPI(title="Pocket Webhook Receiver", version="1.0.0")
+
+
+def _read_secret() -> str | None:
+ try:
+ with open(SECRET_FILE, "r") as f:
+ return f.read().strip() or None
+ except FileNotFoundError:
+ return None
+
+
+@contextmanager
+def _db():
+ conn = sqlite3.connect(DEDUP_DB, timeout=5.0)
+ try:
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY, ts INTEGER NOT NULL)"
+ )
+ yield conn
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def _seen(key: str) -> bool:
+ """Atomically CLAIM a dedup key. Returns True if it was already claimed.
+
+ The INSERT OR IGNORE is the claim — it also guards against concurrent
+ duplicate requests. A claim must be released (see _release) if the
+ downstream handoff fails, otherwise a transient dispatch failure would
+ permanently drop the event (at-most-once instead of at-least-once).
+ """
+ with _db() as conn:
+ now = int(time.time())
+ # Bound table growth: drop claims older than the retention window.
+ conn.execute("DELETE FROM seen WHERE ts < ?", (now - SEEN_RETENTION_SEC,))
+ cur = conn.execute(
+ "INSERT OR IGNORE INTO seen (id, ts) VALUES (?, ?)",
+ (key, now),
+ )
+ return cur.rowcount == 0
+
+
+def _release(key: str) -> None:
+ """Release a previously claimed dedup key so the event can be retried."""
+ with _db() as conn:
+ conn.execute("DELETE FROM seen WHERE id = ?", (key,))
+
+
+def _verify_signature(secret: str, timestamp: str, raw_body: bytes, sig: str) -> bool:
+ msg = f"{timestamp}.".encode("utf-8") + raw_body
+ expected = hmac.new(secret.encode("utf-8"), msg, hashlib.sha256).hexdigest()
+ # Pocket may send raw hex or "sha256=<hex>"; accept both
+ candidates = [expected, f"sha256={expected}"]
+ return any(hmac.compare_digest(c, sig) for c in candidates)
+
+
+def root():
+ return PlainTextResponse("pocket-webhook ok", status_code=200)
+
+
+def health():
+ # Do not disclose secret-configuration posture to unauthenticated callers.
+ return {"ok": True}
+
+
[email protected]("/webhook")
+async def webhook(
+ request: Request,
+ x_heypocket_signature: str | None = Header(default=None),
+ x_heypocket_timestamp: str | None = Header(default=None),
+):
+ raw = await request.body()
+ secret = _read_secret()
+
+ # Auth path: if a secret is configured, signature MUST verify.
+ if secret:
+ if not x_heypocket_signature or not x_heypocket_timestamp:
+ log.warning("missing signature headers")
+ raise HTTPException(status_code=401, detail="missing signature headers")
+
+ # Replay protection. Pocket docs say milliseconds, but it has also sent
+ # seconds in the wild — accept both (signature still uses the raw string,
+ # so this only affects the skew check, never verification).
+ try:
+ ts_raw = int(x_heypocket_timestamp)
+ except ValueError:
+ raise HTTPException(status_code=400, detail="bad timestamp")
+ ts_ms = ts_raw if ts_raw >= _TS_MS_THRESHOLD else ts_raw * 1000
+ now_ms = int(time.time() * 1000)
+ if abs(now_ms - ts_ms) > MAX_SKEW_SEC * 1000:
+ log.warning("timestamp skew %sms", now_ms - ts_ms)
+ raise HTTPException(status_code=401, detail="stale timestamp")
+
+ if not _verify_signature(
+ secret, x_heypocket_timestamp, raw, x_heypocket_signature
+ ):
+ log.warning("signature mismatch")
+ raise HTTPException(status_code=401, detail="invalid signature")
+ else:
+ # Fail closed: this service runs as root and is reachable externally.
+ # An absent/empty secret must NOT degrade into accepting unsigned input.
+ log.error(
+ "POCKET_WEBHOOK_SECRET not configured at %s — refusing request",
+ SECRET_FILE,
+ )
+ raise HTTPException(status_code=503, detail="webhook secret not configured")
+
+ # Parse payload
+ try:
+ payload = json.loads(raw.decode("utf-8")) if raw else {}
+ except json.JSONDecodeError:
+ raise HTTPException(status_code=400, detail="invalid json")
+
+ event = payload.get("event") or payload.get("type") or "unknown"
+ data = payload.get("data") or payload.get("recording") or {}
+ rec_id = (
+ (data.get("id") if isinstance(data, dict) else None)
+ or payload.get("recording_id")
+ or payload.get("id")
+ or "no-id"
+ )
+ dedup_key = f"{rec_id}:{event}"
+
+ if _seen(dedup_key):
+ log.info("dedup hit %s", dedup_key)
+ return JSONResponse({"ok": True, "deduped": True}, status_code=200)
+
+ log.info("event=%s rec=%s bytes=%d", event, rec_id, len(raw))
+
+ # Hand off to the executor. We CLAIMED dedup_key above; if dispatch fails we
+ # must release the claim and return a non-2xx so Pocket retries — otherwise
+ # the recording is lost forever (the claim would dedupe every retry).
+ try:
+ proc = subprocess.Popen(
+ [HANDLER, event],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ proc.stdin.write(json.dumps(payload).encode("utf-8"))
+ proc.stdin.close()
+ threading.Thread(target=proc.wait, daemon=True).start()
+ except Exception as e:
+ try:
+ _release(dedup_key)
+ except Exception as release_err:
+ log.error(
+ "dedup release failed for event=%s rec=%s: %s",
+ event,
+ rec_id,
+ release_err,
+ )
+ log.error(
+ "handler dispatch failed for event=%s rec=%s: %s",
+ event,
+ rec_id,
+ e,
+ )
+ raise HTTPException(status_code=500, detail="handler dispatch failed")
+
+ return JSONResponse({"ok": True, "event": event, "id": rec_id}, status_code=200)
diff --git a/claude-ops/scripts/webhook-receiver/on-memory.sh b/claude-ops/scripts/webhook-receiver/on-memory.sh
new file mode 100755
index 00000000..3b3cd5e8
--- /dev/null
+++ b/claude-ops/scripts/webhook-receiver/on-memory.sh
@@ -0,0 +1,65 @@
+#!/usr/bin/env bash
+# Pocket webhook handler — receives validated events from the receiver.
+# Args: $1 = event name. Payload read from stdin (Phase 0 fix 2026-05-29).
+# Runs as root (pocket-webhook.service). Journals every event, then feeds it to
+# the real-time triage ingest (runs AS ec2-user so pipeline state stays
+# ec2-user-owned and consistent with the cron watcher).
+set -euo pipefail
+
+EVENT="${1:-unknown}"
+EVENT_JSON="$(printf '%s' "$EVENT" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()), end="")')"
+# Event name is attacker-controlled (comes from the webhook payload). Sanitize
+# it before it ever touches a filesystem path — strip anything outside a safe
+# charset and cap length, so it cannot traverse out of the journal dir.
+SAFE_EVENT="$(printf '%s' "$EVENT" | tr -c 'A-Za-z0-9._-' '_' | cut -c1-64)"
+[ -n "$SAFE_EVENT" ] || SAFE_EVENT="unknown"
+PAYLOAD="$(cat || true)"
+[ -n "$PAYLOAD" ] || PAYLOAD="{}"
+LOG_DIR="/var/log/pocket-webhook"
+JOURNAL_DIR="/var/lib/pocket-webhook/journal"
+QUEUE_TMP="/var/lib/pocket-webhook/ingest-tmp"
+TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
+EPOCH="$(date -u +%s%N)"
+
+mkdir -p "$LOG_DIR" "$JOURNAL_DIR" "$QUEUE_TMP"
+
+# Append-only journal entry (one JSON-line per event)
+printf '{"ts":"%s","event":%s,"payload":%s}\n' "$TS" "$EVENT_JSON" "$PAYLOAD" \
+ >> "$JOURNAL_DIR/events.jsonl"
+
+# Per-event copy for easy inspection (sanitized name — never raw $EVENT in a path)
+printf '%s\n' "$PAYLOAD" > "$JOURNAL_DIR/${EPOCH}-${SAFE_EVENT}.json"
+
+# Bound disk: prune per-event journal files older than 7 days, rotate the
+# append-only log at 50MB. Lock-free and best-effort — must never break ingest.
+find "$JOURNAL_DIR" -maxdepth 1 -name '*.json' -type f -mtime +7 -delete 2>/dev/null || true
+if [ "$(stat -c%s "$JOURNAL_DIR/events.jsonl" 2>/dev/null || echo 0)" -gt 52428800 ]; then
+ mv -f "$JOURNAL_DIR/events.jsonl" "$JOURNAL_DIR/events.jsonl.1" 2>/dev/null || true
+fi
+
+# systemd journal trace
+logger -t pocket-webhook "event=$EVENT bytes=${#PAYLOAD}"
+
+# ── Real-time triage ingest ──────────────────────────────────────────────────
+# Write the {ts,event,payload} envelope to a temp FILE and hand the path to
+# ops-pocket-webhook-ingest.py (file-arg mode). File-arg avoids any stdin
+# interaction with `sudo -u` / backgrounded subshells. Runs as ec2-user so
+# state files match the cron watcher's owner. Fail-safe: errors here must NEVER
+# break the webhook receiver — backgrounded + `|| true`; the journal above is
+# the durable record regardless.
+POCKET_STATE_DIR="${POCKET_STATE_DIR:-/var/lib/pocket-pipeline}"
+INGEST="/opt/pocket-mcp/pipeline/ops-pocket-webhook-ingest.py"
+ENVFILE="$QUEUE_TMP/${EPOCH}-${SAFE_EVENT}.json"
+printf '{"ts":"%s","event":%s,"payload":%s}' "$TS" "$EVENT_JSON" "$PAYLOAD" > "$ENVFILE"
+chmod 644 "$ENVFILE" 2>/dev/null || true
+if [ -f "$INGEST" ]; then
+ (
+ sudo -u ec2-user env POCKET_STATE_DIR="$POCKET_STATE_DIR" \
+ POCKET_WEBHOOK_INFER="${POCKET_WEBHOOK_INFER:-0}" \
+ /usr/bin/python3 "$INGEST" "$ENVFILE" >>"$LOG_DIR/ingest.log" 2>&1
+ rm -f "$ENVFILE"
+ ) || true &
+fi
+
+printf '%s handler-fired event=%s ingest=%s\n' "$TS" "$EVENT" \
+ "$([ -f "$INGEST" ] && echo queued || echo missing)" >> "$LOG_DIR/handler.log"