The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into feat/hermes-relay-model-metrics
Alex Fournierc0369f08914e
diff --cc tests/hermes_cli/test_relay_shared_metrics.pyindex f193ff2f44f,4bbca69382e..d4d83c1d4b1--- a/tests/hermes_cli/test_relay_shared_metrics.py+++ b/tests/hermes_cli/test_relay_shared_metrics.py@@@ -302,437 -181,43 +302,132 @@@ def test_due_export_runs_once_per_utc_ddef test_package_schema_matches_the_model_call_contract():+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))properties = _package_dimension_schema()["properties"]- assert properties["call_role"] == {"const": PRIMARY_MODEL_CALL_ROLE}- assert set(properties["locality"]["enum"]) == MODEL_LOCALITIES- assert set(properties["model_family"]["enum"]) == MODEL_FAMILIES- assert set(properties["outcome"]["enum"]) == MODEL_OUTCOMES- assert set(properties["provider_family"]["enum"]) == PROVIDER_FAMILIES+ assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v2"+ assert set(properties) == {"model", "provider"}+ assert properties["model"]["maxLength"] == MODEL_IDENTIFIER_MAX_LENGTH+ assert properties["provider"]["maxLength"] == PROVIDER_IDENTIFIER_MAX_LENGTH+ assert "enum" not in properties["model"]+ assert "enum" not in properties["provider"]+++def test_v1_package_schema_retains_the_legacy_model_contract():+ schema = json.loads(LEGACY_SCHEMA_PATH.read_text(encoding="utf-8"))+ model_counter = schema["$defs"]["model_call_counter"]++ assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v1"+ assert model_counter["properties"]["name"]["const"] == LEGACY_MODEL_CALL_METRIC+ assert set(model_counter["properties"]["dimensions"]["properties"]) == {+ "call_role",+ "locality",+ "model_family",+ "outcome",+ "provider_family",+ }++- def test_package_schema_matches_the_task_contract():- schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))- start = _task_dimension_schema("task_started_counter")["properties"]- terminal = _task_dimension_schema("task_finished_counter")["properties"]-- assert set(schema["$defs"]["execution_surface"]["enum"]) == EXECUTION_SURFACES- assert set(schema["$defs"]["task_entrypoint"]["enum"]) == TASK_ENTRYPOINTS- assert set(schema["$defs"]["duration_bucket"]["enum"]) == DURATION_BUCKETS- assert set(schema["$defs"]["count_bucket"]["enum"]) == COUNT_BUCKETS- assert start["entrypoint"] == {"$ref": "#/$defs/task_entrypoint"}- assert set(terminal["end_reason"]["enum"]) == TASK_END_REASONS- assert set(terminal["outcome"]["enum"]) == TASK_OUTCOMES- assert set(terminal["termination"]["enum"]) == TASK_TERMINATIONS--+def test_model_call_fields_report_terminal_model_and_provider_without_a_catalog():+ assert model_call_fields({+ "model": "fallback/model",+ "response_model": "NVIDIA/Nemotron-3-Ultra",+ "provider": "OpenRouter",+ "base_url": "https://private-endpoint.example/v1",+ }) == {+ "model": "nvidia/nemotron-3-ultra",+ "provider": "openrouter",+ }+ assert model_call_fields({+ "model": "ZAI/GLM-5.2",+ "provider": "Brev",+ }) == {+ "model": "zai/glm-5.2",+ "provider": "brev",+ }+++ "response_model",+ [+ "contains a space",+ "x" * (MODEL_IDENTIFIER_MAX_LENGTH + 1),+ ],+)+def test_model_call_fields_fall_back_when_response_model_is_invalid(response_model):+ assert model_call_fields({+ "model": "nvidia/nemotron-3-ultra",+ "response_model": response_model,+ "provider": "openrouter",+ }) == {+ "model": "nvidia/nemotron-3-ultra",+ "provider": "openrouter",+ }+++ ("field", "value"),+ [+ ("model", ""),+ ("model", "contains a space"),+ ("model", "contains\ncontrol"),+ ("model", "_" + "private"),+ ("model", "x" * (MODEL_IDENTIFIER_MAX_LENGTH + 1)),+ ("model", object()),+ ("provider", ""),+ ("provider", "private provider"),+ ("provider", "x" * (PROVIDER_IDENTIFIER_MAX_LENGTH + 1)),+ ("provider", object()),+ ],+)+def test_model_call_fields_collapse_malformed_identifiers(field, value):+ event = {"model": "nvidia/nemotron-3-ultra", "provider": "openrouter"}+ event[field] = value++ assert model_call_fields(event)[field] == "unknown"++- @pytest.mark.parametrize(- ("platform", "expected"),- [- ("", "unknown"),- ("cli", "cli"),- ("api_server", "api"),- ("cron", "scheduled_task"),- ("whatsapp_cloud", "gateway"),- ("private-surface", "other"),- ],- )- def test_execution_surface_uses_the_hermes_platform_registry(platform, expected):- assert execution_surface({"platform": platform}) == expected--- @pytest.mark.parametrize(- ("platform", "expected"),- [- ("cli", "interactive"),- ("tui", "interactive"),- ("whatsapp_cloud", "gateway_message"),- ("cron", "scheduled_task"),- ("api_server", "api"),- ("private-surface", "other"),- ],- )- def test_task_start_fields_use_bounded_surface_and_entrypoint(platform, expected):- fields = task_start_fields({"platform": platform})-- assert fields["entrypoint"] == expected- assert fields["execution_surface"] in EXECUTION_SURFACES--- def test_task_start_fields_identify_delegated_work_without_exporting_parent_id():- fields = task_start_fields({- "platform": "cli",- "parent_session_id": "private-parent-session",- })-- assert fields == {- "entrypoint": "delegated",- "execution_surface": "cli",- }- assert "private-parent-session" not in json.dumps(fields)++def test_store_does_not_record_the_retired_model_metric(tmp_path):++ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")+++ with pytest.raises(ValueError, match="Unsupported shared metric"):++ store.record_counter(++ LEGACY_MODEL_CALL_METRIC,++ _legacy_dimensions(),++ "test-version",++ )+- @pytest.mark.parametrize(- ("duration_ms", "expected"),- [- (0, "lt_1s"),- (999, "lt_1s"),- (1_000, "1s_to_5s"),- (5_000, "5s_to_30s"),- (30_000, "30s_to_2m"),- (120_000, "2m_to_10m"),- (600_000, "gte_10m"),- ],- )- def test_duration_bucket_boundaries(duration_ms, expected):- assert duration_bucket(duration_ms) == expected++ assert store.counter_snapshot() == []- @pytest.mark.parametrize(- ("count", "expected"),- [- (0, "0"),- (1, "1"),- (2, "2"),- (3, "3_to_5"),- (6, "6_to_10"),- (11, "gte_11"),- ],- )- def test_count_bucket_boundaries(count, expected):- assert count_bucket(count) == expected- @pytest.mark.parametrize(- ("event", "expected"),- [- (- {"completed": True, "turn_exit_reason": "text_response(stop)"},- ("success", "completed", "none"),- ),- (- {"failed": True, "turn_exit_reason": "all_retries_exhausted_no_response"},- ("failed", "failed", "none"),- ),- (- {"interrupted": True, "turn_exit_reason": "interrupted_by_user"},- ("cancelled", "user_cancelled", "user_cancelled"),- ),- (- {"turn_exit_reason": "budget_exhausted"},- ("failed", "iteration_limit", "system_aborted"),- ),- (- {"turn_exit_reason": "guardrail_halt"},- ("failed", "guardrail_blocked", "system_aborted"),- ),- (- {"failed": True, "turn_exit_reason": "provider_timeout"},- ("timed_out", "timed_out", "timed_out"),- ),- (- {"failed": True, "turn_exit_reason": "approval_denied"},- ("failed", "approval_denied", "none"),- ),- ],- )- def test_task_terminal_state_is_bounded(event, expected):- assert task_terminal_state(event) == expected--- def test_subscriber_contract_rejects_unknown_fields_and_dimension_values():- event = SimpleNamespace(- kind="scope",- category="llm",- category_profile={"model_name": MODEL_CALL_PROFILE_MODEL},- name="hermes.model_call",- scope_category="end",- metadata={SCHEMA_KEY: SCHEMA_VERSION},- data=_dimensions(),- )- assert model_call_dimensions(event) == _dimensions()- event.category_profile["model_name"] = "gpt"- assert model_call_dimensions(event) is None- event.category_profile["model_name"] = "private-model-name"- assert model_call_dimensions(event) is None- event.category_profile["model_name"] = MODEL_CALL_PROFILE_MODEL- event.data["model"] = "contains a space"- assert model_call_dimensions(event) is None- event.data["model"] = _dimensions()["model"]- event.data["prompt"] = "must-not-pass"- assert model_call_dimensions(event) is None- event.data.pop("prompt")- event.metadata["prompt"] = "must-not-pass"- assert model_call_dimensions(event) is None- event.metadata.pop("prompt")- event.category_profile["private"] = "must-not-pass"- assert model_call_dimensions(event) is None- event.category_profile.pop("private")- event.category = "function"- assert model_call_dimensions(event) is None--- def test_task_subscriber_contract_accepts_only_bounded_scope_events():- start = SimpleNamespace(- kind="scope",- category="function",- category_profile=None,- name="hermes.task_run",- scope_category="start",- metadata={SCHEMA_KEY: SCHEMA_VERSION},- data={"entrypoint": "interactive", "execution_surface": "cli"},- )- assert task_counter(start) == (- "hermes.task_run.started",- {"entrypoint": "interactive", "execution_surface": "cli"},- )- terminal_fields = task_terminal_fields(- {- "platform": "cli",- "completed": True,- "turn_exit_reason": "text_response(stop)",- },- duration_ms=6_000,- model_call_count=2,- tool_call_count=3,- retry_count=1,- )- end = SimpleNamespace(**{- **start.__dict__,- "scope_category": "end",- "data": terminal_fields,- })- assert task_counter(end) == (- "hermes.task_run.finished",- terminal_fields,- )- end.data["task_id"] = "must-not-pass"- assert task_counter(end) is None- end.data.pop("task_id")- end.data["outcome"] = "private"- assert task_counter(end) is None- end.data["outcome"] = "success"- end.metadata["prompt"] = "must-not-pass"- assert task_counter(end) is None- def test_store_rejects_an_unsupported_schema_version(tmp_path):- database_path = tmp_path / "metrics.sqlite3"- with sqlite3.connect(database_path) as connection:- connection.execute(- "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"- )- connection.execute(- "INSERT INTO telemetry_state(key, value) VALUES ('schema_version', '999')"- )- with pytest.raises(RuntimeError, match="Unsupported shared-metrics store schema"):- SharedMetricsStore(database_path, tmp_path / "outbox")- with sqlite3.connect(database_path) as connection:- [schema_version] = connection.execute(- "SELECT value FROM telemetry_state WHERE key = 'schema_version'"- ).fetchone()- assert schema_version == "999"- def test_pending_metrics_keep_the_version_recorded_at_event_time(tmp_path):- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")- store.record_model_call(_dimensions(), "version-a")- store.record_model_call(_dimensions(), "version-b")- packages = [- json.loads(path.read_text(encoding="utf-8"))- for path in store.create_and_export_package()- ]- assert {package["resource"]["hermes_version"] for package in packages} == {- "version-a",- "version-b",- }- assert all(package["metrics"][0]["value"] == 1 for package in packages)- def test_store_exports_task_started_and_terminal_counters(tmp_path):- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")- store.record_counter(- "hermes.task_run.started",- {"entrypoint": "interactive", "execution_surface": "cli"},- "test-version",- )- terminal = task_terminal_fields(- {- "platform": "cli",- "completed": True,- "turn_exit_reason": "text_response(stop)",- },- duration_ms=2_000,- model_call_count=1,- tool_call_count=2,- retry_count=0,- )- store.record_counter("hermes.task_run.finished", terminal, "test-version")- [package_path] = store.create_and_export_package()- package = json.loads(package_path.read_text(encoding="utf-8"))- _schema_validator().validate(package)- assert {metric["name"] for metric in package["metrics"]} == {- "hermes.task_run.finished",- "hermes.task_run.started",- }- def test_package_schema_rejects_unknown_fields(tmp_path):- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")- store.record_model_call(_dimensions(), "test-version")- [package_path] = store.create_and_export_package()- package = json.loads(package_path.read_text(encoding="utf-8"))- invalid_package = deepcopy(package)- invalid_package["prompt"] = "must-not-be-accepted"- jsonschema = pytest.importorskip("jsonschema")- with pytest.raises(jsonschema.ValidationError):- _schema_validator().validate(invalid_package)- def test_store_rejects_dimensions_outside_the_metric_contract(tmp_path):- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")- with pytest.raises(ValueError, match="Unsupported dimensions"):- store.record_counter(- MODEL_ROUTE_METRIC,- {"prompt": "must-not-be-persisted"},- "test-version",- )- assert store.counter_snapshot() == []- def test_store_does_not_record_the_retired_model_metric(tmp_path):- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")- with pytest.raises(ValueError, match="Unsupported shared metric"):- store.record_counter(- LEGACY_MODEL_CALL_METRIC,- _legacy_dimensions(),- "test-version",- )- assert store.counter_snapshot() == []--- def test_package_builder_rejects_tampered_dimensions(tmp_path):- database_path = tmp_path / "metrics.sqlite3"- outbox_directory = tmp_path / "outbox"- store = SharedMetricsStore(database_path, outbox_directory)- store.record_model_call(_dimensions(), "test-version")- with sqlite3.connect(database_path) as connection:- connection.execute(- "UPDATE counter_aggregates SET dimensions_json = ?",- (json.dumps({"prompt": "must-not-be-exported"}),),- )-- with pytest.raises(ValueError, match="Unsupported dimensions"):- store.create_and_export_package()-- assert list(outbox_directory.glob("*.json")) == []--- def test_pending_package_retry_reuses_the_same_package_and_file(tmp_path):- database_path = tmp_path / "metrics.sqlite3"- outbox_directory = tmp_path / "outbox"- store = SharedMetricsStore(database_path, outbox_directory)- store.record_model_call(_dimensions(), "test-version")- [package_path] = store.create_and_export_package()- original_payload = package_path.read_bytes()-- with sqlite3.connect(database_path) as connection:- connection.execute("UPDATE package_outbox SET exported_at = NULL")-- restarted = SharedMetricsStore(database_path, outbox_directory)- assert restarted.create_and_export_package() == [package_path]- assert package_path.read_bytes() == original_payload- assert list(outbox_directory.glob("*.json")) == [package_path]def test_retention_prunes_only_expired_exported_history(tmp_path):diff --cc tests/hermes_cli/test_relay_shared_metrics_runtime.pyindex ae3f8b36500,fab88396da7..9f77ed9f919--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@@ -1827,702 -888,28 +891,204 @@@ def test_subagent_agent_boundary_closes)- def test_concurrent_subagents_inherit_parent_turn_and_close_independently(- direct_runtime,- ):- from concurrent.futures import ThreadPoolExecutor-- coordinator = relay_runtime.SESSION_COORDINATOR- profile_key = relay_runtime.current_profile_key()- parent_lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id="parent",- platform="cli",- )- parent_turn = coordinator.begin_turn(- parent_lease,- turn_id="parent-turn",- task_id="parent-task",- )-- def run_child(child_id):- lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id=child_id,- platform="subagent",- parent_session_id="parent",- )- turn = coordinator.begin_turn(- lease,- turn_id=f"{child_id}-turn",- task_id=f"{child_id}-task",- )- coordinator.end_turn(turn, outcome="success")- coordinator.finalize_conversation(- profile_key=profile_key,- session_id=child_id,- )- coordinator.release_conversation(lease)- contexts = [contextvars.copy_context(), contextvars.copy_context()]- with ThreadPoolExecutor(max_workers=2) as executor:- futures = [- executor.submit(context.run, run_child, f"child-{index}")- for index, context in enumerate(contexts)- ]- for future in futures:- future.result()- runtime = relay_runtime.get_runtime(create=False)- assert runtime is not None- assert runtime.get_session("child-0") is None- assert runtime.get_session("child-1") is None- child_pushes = [- event- for event in direct_runtime.events- if event[0] == "scope.push"- and event[1] == relay_runtime.SESSION_SCOPE- and event[3]["metadata"].get("nemo_relay_scope_role") == "subagent"- ]- assert len(child_pushes) == 2- assert all(event[3]["handle"] == parent_turn.handle for event in child_pushes)- coordinator.end_turn(parent_turn, outcome="success")- coordinator.release_conversation(parent_lease)- coordinator.finalize_conversation(- profile_key=profile_key,- session_id="parent",- )- def test_coordinator_tracks_active_turns_across_threads(direct_runtime):- del direct_runtime- coordinator = relay_runtime.SESSION_COORDINATOR- profile_key = relay_runtime.current_profile_key()- lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id="cross-thread-child",- platform="subagent",- )- assert not coordinator.has_active_turn(- profile_key=profile_key,- session_id="cross-thread-child",- )- turn = coordinator.begin_turn(- lease,- turn_id="child-turn",- task_id="child-task",- )- observed = []- thread = threading.Thread(- target=lambda: observed.append(- coordinator.has_active_turn(- profile_key=profile_key,- session_id="cross-thread-child",- )- )- )- thread.start()- thread.join(timeout=5)- assert observed == [True]- coordinator.end_turn(turn, outcome="success")- assert not coordinator.has_active_turn(- profile_key=profile_key,- session_id="cross-thread-child",- )- coordinator.release_conversation(lease)- coordinator.finalize_conversation(- profile_key=profile_key,- session_id="cross-thread-child",- )- def test_child_session_closes_before_active_turn_guard_is_released(- direct_runtime,- monkeypatch,- ):- del direct_runtime- coordinator = relay_runtime.SESSION_COORDINATOR- profile_key = relay_runtime.current_profile_key()- parent_lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id="parent",- platform="cli",- )- child_lease = coordinator.acquire_conversation(- profile_key=profile_key,- session_id="child",- platform="subagent",- parent_session_id="parent",- )- child_turn = coordinator.begin_turn(- child_lease,- turn_id="child-turn",- task_id="child-task",- )- runtime = relay_runtime.get_runtime(create=False)- assert runtime is not None- close_observations = []- original_close = runtime.close_session-- def observe_close(event):- close_observations.append(- coordinator.has_active_turn(- profile_key=profile_key,- session_id="child",- )- )- original_close(event)- monkeypatch.setattr(runtime, "close_session", observe_close)- coordinator.end_turn(child_turn, outcome="success")- assert close_observations == [True]- assert runtime.get_session("child") is None- assert not coordinator.has_active_turn(- profile_key=profile_key,- session_id="child",- )- coordinator.release_conversation(child_lease)- coordinator.release_conversation(parent_lease)- coordinator.finalize_conversation(- profile_key=profile_key,- session_id="parent",- )- def test_core_runtime_ignores_self_parenting_subagent_event(direct_runtime):- runtime = relay_runtime.get_runtime()- assert runtime is not None- runtime.register_subagent({"parent_session_id": "same", "child_session_id": "same"})- session = runtime.ensure_session({"session_id": "same"})- assert session is not None- assert session.parent_session_id == ""+++def test_terminal_model_error_retains_the_failed_route(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "api_request_id": "r1",+ "provider": "anthropic",+ "model": "claude-sonnet",+ }++ lifecycle.invoke_hook("pre_api_request", **base)+ lifecycle.invoke_hook(+ "api_request_error",+ **base,+ retryable=False,+ error={"message": "sensitive-error"},+ )+ assert not [event for event in direct_runtime.events if event[0] == "llm.call_end"]+ runtime = relay_shared_metrics._get_runtime()+ session = runtime._session(base)+ assert session is not None+ [model_call] = session.model_calls.values()+ assert model_call.fields == {+ "model": "claude-sonnet",+ "provider": "anthropic",+ }+ lifecycle.finalize_session(session_id="s1")++ [end] = [event for event in direct_runtime.events if event[0] == "llm.call_end"]+ assert end[2] == {+ "model": "claude-sonnet",+ "provider": "anthropic",+ }+++def test_nonretryable_provider_error_can_recover_within_one_logical_call(+ direct_runtime,+):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "api_request_id": "r1",+ "provider": "anthropic",+ "model": "claude-sonnet",+ }++ lifecycle.invoke_hook("pre_api_request", **base, retry_count=0)+ lifecycle.invoke_hook(+ "api_request_error",+ **base,+ retry_count=0,+ retryable=False,+ )+ fallback = {+ **base,+ "provider": "openai-api",+ "model": "gpt-5",+ }+ lifecycle.invoke_hook("pre_api_request", **fallback, retry_count=0)+ lifecycle.invoke_hook(+ "post_api_request",+ **fallback,+ retry_count=0,+ )+ lifecycle.finalize_session(session_id="s1")++ [end] = [event for event in direct_runtime.events if event[0] == "llm.call_end"]+ [start] = [event for event in direct_runtime.events if event[0] == "llm.call"]+ assert start[3]["model_name"] == "unknown"+ assert end[2] == {+ "model": "gpt-5",+ "provider": "openai-api",+ }+++def test_same_request_id_is_isolated_between_tasks(direct_runtime):+ common = {+ "session_id": "s1",+ "api_request_id": "shared-request",+ "platform": "cli",+ "provider": "anthropic",+ "model": "claude-sonnet",+ }+ for task_id in ("t1", "t2"):+ lifecycle.invoke_hook("pre_llm_call", **common, task_id=task_id)+ lifecycle.invoke_hook("pre_api_request", **common, task_id=task_id)++ lifecycle.invoke_hook("post_api_request", **common)+ assert not [event for event in direct_runtime.events if event[0] == "llm.call_end"]++ for task_id in ("t2", "t1"):+ lifecycle.invoke_hook("post_api_request", **common, task_id=task_id)+ lifecycle.invoke_hook(+ "on_session_end",+ **common,+ task_id=task_id,+ completed=True,+ failed=False,+ interrupted=False,+ turn_exit_reason="text_response(stop)",+ )+ lifecycle.finalize_session(session_id="s1")++ model_ends = [+ event for event in direct_runtime.events if event[0] == "llm.call_end"+ ]+ assert len(model_ends) == 2+ task_ends = [+ event[2]["output"]+ for event in direct_runtime.events+ if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"+ ]+ assert len(task_ends) == 2+ assert all(fields["model_call_count_bucket"] == "1" for fields in task_ends)+ assert all(fields["retry_count_bucket"] == "0" for fields in task_ends)++- def test_task_terminal_counts_logical_calls_retries_and_unique_tools(direct_runtime):++def test_task_retry_count_survives_provider_fallback_ordinal_reset(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "api_request_id": "r1",+ "platform": "cli",+ "provider": "nvidia",+ "model": "nvidia/nemotron-3-super-120b-a12b",+ }++ lifecycle.invoke_hook("pre_llm_call", **base)- lifecycle.invoke_hook("pre_api_request", **base)- lifecycle.invoke_hook("api_request_error", **base, retryable=True)- lifecycle.invoke_hook("pre_api_request", **base)- lifecycle.invoke_hook("api_request_error", **base, retryable=True)- lifecycle.invoke_hook("pre_api_request", **base)- lifecycle.invoke_hook("api_request_error", **base, retryable=False)- for tool_call_id in ("tool-1", "tool-1", "tool-2"):- lifecycle.invoke_hook(- "post_tool_call",- **base,- tool_call_id=tool_call_id,- tool_name="terminal",- result={"output": "private"},- status="ok",- )- lifecycle.invoke_hook(- "on_session_end",- **base,- completed=False,- failed=True,- interrupted=False,- turn_exit_reason="all_retries_exhausted_no_response",- )- lifecycle.finalize_session(session_id="s1")-- model_starts = [event for event in direct_runtime.events if event[0] == "llm.call"]- model_ends = [- event for event in direct_runtime.events if event[0] == "llm.call_end"- ]- assert len(model_starts) == 1- assert len(model_ends) == 1- assert model_ends[0][2] == {- "model": "nvidia/nemotron-3-super-120b-a12b",- "provider": "nvidia",- }- [task_end] = [- event- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- assert task_end[2]["output"] == {- "duration_bucket": task_end[2]["output"]["duration_bucket"],- "end_reason": "failed",- "entrypoint": "interactive",- "execution_surface": "cli",- "model_call_count_bucket": "1",- "outcome": "failed",- "retry_count_bucket": "2",- "termination": "none",- "tool_call_count_bucket": "2",- }--- def test_task_terminal_counts_explicit_retry_with_new_request_id(direct_runtime):- base = {- "session_id": "s1",- "task_id": "t1",- "platform": "cli",- "provider": "nvidia",- "model": "nvidia/nemotron-3-super-120b-a12b",- }-- lifecycle.invoke_hook("pre_llm_call", **base)- lifecycle.invoke_hook(- "pre_api_request",- **base,- api_request_id="r1",- retry_count=0,- )- lifecycle.invoke_hook(- "api_request_error",- **base,- api_request_id="r1",- retryable=True,- )- lifecycle.invoke_hook(- "pre_api_request",- **base,- api_request_id="r2",- retry_count=1,- )- lifecycle.invoke_hook(- "post_api_request",- **base,- api_request_id="r2",- )- lifecycle.invoke_hook(- "on_session_end",- **base,- completed=True,- failed=False,- interrupted=False,- turn_exit_reason="text_response(stop)",- )- lifecycle.finalize_session(session_id="s1")-- [task_end] = [- event- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- assert task_end[2]["output"]["model_call_count_bucket"] == "2"- assert task_end[2]["output"]["retry_count_bucket"] == "1"--- def test_task_retry_count_survives_provider_fallback_ordinal_reset(direct_runtime):- base = {- "session_id": "s1",- "task_id": "t1",- "api_request_id": "r1",- "platform": "cli",- "provider": "nvidia",- "model": "nvidia/nemotron-3-super-120b-a12b",- }-- lifecycle.invoke_hook("pre_llm_call", **base)- lifecycle.invoke_hook("pre_api_request", **base, retry_count=0)++ lifecycle.invoke_hook("pre_api_request", **base, retry_count=0)+ lifecycle.invoke_hook(+ "api_request_error",+ **base,+ retry_count=0,+ retryable=True,+ )+ lifecycle.invoke_hook("pre_api_request", **base, retry_count=1)+ lifecycle.invoke_hook(+ "api_request_error",+ **base,+ retry_count=1,+ retryable=True,+ )+ lifecycle.invoke_hook(+ "pre_api_request",+ **{**base, "provider": "openai", "model": "gpt-5"},+ retry_count=0,+ )+ lifecycle.invoke_hook(+ "post_api_request",+ **{**base, "provider": "openai", "model": "gpt-5"},+ retry_count=0,+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=True,+ failed=False,+ interrupted=False,+ turn_exit_reason="text_response(stop)",+ )+ lifecycle.finalize_session(session_id="s1")++ [model_end] = [+ event for event in direct_runtime.events if event[0] == "llm.call_end"+ ]+ assert model_end[2] == {+ "model": "gpt-5",+ "provider": "openai",+ }+ [task_end] = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"+ ]+ assert task_end[2]["output"]["retry_count_bucket"] == "2"- def test_outer_agent_boundary_closes_early_returns_and_exceptions(- direct_runtime,- monkeypatch,- ):- from run_agent import AIAgent-- agent = SimpleNamespace(- session_id="s1",- platform="cli",- _parent_session_id=None,- _session_db=None,- _conversation_root_id=lambda: "s1",- )-- def early_failure(*_args: Any, **_kwargs: Any) -> dict[str, Any]:- return {- "final_response": "private failure detail",- "completed": False,- "failed": True,- "interrupted": False,- }-- monkeypatch.setattr(- "agent.conversation_loop.run_conversation",- early_failure,- )- result = AIAgent.run_conversation(agent, "private prompt", task_id="early")- assert result["failed"] is True-- def raise_failure(*_args: Any, **_kwargs: Any) -> dict[str, Any]:- raise RuntimeError("private exception detail")-- monkeypatch.setattr(- "agent.conversation_loop.run_conversation",- raise_failure,- )- with pytest.raises(RuntimeError, match="private exception detail"):- AIAgent.run_conversation(agent, "private prompt", task_id="exception")-- def raise_interrupt(*_args: Any, **_kwargs: Any) -> dict[str, Any]:- raise KeyboardInterrupt-- monkeypatch.setattr(- "agent.conversation_loop.run_conversation",- raise_interrupt,- )- with pytest.raises(KeyboardInterrupt):- AIAgent.run_conversation(agent, "private prompt", task_id="cancelled")-- def raise_timeout(*_args: Any, **_kwargs: Any) -> dict[str, Any]:- raise TimeoutError("private timeout detail")-- monkeypatch.setattr(- "agent.conversation_loop.run_conversation",- raise_timeout,- )- with pytest.raises(TimeoutError, match="private timeout detail"):- AIAgent.run_conversation(agent, "private prompt", task_id="timed-out")-- lifecycle.finalize_session(session_id="s1")-- task_ends = [- event[2]["output"]- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- assert len(task_ends) == 4- assert task_ends[0]["outcome"] == "failed"- assert task_ends[0]["end_reason"] == "failed"- assert task_ends[0]["termination"] == "none"- assert task_ends[1]["outcome"] == "failed"- assert task_ends[1]["end_reason"] == "system_aborted"- assert task_ends[1]["termination"] == "system_aborted"- assert task_ends[2]["outcome"] == "cancelled"- assert task_ends[2]["end_reason"] == "user_cancelled"- assert task_ends[2]["termination"] == "user_cancelled"- assert task_ends[3]["outcome"] == "timed_out"- assert task_ends[3]["end_reason"] == "timed_out"- assert task_ends[3]["termination"] == "timed_out"- serialized = json.dumps(direct_runtime.events)- assert "private prompt" not in serialized- assert "private failure detail" not in serialized- assert "private exception detail" not in serialized- assert "private timeout detail" not in serialized--- def test_outer_agent_boundary_preserves_a_returned_timeout_reason(- direct_runtime,- monkeypatch,- ):- from run_agent import AIAgent-- agent = SimpleNamespace(- session_id="s1",- platform="cli",- _parent_session_id=None,- _session_db=None,- _conversation_root_id=lambda: "s1",- )-- monkeypatch.setattr(- "agent.conversation_loop.run_conversation",- lambda *_args, **_kwargs: {- "final_response": "private timeout response",- "completed": False,- "failed": True,- "failure_reason": "timeout",- },- )- AIAgent.run_conversation(agent, "private prompt", task_id="timed-out")-- [task_end] = [- event[2]["output"]- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- assert task_end["outcome"] == "timed_out"- assert task_end["end_reason"] == "timed_out"- assert task_end["termination"] == "timed_out"- serialized = json.dumps(direct_runtime.events)- assert "private prompt" not in serialized- assert "private timeout response" not in serialized--- def test_session_finalize_closes_a_pending_task_as_system_aborted(direct_runtime):- lifecycle.invoke_hook(- "pre_llm_call",- session_id="s1",- task_id="t1",- platform="cli",- )-- lifecycle.finalize_session(session_id="s1")-- [task_end] = [- event- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- assert task_end[2]["output"] == {- "duration_bucket": task_end[2]["output"]["duration_bucket"],- "end_reason": "system_aborted",- "entrypoint": "interactive",- "execution_surface": "cli",- "model_call_count_bucket": "0",- "outcome": "failed",- "retry_count_bucket": "0",- "termination": "system_aborted",- "tool_call_count_bucket": "0",- }--- def test_desktop_task_completion_exports_once_per_utc_day(- direct_runtime, tmp_path, monkeypatch- ):- current_time = datetime(2026, 7, 28, 9, tzinfo=timezone.utc)- monkeypatch.setattr(- "hermes_cli.observability.shared_metrics._utc_now",- lambda: current_time,- )- for task_id in ("t1", "t2"):- lifecycle.invoke_hook(- "pre_llm_call",- session_id="s1",- task_id=task_id,- platform="desktop",- )- lifecycle.invoke_hook(- "on_session_end",- session_id="s1",- task_id=task_id,- platform="desktop",- completed=True,- failed=False,- interrupted=False,- turn_exit_reason="text_response(stop)",- )-- outbox = tmp_path / "hermes-home" / "telemetry" / "shared_metrics" / "outbox"- [first_package_path] = list(outbox.glob("*.json"))- first_package = json.loads(first_package_path.read_text(encoding="utf-8"))- first_metrics = {metric["name"]: metric for metric in first_package["metrics"]}- assert first_metrics["hermes.task_run.started"]["value"] == 1- assert first_metrics["hermes.task_run.started"]["dimensions"] == {- "entrypoint": "interactive",- "execution_surface": "desktop",- }- assert first_metrics["hermes.task_run.finished"]["value"] == 1-- lifecycle.finalize_session(session_id="s1")- assert list(outbox.glob("*.json")) == [first_package_path]-- current_time = datetime(2026, 7, 29, 9, tzinfo=timezone.utc)- lifecycle.invoke_hook(- "pre_llm_call",- session_id="s1",- task_id="t3",- platform="desktop",- )- lifecycle.invoke_hook(- "on_session_end",- session_id="s1",- task_id="t3",- platform="desktop",- completed=True,- failed=False,- interrupted=False,- turn_exit_reason="text_response(stop)",- )-- packages = [- json.loads(package_path.read_text(encoding="utf-8"))- for package_path in outbox.glob("*.json")- ]- totals: dict[str, int] = {}- for package in packages:- for metric in package["metrics"]:- totals[metric["name"]] = totals.get(metric["name"], 0) + metric["value"]- assert totals["hermes.task_run.started"] == 3- assert totals["hermes.task_run.finished"] == 3--def test_failed_flush_keeps_daily_export_open_for_later_task(direct_runtime, tmp_path, monkeypatch, caplog):@@@ -2582,185 -969,9 +1148,8 @@@assert "Hermes shared-metrics task flush failed" in caplog.text- def test_task_ownership_survives_session_id_rotation(direct_runtime):- lifecycle.invoke_hook(- "pre_llm_call",- session_id="before-compression",- task_id="t1",- platform="cli",- )- lifecycle.invoke_hook(- "pre_api_request",- session_id="after-compression",- task_id="t1",- api_request_id="r1",- platform="cli",- provider="nvidia",- model="nvidia/nemotron-3-super-120b-a12b",- )- lifecycle.invoke_hook(- "post_api_request",- session_id="after-compression",- task_id="t1",- api_request_id="r1",- platform="cli",- provider="nvidia",- model="nvidia/nemotron-3-super-120b-a12b",- )- lifecycle.invoke_hook(- "on_session_end",- session_id="after-compression",- task_id="t1",- platform="cli",- completed=True,- failed=False,- interrupted=False,- turn_exit_reason="text_response(stop)",- )- lifecycle.finalize_session(session_id="before-compression")- task_starts = [- event- for event in direct_runtime.events- if event[0] == "scope.push" and event[1] == "hermes.task_run"- ]- task_ends = [- event- for event in direct_runtime.events- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"- ]- model_ends = [- event for event in direct_runtime.events if event[0] == "llm.call_end"- ]- assert len(task_starts) == 1- assert len(task_ends) == 1- assert len(model_ends) == 1- assert model_ends[0][2] == {- "model": "nvidia/nemotron-3-super-120b-a12b",- "provider": "nvidia",- }- assert task_ends[0][2]["output"]["model_call_count_bucket"] == "1"- assert task_ends[0][2]["output"]["outcome"] == "success"- def test_gateway_and_delegated_entrypoints_flow_through_relay(direct_runtime):- tasks = [- {- "session_id": "gateway-session",- "task_id": "gateway-task",- "platform": "whatsapp_cloud",- },- {- "session_id": "child-session",- "task_id": "delegated-task",- "platform": "cli",- "parent_session_id": "private-parent-session",- },- ]- for task in tasks:- lifecycle.invoke_hook("pre_llm_call", **task)- lifecycle.invoke_hook(- "on_session_end",- **task,- completed=True,- failed=False,- interrupted=False,- turn_exit_reason="text_response(stop)",- )-- starts = [- event[3]["input"]- for event in direct_runtime.events- if event[0] == "scope.push" and event[1] == "hermes.task_run"- ]- assert starts == [- {"entrypoint": "gateway_message", "execution_surface": "gateway"},- {"entrypoint": "delegated", "execution_surface": "cli"},- ]- assert "private-parent-session" not in json.dumps(direct_runtime.events)--- def test_persistence_failure_does_not_escape_the_hook(- direct_runtime,- monkeypatch,- caplog,- ):- runtime = relay_shared_metrics._get_runtime()- assert runtime is not None- def fail_record(*_args: Any, **_kwargs: Any) -> None:- raise OSError("store unavailable")- monkeypatch.setattr(runtime.subscriber.store, "record_counter", fail_record)- lifecycle.invoke_hook(- "pre_api_request",- session_id="s1",- task_id="t1",- api_request_id="r1",- provider="openai",- model="gpt-5",- )- lifecycle.invoke_hook(- "post_api_request",- session_id="s1",- task_id="t1",- api_request_id="r1",- provider="openai",- model="gpt-5",- )-- assert "Unable to persist the Hermes shared metric" in caplog.text--- def test_close_does_not_reopen_a_session_after_scope_start_failure(- direct_runtime,- monkeypatch,- ):- runtime = relay_runtime.get_runtime()- assert runtime is not None- original_push = direct_runtime.scope.push- push_attempts = 0-- def fail_first_push(*args: Any, **kwargs: Any) -> Any:- nonlocal push_attempts- push_attempts += 1- if push_attempts == 1:- raise RuntimeError("simulated scope failure")- return original_push(*args, **kwargs)-- direct_runtime.scope.push = fail_first_push- with pytest.raises(RuntimeError, match="simulated scope failure"):- runtime.ensure_session({"session_id": "s1"})-- close_started = threading.Event()- allow_close = threading.Event()- original_flush = direct_runtime.subscribers.flush-- def block_flush():- session = runtime._sessions["s1"]- assert session.closing is True- close_started.set()- assert allow_close.wait(timeout=5)- original_flush()-- direct_runtime.subscribers.flush = block_flush- close_thread = threading.Thread(- target=runtime.close_session,- args=({"session_id": "s1"},),- )- close_thread.start()- assert close_started.wait(timeout=5)-- ensure_thread = threading.Thread(- target=runtime.ensure_session,- args=({"session_id": "s1"},),- )- ensure_thread.start()- allow_close.set()- close_thread.join(timeout=5)- ensure_thread.join(timeout=5)--- assert not close_thread.is_alive()- assert not ensure_thread.is_alive()- assert push_attempts == 1- assert "s1" not in runtime._sessions