import json import threading from rich.console import Console from afk_developer.events import ( ConsoleSink, JsonlSink, RunEvent, TeeSink, audit_sink, emit, load_attempt_summaries, ) from afk_developer.planner.task_model import TaskNode, TaskPlan def test_jsonl_sink_writes_one_valid_record_per_event(tmp_path): path = tmp_path / "audit" / "attempts.jsonl" sink = JsonlSink(path) threads = [ threading.Thread(target=sink.emit, args=(RunEvent("attempt_summary", f"event {index}", {"i": index}),)) for index in range(10) ] for thread in threads: thread.start() for thread in threads: thread.join() records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] assert len(records) == 10 assert {record["data"]["i"] for record in records} == set(range(10)) assert all({"timestamp", "kind", "text", "data"} <= record.keys() for record in records) def test_tee_sink_delivers_to_console_and_jsonl(tmp_path): console = Console(record=True) path = tmp_path / "events.jsonl" TeeSink(ConsoleSink(console), JsonlSink(path)).emit(RunEvent("info", "hello", {"safe": True})) assert "hello" in console.export_text() assert json.loads(path.read_text(encoding="utf-8"))["data"] == {"safe": True} def test_jsonl_sink_write_failure_is_nonfatal(tmp_path): sink = JsonlSink(tmp_path / "parent-file" / "events.jsonl") (tmp_path / "parent-file").write_text("not a directory", encoding="utf-8") sink.emit(RunEvent("info", "continue", {})) def test_attempt_summary_loader_ignores_corrupt_lines(tmp_path): path = tmp_path / "attempts.jsonl" path.write_text( '\n'.join( [ json.dumps({"kind": "attempt_summary", "data": {"task_id": "one", "total_turns": 3}}), "{broken trailing record", json.dumps({"kind": "info", "data": {"task_id": "one"}}), ] ), encoding="utf-8", ) assert load_attempt_summaries(path, "one") == [{"task_id": "one", "total_turns": 3}] def test_plan_round_trips_a_relative_audit_log_path(): plan = TaskPlan( project_name="example", goal="goal", intent="implement", tasks=[TaskNode(id="task", title="Task", description="Description")], audit_log_path="audits/example.jsonl", ) assert TaskPlan.model_validate_json(plan.model_dump_json()).audit_log_path == "audits/example.jsonl" def test_audit_scope_writes_bounded_event_data_without_tool_arguments(tmp_path): path = tmp_path / "attempts.jsonl" with audit_sink(path): emit( "attempt_summary", "Attempt complete", task_id="one", attempt_id="attempt-1", outcome="passed", total_turns=4, total_tokens=25, api_calls=2, files_changed=["result.txt"], tool_counts={"read_file": 2, "write_file": 1}, ) record = json.loads(path.read_text(encoding="utf-8")) assert record["data"]["tool_counts"] == {"read_file": 2, "write_file": 1} assert "arguments" not in record["data"]