diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index c99f5ca67..63968bf33 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "1b121efa8d9400fa2f1497145dae25076a22aa0ff224dddcc73f90c037591bf5", + "registryDigest": "9a8492b95e59105333e2eb0d380c7f958c9dc72e22e8f46813abfee599c68a4d", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/skills/videodb/SKILL.md b/skills/videodb/SKILL.md index e1290296a..6137a6934 100644 --- a/skills/videodb/SKILL.md +++ b/skills/videodb/SKILL.md @@ -305,11 +305,14 @@ Use `ws_listener.py` to capture WebSocket events during recording sessions. Desk #### Quick Start 1. **Choose state dir**: `STATE_DIR="${VIDEODB_EVENTS_DIR:-$HOME/.local/state/videodb}"` -2. **Start listener**: `VIDEODB_EVENTS_DIR="$STATE_DIR" python scripts/ws_listener.py --clear "$STATE_DIR" &` +2. **Start listener** from the project directory, so it reads the project's `.env`: `VIDEODB_EVENTS_DIR="$STATE_DIR" python "${CLAUDE_SKILL_DIR}/scripts/ws_listener.py" --clear "$STATE_DIR" &` 3. **Get WebSocket ID**: `cat "$STATE_DIR/videodb_ws_id"` 4. **Run capture code** (see reference/capture.md for the full workflow) 5. **Events written to**: `$STATE_DIR/videodb_events.jsonl` +`scripts/ws_listener.py` in the reference files is relative to this skill's directory (`${CLAUDE_SKILL_DIR}`), not to the project. +Claude Code fills in `${CLAUDE_SKILL_DIR}`. Other hosts leave it empty, so replace it with the directory this skill is installed in (for Codex, `$HOME/.codex/skills/videodb`; `~` does not expand inside the quotes). + Use `--clear` whenever you start a fresh capture run so stale transcript and visual events do not leak into the new session. #### Query Events diff --git a/skills/videodb/scripts/ws_listener.py b/skills/videodb/scripts/ws_listener.py index 0ec201056..3d96dc3cd 100644 --- a/skills/videodb/scripts/ws_listener.py +++ b/skills/videodb/scripts/ws_listener.py @@ -35,8 +35,9 @@ import contextlib from datetime import datetime, timezone from pathlib import Path -from dotenv import load_dotenv -load_dotenv() +from dotenv import find_dotenv, load_dotenv +# Search from the working directory (the user's project), not this script's dir. +load_dotenv(find_dotenv(usecwd=True)) import videodb from videodb.exceptions import AuthenticationError @@ -191,15 +192,21 @@ async def listen_with_retry(): print(f"WS_ID={ws_id}", flush=True) log(f"Connected (ws_id={ws_id})") - retry_count = 0 - backoff = INITIAL_BACKOFF - receiver = ws.receive().__aiter__() while True: try: msg = await anext(receiver) except StopAsyncIteration: + # Counts as a failed attempt, so a server that accepts and then + # closes at once is retried with backoff, not in a tight loop. + retry_count += 1 log("Connection closed by server") + if retry_count >= MAX_RETRIES: + log(f"Max retries ({MAX_RETRIES}) exceeded, exiting") + return + log(f"Reconnecting in {backoff}s (attempt {retry_count}/{MAX_RETRIES})...") + await asyncio.sleep(backoff) + backoff = min(backoff * 2, MAX_BACKOFF) break except asyncio.CancelledError: log("Shutdown requested") @@ -222,6 +229,9 @@ async def listen_with_retry(): backoff = min(backoff * 2, MAX_BACKOFF) break + # Only a connection that delivers events resets the retry budget. + retry_count = 0 + backoff = INITIAL_BACKOFF append_event(msg) channel = msg.get("channel", msg.get("event", "unknown")) text = msg.get("data", {}).get("text", "") diff --git a/tests/test_videodb_ws_listener.py b/tests/test_videodb_ws_listener.py new file mode 100644 index 000000000..925286b1d --- /dev/null +++ b/tests/test_videodb_ws_listener.py @@ -0,0 +1,89 @@ +"""Regression tests for skills/videodb/scripts/ws_listener.py. + +`dotenv` and `videodb` are stubbed, so neither package nor a network is needed. +""" +import asyncio +import importlib.util +import sys +import types +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parent.parent / "skills" / "videodb" / "scripts" / "ws_listener.py" + + +class FakeWebSocket: + def __init__(self, events): + self.connection_id = "ws-test" + self._events = events + + async def receive(self): + for event in self._events: + yield event + + +def load_listener(monkeypatch, tmp_path, connections): + """Import ws_listener with stubs; each connect() serves the next event list.""" + dotenv_calls = [] + dotenv = types.ModuleType("dotenv") + dotenv.find_dotenv = lambda **kwargs: dotenv_calls.append(("find", kwargs)) or "/project/.env" + dotenv.load_dotenv = lambda *args, **kwargs: dotenv_calls.append(("load", args)) or True + + remaining = list(connections) + + class Wrapper: + async def connect(self): + if not remaining: + raise AssertionError("listener kept reconnecting after its retry budget") + return FakeWebSocket(remaining.pop(0)) + + class Conn: + def connect_websocket(self): + return Wrapper() + + videodb = types.ModuleType("videodb") + videodb.connect = Conn + exceptions = types.ModuleType("videodb.exceptions") + exceptions.AuthenticationError = type("AuthenticationError", (Exception,), {}) + videodb.exceptions = exceptions + + monkeypatch.setitem(sys.modules, "dotenv", dotenv) + monkeypatch.setitem(sys.modules, "videodb", videodb) + monkeypatch.setitem(sys.modules, "videodb.exceptions", exceptions) + monkeypatch.setattr(sys, "argv", [str(SCRIPT), str(tmp_path)]) + + spec = importlib.util.spec_from_file_location("ws_listener_under_test", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + sleeps = [] + + async def fake_sleep(seconds): + sleeps.append(seconds) + + monkeypatch.setattr(module.asyncio, "sleep", fake_sleep) + return module, dotenv_calls, sleeps, remaining + + +def test_loads_dotenv_found_from_the_working_directory(monkeypatch, tmp_path): + _, dotenv_calls, _, _ = load_listener(monkeypatch, tmp_path, []) + assert ("find", {"usecwd": True}) in dotenv_calls + assert ("load", ("/project/.env",)) in dotenv_calls + + +def test_eventless_closes_back_off_and_stop(monkeypatch, tmp_path): + module, _, sleeps, remaining = load_listener(monkeypatch, tmp_path, [[]] * 20) + asyncio.run(module.listen_with_retry()) + assert len(remaining) == 20 - module.MAX_RETRIES + assert sleeps == [1, 2, 4, 8, 16, 32, 60, 60, 60] + + +def test_an_event_resets_the_retry_budget(monkeypatch, tmp_path): + event = {"channel": "transcript", "data": {"text": "hi"}} + connections = [[], [event]] + [[]] * 20 + module, _, sleeps, _ = load_listener(monkeypatch, tmp_path, connections) + asyncio.run(module.listen_with_retry()) + # First close backs off 1s; the event resets backoff, so the next close waits 1s again. + assert sleeps[:3] == [1, 1, 2] + assert len(sleeps) == 1 + module.MAX_RETRIES - 1 + assert (tmp_path / "videodb_events.jsonl").read_text().count("transcript") == 1 +