Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
test(cli_agent): JsonlWatcher + claude_session_* CloudEvent factories (Step 12)
trohitga523d3dddc1e
diff --git a/server/tests/services/cli_agent/test_claude_session_events.py b/server/tests/services/cli_agent/test_claude_session_events.pynew file mode 100644index 00000000..c6364332--- /dev/null+++ b/server/tests/services/cli_agent/test_claude_session_events.py@@ -0,0 +1,183 @@+"""Unit tests for the four ``claude.session.*`` CloudEvent factories+on :class:`services.events.envelope.WorkflowEvent`.++Locks the envelope contract — source URI, type prefix, subject,+workflow_id extension attribute, and data shape — so frontend+consumers + future plugin authors don't get surprise drift.+"""++from __future__ import annotations++from services.events.envelope import WorkflowEvent+++class TestClaudeSessionSpawned:+ def test_envelope_shape(self):+ event = WorkflowEvent.claude_session_spawned(+ memory_node_id="mem-1",+ session_uuid="abc-123",+ pid=12345,+ workflow_id="wf-99",+ )+ assert event.source == "machinaos://services/cli_agent"+ assert event.type == "com.machinaos.claude.session.spawned"+ assert event.subject == "mem-1"+ assert event.workflow_id == "wf-99"+ assert event.data == {+ "memory_node_id": "mem-1",+ "session_uuid": "abc-123",+ "pid": 12345,+ }++ def test_workflow_id_optional(self):+ event = WorkflowEvent.claude_session_spawned(+ memory_node_id="mem-1",+ session_uuid="abc",+ pid=1,+ )+ assert event.workflow_id is None++ def test_matches_type_glob(self):+ event = WorkflowEvent.claude_session_spawned(+ memory_node_id="m", session_uuid="u", pid=1,+ )+ assert event.matches_type("claude.session.*")+ assert event.matches_type("claude.session.spawned")+ assert not event.matches_type("claude.session.cleared")+++class TestClaudeSessionCleared:+ def test_envelope_shape(self):+ event = WorkflowEvent.claude_session_cleared(+ memory_node_id="mem-1",+ old_session_uuid="uuid-A",+ new_session_uuid="uuid-B",+ workflow_id="wf-99",+ )+ assert event.type == "com.machinaos.claude.session.cleared"+ assert event.subject == "mem-1"+ assert event.data["old_session_uuid"] == "uuid-A"+ assert event.data["new_session_uuid"] == "uuid-B"+++class TestClaudeSessionTerminated:+ def test_envelope_shape(self):+ event = WorkflowEvent.claude_session_terminated(+ memory_node_id="mem-1",+ reason="idle",+ session_uuid="uuid-A",+ )+ assert event.type == "com.machinaos.claude.session.terminated"+ assert event.subject == "mem-1"+ assert event.data["reason"] == "idle"+ assert event.data["session_uuid"] == "uuid-A"++ def test_session_uuid_optional(self):+ event = WorkflowEvent.claude_session_terminated(+ memory_node_id="mem-1",+ reason="shutdown",+ )+ # When session_uuid is None, the key is omitted from data.+ assert "session_uuid" not in event.data+ assert event.data["reason"] == "shutdown"+++class TestClaudeSessionUsage:+ def test_envelope_shape(self):+ event = WorkflowEvent.claude_session_usage(+ memory_node_id="mem-1",+ session_uuid="uuid-A",+ total_cost_usd=0.0123,+ input_tokens=100,+ output_tokens=50,+ cache_read_input_tokens=200,+ cache_creation_input_tokens=10,+ duration_ms=4567,+ num_turns=3,+ workflow_id="wf-99",+ )+ assert event.type == "com.machinaos.claude.session.usage"+ assert event.subject == "mem-1"+ assert event.workflow_id == "wf-99"+ assert event.data["session_uuid"] == "uuid-A"+ assert event.data["total_cost_usd"] == 0.0123+ assert event.data["usage"] == {+ "input_tokens": 100,+ "output_tokens": 50,+ "cache_read_input_tokens": 200,+ "cache_creation_input_tokens": 10,+ }+ assert event.data["duration_ms"] == 4567+ assert event.data["num_turns"] == 3++ def test_optional_fields_omitted_when_none(self):+ event = WorkflowEvent.claude_session_usage(+ memory_node_id="mem-1",+ session_uuid="uuid-A",+ )+ assert event.data["total_cost_usd"] is None+ # duration_ms / num_turns omitted (not present in data) when None.+ assert "duration_ms" not in event.data+ assert "num_turns" not in event.data+ # Usage block always emitted (zeros), so the FE doesn't need a+ # null check.+ assert event.data["usage"]["input_tokens"] == 0++ def test_zero_costs_and_tokens_acceptable(self):+ event = WorkflowEvent.claude_session_usage(+ memory_node_id="mem-1",+ session_uuid="uuid-A",+ total_cost_usd=0.0,+ )+ assert event.data["total_cost_usd"] == 0.0+++class TestCloudEventInvariants:+ """Cross-cutting checks the four events all satisfy."""++ EVENTS = [+ ("spawned", lambda: WorkflowEvent.claude_session_spawned(+ memory_node_id="m", session_uuid="u", pid=1,+ )),+ ("cleared", lambda: WorkflowEvent.claude_session_cleared(+ memory_node_id="m", old_session_uuid="a", new_session_uuid="b",+ )),+ ("terminated", lambda: WorkflowEvent.claude_session_terminated(+ memory_node_id="m", reason="idle",+ )),+ ("usage", lambda: WorkflowEvent.claude_session_usage(+ memory_node_id="m", session_uuid="u",+ )),+ ]++ def test_all_share_source_uri(self):+ for name, builder in self.EVENTS:+ event = builder()+ assert event.source == "machinaos://services/cli_agent", name++ def test_all_share_subject_convention(self):+ # subject = memory_node_id, drives FE per-memory-node routing.+ for name, builder in self.EVENTS:+ event = builder()+ assert event.subject == "m", name++ def test_all_dataschema_auto_populated(self):+ for name, builder in self.EVENTS:+ event = builder()+ assert event.dataschema is not None+ assert event.dataschema.startswith(+ "machinaos://schemas/events/claude.session."+ ), name+ assert event.dataschema.endswith(".json"), name++ def test_all_carry_specversion_1(self):+ for name, builder in self.EVENTS:+ event = builder()+ assert event.specversion == "1.0", name++ def test_all_have_unique_id(self):+ ids = set()+ for _, builder in self.EVENTS:+ for _ in range(10):+ ids.add(builder().id)+ assert len(ids) == 40 # all distinctdiff --git a/server/tests/services/cli_agent/test_jsonl_watcher.py b/server/tests/services/cli_agent/test_jsonl_watcher.pynew file mode 100644index 00000000..a003c5d6--- /dev/null+++ b/server/tests/services/cli_agent/test_jsonl_watcher.py@@ -0,0 +1,190 @@+"""Unit tests for :mod:`services.cli_agent.jsonl_watcher`.++Covers :class:`JsonlWatcher` (tail-f one file) and+:class:`JsonlDirWatcher` (detect new files). Both run with real+tempfiles; no PTY / claude / network dependencies.+"""++from __future__ import annotations++import asyncio+import json+import tempfile+from pathlib import Path+from typing import Any, Dict, List++import pytest++from services.cli_agent.jsonl_watcher import (+ JsonlDirWatcher,+ JsonlWatcher,+ session_uuid_from_jsonl_path,+)+++class TestJsonlWatcher:+ @pytest.fixture+ def tmp_jsonl(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "session.jsonl"+ yield path++ async def test_tails_newly_written_lines(self, tmp_jsonl):+ events: List[Dict[str, Any]] = []++ async def on_event(event):+ events.append(event)++ watcher = JsonlWatcher(tmp_jsonl, on_event=on_event, poll_interval=0.05)+ await watcher.start()+ try:+ # Wait briefly so the loop has a chance to open the file.+ await asyncio.sleep(0.1)+ with tmp_jsonl.open("ab") as fh:+ fh.write(json.dumps({"type": "system", "subtype": "init"}).encode() + b"\n")+ fh.write(json.dumps({"type": "assistant", "message": {"content": "hi"}}).encode() + b"\n")+ # Give the poll loop a couple ticks.+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ assert len(events) == 2+ assert events[0]["type"] == "system"+ assert events[1]["type"] == "assistant"++ async def test_ignores_garbage_lines(self, tmp_jsonl):+ events: List[Dict[str, Any]] = []++ async def on_event(event):+ events.append(event)++ watcher = JsonlWatcher(tmp_jsonl, on_event=on_event, poll_interval=0.05)+ await watcher.start()+ try:+ await asyncio.sleep(0.1)+ with tmp_jsonl.open("ab") as fh:+ fh.write(b"not valid json\n")+ fh.write(json.dumps({"type": "result"}).encode() + b"\n")+ fh.write(b"\n") # blank+ fh.write(b" \n") # whitespace+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ # Only the valid line dispatched.+ assert len(events) == 1+ assert events[0]["type"] == "result"++ async def test_stop_is_idempotent(self, tmp_jsonl):+ async def on_event(event): # pragma: no cover — never fires+ pass++ watcher = JsonlWatcher(tmp_jsonl, on_event=on_event, poll_interval=0.05)+ await watcher.start()+ await watcher.stop()+ await watcher.stop() # second stop must not raise++ async def test_handler_exception_doesnt_break_loop(self, tmp_jsonl):+ events: List[Dict[str, Any]] = []++ async def on_event(event):+ if event.get("type") == "boom":+ raise RuntimeError("handler exploded")+ events.append(event)++ watcher = JsonlWatcher(tmp_jsonl, on_event=on_event, poll_interval=0.05)+ await watcher.start()+ try:+ await asyncio.sleep(0.1)+ with tmp_jsonl.open("ab") as fh:+ fh.write(json.dumps({"type": "boom"}).encode() + b"\n")+ fh.write(json.dumps({"type": "good"}).encode() + b"\n")+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ assert any(e["type"] == "good" for e in events)+++class TestJsonlDirWatcher:+ @pytest.fixture+ def tmp_dir(self):+ with tempfile.TemporaryDirectory() as tmp:+ yield Path(tmp)++ async def test_detects_newly_created_jsonl(self, tmp_dir):+ new_files: List[Path] = []++ async def on_new(path):+ new_files.append(path)++ watcher = JsonlDirWatcher(tmp_dir, on_new_file=on_new, poll_interval=0.05)+ await watcher.start()+ try:+ await asyncio.sleep(0.1)+ (tmp_dir / "abc-123.jsonl").write_text("")+ (tmp_dir / "def-456.jsonl").write_text("")+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ names = {p.name for p in new_files}+ assert "abc-123.jsonl" in names+ assert "def-456.jsonl" in names++ async def test_baseline_files_not_fired(self, tmp_dir):+ # File present BEFORE start = baseline; should NOT fire callback.+ (tmp_dir / "existing.jsonl").write_text("")++ new_files: List[Path] = []++ async def on_new(path):+ new_files.append(path)++ watcher = JsonlDirWatcher(tmp_dir, on_new_file=on_new, poll_interval=0.05)+ await watcher.start()+ try:+ await asyncio.sleep(0.15)+ # Add a new file post-start.+ (tmp_dir / "fresh.jsonl").write_text("")+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ names = [p.name for p in new_files]+ assert "existing.jsonl" not in names+ assert "fresh.jsonl" in names++ async def test_non_jsonl_files_ignored(self, tmp_dir):+ new_files: List[Path] = []++ async def on_new(path):+ new_files.append(path)++ watcher = JsonlDirWatcher(tmp_dir, on_new_file=on_new, poll_interval=0.05)+ await watcher.start()+ try:+ await asyncio.sleep(0.1)+ (tmp_dir / "session.jsonl").write_text("")+ (tmp_dir / "session.txt").write_text("")+ (tmp_dir / "session.json").write_text("")+ await asyncio.sleep(0.2)+ finally:+ await watcher.stop()++ names = {p.name for p in new_files}+ assert names == {"session.jsonl"}+++class TestSessionUuidFromJsonlPath:+ def test_extracts_uuid_stem(self):+ path = Path("/some/dir/abc-123-def-456.jsonl")+ assert session_uuid_from_jsonl_path(path) == "abc-123-def-456"++ def test_returns_none_for_non_jsonl(self):+ assert session_uuid_from_jsonl_path(Path("foo.txt")) is None+ assert session_uuid_from_jsonl_path(Path("foo.json")) is None++ def test_returns_none_for_empty_stem(self):+ # A path like `.jsonl` (no stem) returns None.+ assert session_uuid_from_jsonl_path(Path(".jsonl")) is None