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): POCKET_MAX_INFER_PER_RUN cap to prevent backfill blowout (#274)

Aurora Capitald2e547102781
diff --git a/claude-ops/scripts/ops-cron-pocket-watcher.py b/claude-ops/scripts/ops-cron-pocket-watcher.py
index 4ea41d5f..82684183 100755
--- a/claude-ops/scripts/ops-cron-pocket-watcher.py
+++ b/claude-ops/scripts/ops-cron-pocket-watcher.py
@@ -34,6 +34,12 @@ Implicit-task inference (Haiku):
Pocket didn't flag as an actionItem.
POCKET_INFER_MIN_SECS default 60 (skip recordings shorter than this).
POCKET_INFER_CONFIDENCE default 0.7 (skip tasks below this confidence).
+ POCKET_MAX_INFER_PER_RUN default 10. Hard cap on Haiku inference calls per
+ run to prevent first-run / backfill blowout (N unseen
+ recordings × 1 Haiku call each = unbounded spend).
+ Recordings beyond the cap are NOT marked seen and are
+ picked up on the next run. Set to 0 to disable the cap
+ (NOT recommended in cron — leaves money-leak open).
ANTHROPIC_API_KEY env-or-keychain (service=ANTHROPIC_API_KEY,
account=ops-daemon). OAuth from keychain
(Claude Code-credentials) preferred if available.
@@ -92,6 +98,11 @@ GIGA_CONSOLIDATE = os.environ.get("GIGA_CONSOLIDATE", "0") == "1"
INFER_TASKS = os.environ.get("POCKET_INFER_TASKS", "1") == "1"
INFER_MIN_SECS = int(os.environ.get("POCKET_INFER_MIN_SECS", "60"))
INFER_CONFIDENCE = float(os.environ.get("POCKET_INFER_CONFIDENCE", "0.7"))
+# Hard cap on Haiku inference calls per run — prevents first-run backfill
+# blowout. Recordings beyond the cap are NOT marked seen and roll over to the
+# next run. 0 disables the cap (not recommended in cron). See NEVER LEAK MONEY
+# in user CLAUDE.md.
+MAX_INFER_PER_RUN = int(os.environ.get("POCKET_MAX_INFER_PER_RUN", "10"))
LOG_FILE = STATE_DIR / "run.log"
_USER_CONTEXT_PATH = Path(os.environ.get(
@@ -346,6 +357,22 @@ def _resolve_anthropic_auth() -> tuple[str, dict] | tuple[None, None]:
return (None, None)
+def _transcript_for_infer_length_gate(recording: dict) -> str:
+ """Transcript string used for infer length gating and Haiku prompting.
+
+ Matches infer_tasks_from_recording: use Pocket transcript when non-empty;
+ otherwise join transcriptSegments with speaker prefixes (same as inference).
+ """
+ transcript = recording.get("transcript") or ""
+ if not transcript:
+ segs = recording.get("transcriptSegments") or []
+ transcript = "\n".join(
+ f"{s.get('speaker') or 'Speaker'}: {s.get('text', '').strip()}"
+ for s in segs[:80] if s.get("text")
+ )
+ return transcript
+
+
def infer_tasks_from_recording(recording: dict) -> list[dict]:
"""Call Haiku to extract implicit tasks from a recording's transcript.
@@ -358,13 +385,7 @@ def infer_tasks_from_recording(recording: dict) -> list[dict]:
duration = recording.get("durationSec") or recording.get("duration") or 0
if duration and duration < INFER_MIN_SECS:
return []
- transcript = recording.get("transcript") or ""
- if not transcript:
- segs = recording.get("transcriptSegments") or []
- transcript = "\n".join(
- f"{s.get('speaker') or 'Speaker'}: {s.get('text', '').strip()}"
- for s in segs[:80] if s.get("text")
- )
+ transcript = _transcript_for_infer_length_gate(recording)
if len(transcript) < 200:
return []
@@ -800,6 +821,8 @@ def main() -> int:
new_recordings: list[str] = []
next_before: str | None = None
page = 0
+ infer_calls = 0 # Haiku calls made this run; capped by MAX_INFER_PER_RUN
+ cap_hit = False # set when MAX_INFER_PER_RUN reached — breaks page loop too
while True:
page += 1
args = {"recordingDateAfter": cursor}
@@ -827,6 +850,32 @@ def main() -> int:
log(f"skip noise recording {rid} (dur={duration}s, no transcript)")
seen.add(rid)
continue
+
+ # Money-leak guard: if a Haiku inference would fire for THIS
+ # recording and we've already hit the per-run cap, STOP the loop
+ # entirely — do NOT write_memory and do NOT mark seen, so the
+ # recording rolls over to the next run untouched. We pre-check
+ # the same gating logic infer_tasks_from_recording uses so we
+ # don't artificially skip recordings that wouldn't trigger Haiku
+ # anyway (too-short, INFER_TASKS=0, etc).
+ gate_transcript = _transcript_for_infer_length_gate(rec)
+ would_infer = (
+ INFER_TASKS
+ and (not duration or duration >= INFER_MIN_SECS)
+ and len(gate_transcript) >= 200
+ )
+ if (
+ MAX_INFER_PER_RUN > 0
+ and would_infer
+ and infer_calls >= MAX_INFER_PER_RUN
+ ):
+ log(
+ f"infer cap hit: {infer_calls}/{MAX_INFER_PER_RUN} Haiku "
+ f"calls this run — deferring recording {rid} to next run"
+ )
+ cap_hit = True
+ break
+
write_memory(rec, giga=giga)
new_memories += 1
new_recordings.append(rid)
@@ -834,6 +883,8 @@ def main() -> int:
# Implicit-task inference (Haiku) — only on substantive recordings
inferred = infer_tasks_from_recording(rec)
+ if would_infer:
+ infer_calls += 1
for idx, t in enumerate(inferred):
inferred_id = f"inferred-{rid[:12]}-{idx}"
if inferred_id in seen:
@@ -863,6 +914,8 @@ def main() -> int:
f.write(json.dumps(payload) + "\n")
log(f"queued for triage: {t['title'][:60]} (conf={t['confidence']:.2f})")
seen.add(inferred_id)
+ if cap_hit:
+ break
if meta.get("hasMore") and meta.get("nextRecordingDateBeforeExclusive"):
next_before = meta["nextRecordingDateBeforeExclusive"]
if page >= 10:
@@ -902,8 +955,16 @@ def main() -> int:
if giga and giga.ok:
giga_flush_ok = giga.flush()
- # 4) Advance cursor & persist
- save_cursor(run_started)
+ # 4) Advance cursor & persist.
+ # If the Haiku-inference cap was hit, leave the cursor at the OLD value so
+ # next run re-queries the same window and picks up the deferred recordings
+ # (they're not in `seen`, so they won't be double-processed). Advancing the
+ # cursor here would skip them permanently — that's the money-leak that the
+ # cap is meant to PREVENT (not cause).
+ if cap_hit:
+ log(f"cap hit: holding cursor at {cursor} (not advancing to {run_started})")
+ else:
+ save_cursor(run_started)
save_seen(seen)
if giga and giga.ok and not giga_flush_ok:
@@ -918,7 +979,7 @@ def main() -> int:
write_health("ok", summary, extra={
"new_memories": new_memories,
"new_tasks": new_tasks,
- "cursor": run_started,
+ "cursor": run_started if not cap_hit else cursor,
"giga_sync": giga_status,
})
log(f"done {summary}")
diff --git a/claude-ops/tests/test-pocket-infer-cap.py b/claude-ops/tests/test-pocket-infer-cap.py
new file mode 100644
index 00000000..9fe0be3b
--- /dev/null
+++ b/claude-ops/tests/test-pocket-infer-cap.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""test-pocket-infer-cap.py — POCKET_MAX_INFER_PER_RUN guard test.
+
+Asserts the money-leak guardrail in scripts/ops-cron-pocket-watcher.py works:
+when 50 unseen recordings are fed in with POCKET_MAX_INFER_PER_RUN=10, the
+watcher fires EXACTLY 10 Haiku inference calls and seen.json contains EXACTLY
+10 new entries. The other 40 recordings stay unseen for the next run.
+
+Also covers:
+ - Cap of 0 disables capping (all 50 fire — used as the "without guard"
+ counter-factual).
+ - Cursor is NOT advanced when the cap is hit (otherwise next run would
+ skip the deferred recordings and lose them forever).
+
+stdlib only. Imports the watcher as a module after setting env vars.
+"""
+from __future__ import annotations
+
+import importlib
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+HERE = Path(__file__).resolve().parent
+SCRIPTS = HERE.parent / "scripts"
+
+
+def _load_watcher(state_dir: Path, memory_dir: Path, max_cap: str) -> object:
+ """Reload the watcher module under controlled env."""
+ os.environ["POCKET_STATE_DIR"] = str(state_dir)
+ os.environ["POCKET_MEMORY_DIR"] = str(memory_dir)
+ os.environ["POCKET_TASK_QUEUE"] = str(state_dir / "tasks.jsonl")
+ os.environ["POCKET_DRAFT_QUEUE"] = str(state_dir / "drafts.jsonl")
+ os.environ["POCKET_PENDING_TRIAGE"] = str(state_dir / "pending-triage.jsonl")
+ os.environ["POCKET_MAX_INFER_PER_RUN"] = max_cap
+ os.environ["POCKET_INFER_TASKS"] = "1"
+ os.environ["POCKET_INFER_MIN_SECS"] = "60"
+ os.environ["POCKET_INFER_CONFIDENCE"] = "0.0"
+ os.environ["GIGA_SYNC"] = "0"
+ os.environ["POCKET_API_KEY"] = "pk_test"
+ os.environ["POCKET_LOOKBACK_HOURS"] = "24"
+ # Force re-import so module-level env reads pick up new values.
+ sys.path.insert(0, str(SCRIPTS))
+ mod_name = "ops_cron_pocket_watcher"
+ if mod_name in sys.modules:
+ del sys.modules[mod_name]
+ spec = importlib.util.spec_from_file_location(
+ mod_name, SCRIPTS / "ops-cron-pocket-watcher.py"
+ )
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[mod_name] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _make_recordings(n: int) -> list[dict]:
+ """N fake recordings, each substantive enough to trigger Haiku inference."""
+ transcript = "Speaker: " + ("This is a long enough sentence for the inference gate. " * 30)
+ return [
+ {
+ "id": f"rec-{i:04d}",
+ "recordingDate": "2026-05-20T10:00:00Z",
+ "durationSec": 120,
+ "transcript": transcript,
+ "summary": {"text": "test summary"},
+ }
+ for i in range(n)
+ ]
+
+
+class PocketInferCapTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.state_dir = Path(self.tmp.name) / "state"
+ self.memory_dir = Path(self.tmp.name) / "memory"
+ self.state_dir.mkdir(parents=True)
+ self.memory_dir.mkdir(parents=True)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+ # Clean env so other tests aren't polluted.
+ for k in list(os.environ):
+ if k.startswith("POCKET_") or k in ("GIGA_SYNC",):
+ del os.environ[k]
+
+ def _run_watcher_with_cap(self, n_recordings: int, cap: str) -> tuple[int, int, str]:
+ """Invoke watcher.main() with N mocked recordings + cap. Returns
+ (haiku_call_count, seen_count, final_cursor)."""
+ mod = _load_watcher(self.state_dir, self.memory_dir, cap)
+ recordings = _make_recordings(n_recordings)
+
+ haiku_calls = {"n": 0}
+
+ def fake_infer(rec):
+ haiku_calls["n"] += 1
+ return [] # no inferred tasks; we only care about call count
+
+ def fake_call_tool(self_, tool_name, args, timeout=30):
+ if tool_name == "search_pocket_conversations_timerange":
+ return ({"data": {"results": recordings, "meta": {}}}, None)
+ if tool_name == "search_pocket_actionitems":
+ return ({"data": {"results": []}}, None)
+ return ({}, None)
+
+ with mock.patch.object(mod.MCPClient, "initialize", return_value=True), \
+ mock.patch.object(mod.MCPClient, "call_tool", new=fake_call_tool), \
+ mock.patch.object(mod, "infer_tasks_from_recording", new=fake_infer), \
+ mock.patch.object(mod, "write_memory", new=lambda rec, giga=None: None), \
+ mock.patch.object(mod, "resolve_api_key", return_value="pk_test"):
+ rc = mod.main()
+ self.assertEqual(rc, 0, "watcher main() should exit 0")
+
+ seen_path = self.state_dir / "seen.json"
+ seen = json.loads(seen_path.read_text()) if seen_path.exists() else []
+ cursor_path = self.state_dir / "cursor.txt"
+ cursor = cursor_path.read_text().strip() if cursor_path.exists() else ""
+ return haiku_calls["n"], len(seen), cursor
+
+ def test_cap_respected_under_50_recordings(self):
+ """50 unseen recordings × cap=10 → exactly 10 Haiku calls, 10 seen."""
+ n_calls, n_seen, cursor = self._run_watcher_with_cap(50, "10")
+ self.assertEqual(n_calls, 10, f"Haiku should fire exactly 10 times under cap=10, got {n_calls}")
+ self.assertEqual(n_seen, 10, f"seen.json should have exactly 10 entries, got {n_seen}")
+
+ def test_cap_zero_disables_cap(self):
+ """cap=0 → all 50 fire (counter-factual: without guard, money leaks)."""
+ n_calls, n_seen, _ = self._run_watcher_with_cap(50, "0")
+ self.assertEqual(n_calls, 50, f"cap=0 should disable cap; expected 50 calls, got {n_calls}")
+ self.assertEqual(n_seen, 50)
+
+ def test_cap_hit_holds_cursor(self):
+ """When cap is hit, cursor must NOT advance — else deferred recordings
+ are lost forever (the money-leak the cap is meant to prevent)."""
+ mod = _load_watcher(self.state_dir, self.memory_dir, "10")
+ old_cursor = "2026-05-19T00:00:00Z"
+ (self.state_dir / "cursor.txt").write_text(old_cursor)
+
+ recordings = _make_recordings(50)
+
+ def fake_call_tool(self_, tool_name, args, timeout=30):
+ if tool_name == "search_pocket_conversations_timerange":
+ return ({"data": {"results": recordings, "meta": {}}}, None)
+ if tool_name == "search_pocket_actionitems":
+ return ({"data": {"results": []}}, None)
+ return ({}, None)
+
+ with mock.patch.object(mod.MCPClient, "initialize", return_value=True), \
+ mock.patch.object(mod.MCPClient, "call_tool", new=fake_call_tool), \
+ mock.patch.object(mod, "infer_tasks_from_recording", new=lambda r: []), \
+ mock.patch.object(mod, "write_memory", new=lambda rec, giga=None: None), \
+ mock.patch.object(mod, "resolve_api_key", return_value="pk_test"):
+ rc = mod.main()
+ self.assertEqual(rc, 0)
+ final_cursor = (self.state_dir / "cursor.txt").read_text().strip()
+ self.assertEqual(
+ final_cursor, old_cursor,
+ f"cursor must stay at {old_cursor} when cap hit, got {final_cursor}",
+ )
+
+ def test_cap_not_hit_advances_cursor(self):
+ """When cap is NOT hit (fewer recordings than cap), cursor advances normally."""
+ mod = _load_watcher(self.state_dir, self.memory_dir, "10")
+ old_cursor = "2026-05-19T00:00:00Z"
+ (self.state_dir / "cursor.txt").write_text(old_cursor)
+ recordings = _make_recordings(5)
+
+ def fake_call_tool(self_, tool_name, args, timeout=30):
+ if tool_name == "search_pocket_conversations_timerange":
+ return ({"data": {"results": recordings, "meta": {}}}, None)
+ if tool_name == "search_pocket_actionitems":
+ return ({"data": {"results": []}}, None)
+ return ({}, None)
+
+ with mock.patch.object(mod.MCPClient, "initialize", return_value=True), \
+ mock.patch.object(mod.MCPClient, "call_tool", new=fake_call_tool), \
+ mock.patch.object(mod, "infer_tasks_from_recording", new=lambda r: []), \
+ mock.patch.object(mod, "write_memory", new=lambda rec, giga=None: None), \
+ mock.patch.object(mod, "resolve_api_key", return_value="pk_test"):
+ mod.main()
+ final_cursor = (self.state_dir / "cursor.txt").read_text().strip()
+ self.assertNotEqual(final_cursor, old_cursor, "cursor should advance when cap not hit")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)