The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge updated model metrics into tool metrics
Alex Fournieraef76ba39843
diff --cc hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.jsonindex 00000000000,112b9f3ce86..da8e7c78d0cmode 000000,100644..100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json@@@ -1,0 -1,385 +1,544 @@@+ {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "urn:hermes-agent:schema:shared-metrics:v2",+ "title": "Hermes Shared Metrics Package v2",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schema_version",+ "package_id",+ "install_id",+ "period_start",+ "period_end",+ "generated_at",+ "resource",+ "metrics"+ ],+ "properties": {+ "schema_version": {+ "const": "hermes.shared_metrics.v2"+ },+ "package_id": {+ "$ref": "#/$defs/uuid"+ },+ "install_id": {+ "description": "Random persistent identifier scoped to one HERMES_HOME; local-only in schema v2.",+ "$ref": "#/$defs/uuid"+ },+ "period_start": {+ "type": "string",+ "format": "date-time"+ },+ "period_end": {+ "type": "string",+ "format": "date-time"+ },+ "generated_at": {+ "type": "string",+ "format": "date-time"+ },+ "resource": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "hermes_version"+ ],+ "properties": {+ "hermes_version": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ }+ },+ "metrics": {+ "type": "array",+ "minItems": 1,+ "items": {+ "oneOf": [+ {+ "$ref": "#/$defs/model_call_counter"+ },+ {+ "$ref": "#/$defs/model_route_counter"+ },+ {+ "$ref": "#/$defs/task_started_counter"+ },+ {+ "$ref": "#/$defs/task_finished_counter"++ },++ {++ "$ref": "#/$defs/tool_call_counter"++ },++ {++ "$ref": "#/$defs/tool_approval_counter"+ }+ ]+ }+ }+ },+ "$defs": {+ "uuid": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"+ },+ "model_call_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.model_call.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "call_role",+ "locality",+ "model_family",+ "outcome",+ "provider_family"+ ],+ "properties": {+ "call_role": {+ "const": "primary"+ },+ "locality": {+ "enum": [+ "local",+ "remote",+ "unknown"+ ]+ },+ "model_family": {+ "enum": [+ "claude",+ "deepseek",+ "gemini",+ "gemma",+ "glm",+ "gpt",+ "grok",+ "kimi",+ "llama",+ "minimax",+ "mimo",+ "mistral",+ "nemotron",+ "nova",+ "o1",+ "o3",+ "o4",+ "qwen",+ "step",+ "trinity",+ "unknown"+ ]+ },+ "outcome": {+ "enum": [+ "cancelled",+ "failed",+ "success"+ ]+ },+ "provider_family": {+ "enum": [+ "aggregator",+ "custom",+ "direct",+ "local",+ "unknown"+ ]+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "model_route_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.model_route.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "model",+ "provider"+ ],+ "properties": {+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "task_started_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.task_run.started"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "entrypoint",+ "execution_surface"+ ],+ "properties": {+ "entrypoint": {+ "$ref": "#/$defs/task_entrypoint"+ },+ "execution_surface": {+ "$ref": "#/$defs/execution_surface"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "task_finished_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.task_run.finished"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "duration_bucket",+ "end_reason",+ "entrypoint",+ "execution_surface",+ "model_call_count_bucket",+ "outcome",+ "retry_count_bucket",+ "termination",+ "tool_call_count_bucket"+ ],+ "properties": {+ "duration_bucket": {+ "$ref": "#/$defs/duration_bucket"+ },+ "end_reason": {+ "enum": [+ "approval_denied",+ "completed",+ "failed",+ "guardrail_blocked",+ "iteration_limit",+ "system_aborted",+ "timed_out",+ "unknown",+ "user_cancelled"+ ]+ },+ "entrypoint": {+ "$ref": "#/$defs/task_entrypoint"+ },+ "execution_surface": {+ "$ref": "#/$defs/execution_surface"+ },+ "model_call_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ },+ "outcome": {+ "enum": [+ "cancelled",+ "failed",+ "success",+ "timed_out",+ "unknown"+ ]+ },+ "retry_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ },+ "termination": {+ "enum": [+ "none",+ "system_aborted",+ "timed_out",+ "unknown",+ "user_cancelled"+ ]+ },+ "tool_call_count_bucket": {+ "$ref": "#/$defs/count_bucket"+ }+ }+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "execution_surface": {+ "enum": [+ "api",+ "batch",+ "cli",+ "desktop",+ "gateway",+ "other",+ "python",+ "scheduled_task",+ "tui",+ "unknown"+ ]+ },+ "task_entrypoint": {+ "enum": [+ "api",+ "background",+ "batch",+ "delegated",+ "gateway_message",+ "interactive",+ "other",+ "python",+ "scheduled_task",+ "unknown"+ ]+ },+ "duration_bucket": {+ "enum": [+ "1s_to_5s",+ "2m_to_10m",+ "30s_to_2m",+ "5s_to_30s",+ "gte_10m",+ "lt_1s"+ ]+ },+ "count_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "gte_11"+ ]++ },++ "tool_latency_bucket": {++ "enum": [++ "100ms_to_250ms",++ "10s_to_30s",++ "1s_to_2s",++ "250ms_to_500ms",++ "2s_to_5s",++ "500ms_to_1s",++ "5s_to_10s",++ "gte_30s",++ "lt_100ms",++ "unknown"++ ]++ },++ "tool_retry_bucket": {++ "enum": [++ "0",++ "1",++ "2",++ "3_to_5",++ "6_to_10",++ "gte_11",++ "unknown"++ ]++ },++ "tool_call_counter": {++ "type": "object",++ "additionalProperties": false,++ "required": [++ "name",++ "type",++ "dimensions",++ "value"++ ],++ "properties": {++ "name": {++ "const": "hermes.tool_call.count"++ },++ "type": {++ "const": "counter"++ },++ "dimensions": {++ "type": "object",++ "additionalProperties": false,++ "required": [++ "approval_outcome",++ "latency_bucket",++ "outcome",++ "retry_count_bucket",++ "tool_category"++ ],++ "properties": {++ "approval_outcome": {++ "enum": [++ "approved",++ "denied",++ "not_required",++ "timed_out",++ "unknown"++ ]++ },++ "latency_bucket": {++ "$ref": "#/$defs/tool_latency_bucket"++ },++ "outcome": {++ "enum": [++ "blocked",++ "cancelled",++ "failed",++ "success",++ "timed_out",++ "unknown"++ ]++ },++ "retry_count_bucket": {++ "$ref": "#/$defs/tool_retry_bucket"++ },++ "tool_category": {++ "enum": [++ "browser",++ "code_execution",++ "communication",++ "computer_use",++ "delegation",++ "file",++ "home_automation",++ "mcp",++ "media",++ "memory",++ "other",++ "planning",++ "project",++ "scheduler",++ "skill",++ "terminal",++ "unknown",++ "web"++ ]++ }++ }++ },++ "value": {++ "type": "integer",++ "minimum": 1++ }++ }++ },++ "tool_approval_counter": {++ "type": "object",++ "additionalProperties": false,++ "required": [++ "name",++ "type",++ "dimensions",++ "value"++ ],++ "properties": {++ "name": {++ "const": "hermes.tool_approval.count"++ },++ "type": {++ "const": "counter"++ },++ "dimensions": {++ "type": "object",++ "additionalProperties": false,++ "required": [++ "attribution",++ "outcome"++ ],++ "properties": {++ "attribution": {++ "enum": [++ "tool_call",++ "unattributed"++ ]++ },++ "outcome": {++ "enum": [++ "approved",++ "denied",++ "timed_out",++ "unknown"++ ]++ }++ }++ },++ "value": {++ "type": "integer",++ "minimum": 1++ }++ }+ }+ }+ }diff --cc hermes_cli/observability/shared_metrics_contract.pyindex 490ae136fa0,bb48952cb89..870152634f5--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@@ -2,24 -2,25 +2,30 @@@from __future__ import annotations+from math import isfinitefrom typing import Any- from agent.relay_runtime import RUNTIME_INSTANCE_KEY+ from agent.relay_runtime import (+ LOGICAL_LLM_SCOPE,+ RUNTIME_INSTANCE_KEY,+ RUNTIME_SCHEMA_KEY,+ RUNTIME_SCHEMA_VERSION,+ )SCHEMA_KEY = "hermes.metrics.schema_version"- SCHEMA_VERSION = "hermes.metrics.event.v1"+ SCHEMA_VERSION = "hermes.metrics.event.v2"MODEL_CALL_SCOPE = "hermes.model_call"MODEL_CALL_PROFILE_MODEL = "unknown"TASK_SCOPE = "hermes.task_run"+TOOL_CALL_SCOPE = "hermes.tool_call"+TOOL_APPROVAL_MARK = "hermes.tool_approval"SUBSCRIBER_NAME = "hermes.nemo_relay.shared_metrics"- MODEL_CALL_METRIC = "hermes.model_call.count"+ LEGACY_MODEL_CALL_METRIC = "hermes.model_call.count"+ MODEL_ROUTE_METRIC = "hermes.model_route.count"TASK_STARTED_METRIC = "hermes.task_run.started"TASK_FINISHED_METRIC = "hermes.task_run.finished"+TOOL_CALL_METRIC = "hermes.tool_call.count"+TOOL_APPROVAL_METRIC = "hermes.tool_approval.count"MODEL_IDENTIFIER_MAX_LENGTH = 256PROVIDER_IDENTIFIER_MAX_LENGTH = 64_METRIC_IDENTIFIER_CHARACTERS = frozenset(@@@ -94,60 -95,49 +100,101 @@@ COUNT_BUCKETS: frozenset[str] = frozens"6_to_10","gte_11",})+TOOL_CATEGORIES: frozenset[str] = frozenset({+ "browser",+ "code_execution",+ "communication",+ "computer_use",+ "delegation",+ "file",+ "home_automation",+ "mcp",+ "media",+ "memory",+ "other",+ "planning",+ "project",+ "scheduler",+ "skill",+ "terminal",+ "unknown",+ "web",+})+TOOL_OUTCOMES: frozenset[str] = frozenset({+ "blocked",+ "cancelled",+ "failed",+ "success",+ "timed_out",+ "unknown",+})+TOOL_APPROVAL_OUTCOMES: frozenset[str] = frozenset({+ "approved",+ "denied",+ "not_required",+ "timed_out",+ "unknown",+})+TOOL_APPROVAL_ATTRIBUTIONS: frozenset[str] = frozenset({+ "tool_call",+ "unattributed",+})+TOOL_LATENCY_BUCKETS: frozenset[str] = frozenset({+ "100ms_to_250ms",+ "10s_to_30s",+ "1s_to_2s",+ "250ms_to_500ms",+ "2s_to_5s",+ "500ms_to_1s",+ "5s_to_10s",+ "gte_30s",+ "lt_100ms",+ "unknown",+})+TOOL_RETRY_BUCKETS: frozenset[str] = COUNT_BUCKETS | frozenset({"unknown"})+ _LEGACY_PROVIDER_FAMILIES = frozenset({+ "aggregator",+ "custom",+ "direct",+ "local",+ "unknown",+ })+ _LEGACY_MODEL_LOCALITIES = frozenset({"local", "remote", "unknown"})+ _LEGACY_MODEL_OUTCOMES = frozenset({"cancelled", "failed", "success"})+ _LEGACY_MODEL_FAMILIES = frozenset({+ "claude",+ "deepseek",+ "gemini",+ "gemma",+ "glm",+ "gpt",+ "grok",+ "kimi",+ "llama",+ "minimax",+ "mimo",+ "mistral",+ "nemotron",+ "nova",+ "o1",+ "o3",+ "o4",+ "qwen",+ "step",+ "trinity",+ "unknown",+ })+_COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {+ # Retained only so pre-v2 pending rows remain packageable.+ LEGACY_MODEL_CALL_METRIC: {+ "call_role": frozenset({"primary"}),+ "locality": _LEGACY_MODEL_LOCALITIES,+ "model_family": _LEGACY_MODEL_FAMILIES,+ "outcome": _LEGACY_MODEL_OUTCOMES,+ "provider_family": _LEGACY_PROVIDER_FAMILIES,+ },TASK_STARTED_METRIC: {"entrypoint": TASK_ENTRYPOINTS,"execution_surface": EXECUTION_SURFACES,@@@ -163,21 -153,12 +210,25 @@@"termination": TASK_TERMINATIONS,"tool_call_count_bucket": COUNT_BUCKETS,},+ TOOL_CALL_METRIC: {+ "approval_outcome": TOOL_APPROVAL_OUTCOMES,+ "latency_bucket": TOOL_LATENCY_BUCKETS,+ "outcome": TOOL_OUTCOMES,+ "retry_count_bucket": TOOL_RETRY_BUCKETS,+ "tool_category": TOOL_CATEGORIES,+ },+ TOOL_APPROVAL_METRIC: {+ "attribution": TOOL_APPROVAL_ATTRIBUTIONS,+ "outcome": TOOL_APPROVAL_OUTCOMES - {"not_required"},+ },}- COUNTER_METRICS: frozenset[str] = frozenset(- {*_COUNTER_DIMENSION_VALUES, MODEL_CALL_METRIC}- )+ COUNTER_METRICS: frozenset[str] = frozenset({+ MODEL_ROUTE_METRIC,+ TASK_FINISHED_METRIC,+ TASK_STARTED_METRIC,++ TOOL_APPROVAL_METRIC,++ TOOL_CALL_METRIC,+ })def counter_dimensions_are_valid(@@@ -208,19 -190,19 +259,22 @@@)+def _event_metadata_is_valid(event: Any) -> bool:+ metadata = getattr(event, "metadata", None)+ if not isinstance(metadata, dict) or metadata.get(SCHEMA_KEY) != SCHEMA_VERSION:+ return False+ relay_metadata = set(metadata) - {SCHEMA_KEY, RUNTIME_INSTANCE_KEY}+ return not relay_metadata - {"otel.status_code"} and metadata.get(+ "otel.status_code", "OK"+ ) in {"OK", "ERROR"}++def model_call_dimensions(event: Any) -> dict[str, str] | None:- """Return package dimensions for one valid primary model-call end event."""+ """Return package dimensions for one valid logical model-call end event."""+ auxiliary = _auxiliary_model_call_dimensions(event)+ if auxiliary is not None:+ return auxiliary-- metadata = getattr(event, "metadata", None)- if not isinstance(metadata, dict) or metadata.get(SCHEMA_KEY) != SCHEMA_VERSION:- return None- relay_metadata = set(metadata) - {SCHEMA_KEY, RUNTIME_INSTANCE_KEY}- if relay_metadata - {"otel.status_code"} or metadata.get(- "otel.status_code", "OK"- ) not in {"OK", "ERROR"}:+ if not _event_metadata_is_valid(event):return Noneif (str(getattr(event, "kind", "") or "") != "scope"diff --cc hermes_cli/observability/shared_metrics_subscriber.pyindex 6f36a406792,259a6f6b4a2..086f88d4c23--- a/hermes_cli/observability/shared_metrics_subscriber.py+++ b/hermes_cli/observability/shared_metrics_subscriber.py@@@ -9,14 -9,7 +9,14 @@@ from typing import Anfrom agent.relay_runtime import RUNTIME_INSTANCE_KEYfrom .shared_metrics import SharedMetricsStore-from .shared_metrics_contract import MODEL_ROUTE_METRIC, model_call_dimensions, task_counter+from .shared_metrics_contract import (- MODEL_CALL_METRIC,++ MODEL_ROUTE_METRIC,+ TOOL_CALL_METRIC,+ model_call_dimensions,+ task_counter,+ tool_approval_counter,+ tool_call_dimensions,+)logger = logging.getLogger(__name__)@@@ -51,15 -44,12 +51,15 @@@ class SharedMetricsSubscriber):returndimensions = model_call_dimensions(event)- metric_name = MODEL_CALL_METRIC+ metric_name = MODEL_ROUTE_METRICif dimensions is None:- task_metric = task_counter(event)- if task_metric is None:+ dimensions = tool_call_dimensions(event)+ metric_name = TOOL_CALL_METRIC+ if dimensions is None:+ metric = task_counter(event) or tool_approval_counter(event)+ if metric is None:return- metric_name, dimensions = task_metric+ metric_name, dimensions = metricwith self._lock:if not self._active:returndiff --cc scripts/smoke_nemo_relay_shared_metrics.pyindex 92678de4978,a8bf4adb012..64c69bdc3c0--- a/scripts/smoke_nemo_relay_shared_metrics.py+++ b/scripts/smoke_nemo_relay_shared_metrics.py@@@ -292,31 -220,27 +292,31 @@@ def _validate_store(database_path: Path}for name, dimensions, value, packaged_value in rows]- by_name = {counter["name"]: counter for counter in counters}+ by_name: dict[str, list[dict[str, Any]]] = {}+ for counter in counters:+ by_name.setdefault(counter["name"], []).append(counter)if set(by_name) != {- "hermes.model_call.count",+ "hermes.model_route.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool_call.count",}:raise AssertionError(f"Unexpected SQLite counters:\n{json.dumps(counters, indent=2)}")- [model] = by_name["hermes.model_call.count"]++ [model] = by_name["hermes.model_route.count"]expected_model = {- "name": "hermes.model_call.count",+ "name": "hermes.model_route.count","dimensions": {"model": MODEL_CANARY,"provider": "custom",},- "value": 1,- "packaged_value": 1,+ "value": 2,+ "packaged_value": 2,}- if by_name["hermes.model_route.count"] != expected_model:+ if model != expected_model:raise AssertionError(- f"Unexpected model counter: {by_name['hermes.model_call.count']}"+ f"Unexpected model counter: {by_name['hermes.model_route.count']}")expected_start = {"name": "hermes.task_run.started",@@@ -393,27 -297,24 +393,27 @@@ def _validate_package(outbox: Path, schraise AssertionError(f"Exported package leaked prohibited value: {prohibited!r}")- metrics = {metric["name"]: metric for metric in package.get("metrics", [])}+ metrics: dict[str, list[dict[str, Any]]] = {}+ for metric in package.get("metrics", []):+ metrics.setdefault(metric["name"], []).append(metric)if set(metrics) != {- "hermes.model_call.count",+ "hermes.model_route.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool_call.count",}:raise AssertionError(f"Unexpected package metrics:\n{json.dumps(package.get('metrics'), indent=2)}")- [model] = metrics["hermes.model_call.count"]- model_dimensions = metrics["hermes.model_route.count"]["dimensions"]- if model_dimensions != {++ [model] = metrics["hermes.model_route.count"]+ if model["dimensions"] != {"model": MODEL_CANARY,"provider": "custom",- }:+ } or model["value"] != 2:raise AssertionError(- f"Unexpected model metric: {metrics['hermes.model_call.count']}"+ f"Unexpected model metric: {metrics['hermes.model_route.count']}")- terminal = metrics["hermes.task_run.finished"]+ [terminal] = metrics["hermes.task_run.finished"]if terminal["dimensions"] != {"duration_bucket": terminal["dimensions"].get("duration_bucket"),"end_reason": "completed",diff --cc tests/hermes_cli/test_plugins.pyindex 920e6f0276a,4d604ef8995..d4ea437b822--- a/tests/hermes_cli/test_plugins.py+++ b/tests/hermes_cli/test_plugins.py@@@ -981,71 -398,7 +446,34 @@@ class TestResolvePreToolBlock"""Tests for the single dispatch-site chokepoint that resolves adirective (incl. the approve→gate escalation) to a block message."""- def test_block_returns_message(self, monkeypatch):- from hermes_cli.plugins import resolve_pre_tool_block- monkeypatch.setattr(- "hermes_cli.plugins.invoke_hook",- lambda hook_name, **kwargs: [{"action": "block", "message": "no"}],- )- assert resolve_pre_tool_block("terminal", {}) == "no"-- def test_no_directive_returns_none(self, monkeypatch):- from hermes_cli.plugins import resolve_pre_tool_block- monkeypatch.setattr(- "hermes_cli.plugins.invoke_hook", lambda hook_name, **kwargs: [])- assert resolve_pre_tool_block("terminal", {}) is None-- def test_approve_denied_blocks(self, monkeypatch):- from hermes_cli.plugins import resolve_pre_tool_block- monkeypatch.setattr(- "hermes_cli.plugins.invoke_hook",- lambda hook_name, **kwargs: [{"action": "approve", "message": "why"}],- )- monkeypatch.setattr(- "tools.approval.request_tool_approval",- lambda *a, **k: {"approved": False, "message": "user denied it"},- )- assert resolve_pre_tool_block("write_file", {}) == "user denied it"-- def test_approve_granted_allows(self, monkeypatch):- from hermes_cli.plugins import resolve_pre_tool_block- monkeypatch.setattr(- "hermes_cli.plugins.invoke_hook",- lambda hook_name, **kwargs: [{"action": "approve", "message": "why"}],- )- monkeypatch.setattr(- "tools.approval.request_tool_approval",- lambda *a, **k: {"approved": True, "message": None},- )- assert resolve_pre_tool_block("write_file", {}) is None+ def test_approve_gate_receives_tool_observability_context(self, monkeypatch):+ from hermes_cli.plugins import resolve_pre_tool_block+ from tools import approval++ seen = {}+ monkeypatch.setattr(+ "hermes_cli.plugins.invoke_hook",+ lambda hook_name, **kwargs: [+ {"action": "approve", "message": "why"}+ ],+ )++ def _approve(*args, **kwargs):+ seen["turn_id"] = approval._approval_turn_id.get()+ seen["tool_call_id"] = approval._approval_tool_call_id.get()+ return {"approved": True, "message": None}++ monkeypatch.setattr("tools.approval.request_tool_approval", _approve)++ assert resolve_pre_tool_block(+ "write_file",+ {},+ turn_id="turn-1",+ tool_call_id="call-1",+ ) is None+ assert seen == {"turn_id": "turn-1", "tool_call_id": "call-1"}+def test_approve_passes_plugin_rule_key_to_gate(self, monkeypatch):from hermes_cli.plugins import resolve_pre_tool_blockdiff --cc tests/hermes_cli/test_relay_shared_metrics.pyindex 609e7a2bbfe,71abad092d4..18190d9cb19--- a/tests/hermes_cli/test_relay_shared_metrics.py+++ b/tests/hermes_cli/test_relay_shared_metrics.py@@@ -201,144 -314,21 +333,144 @@@ def test_package_schema_matches_the_modassert "enum" not in properties["provider"]- 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"]+ 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 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+ 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_tool_contract():+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))+ tool = _tool_dimension_schema("tool_call_counter")["properties"]+ approval = _tool_dimension_schema("tool_approval_counter")["properties"]++ assert set(tool["tool_category"]["enum"]) == TOOL_CATEGORIES+ assert set(tool["outcome"]["enum"]) == TOOL_OUTCOMES+ assert set(tool["approval_outcome"]["enum"]) == TOOL_APPROVAL_OUTCOMES+ assert tool["latency_bucket"] == {"$ref": "#/$defs/tool_latency_bucket"}+ assert tool["retry_count_bucket"] == {"$ref": "#/$defs/tool_retry_bucket"}+ assert set(schema["$defs"]["tool_latency_bucket"]["enum"]) == (+ TOOL_LATENCY_BUCKETS+ )+ assert set(schema["$defs"]["tool_retry_bucket"]["enum"]) == TOOL_RETRY_BUCKETS+ assert set(approval["attribution"]["enum"]) == TOOL_APPROVAL_ATTRIBUTIONS+ assert set(approval["outcome"]["enum"]) == (+ TOOL_APPROVAL_OUTCOMES - {"not_required"}+ )+++ ("toolset", "expected"),+ [+ ("", "unknown"),+ ("file", "file"),+ ("terminal", "terminal"),+ ("code_execution", "code_execution"),+ ("delegation", "delegation"),+ ("skills", "skill"),+ ("browser-cdp", "browser"),+ ("image_gen", "media"),+ ("homeassistant", "home_automation"),+ ("kanban", "planning"),+ ("project", "project"),+ ("discord", "communication"),+ ("feishu_doc", "communication"),+ ("mcp-github", "mcp"),+ ("private_plugin", "other"),+ ],+)+def test_tool_category_uses_bounded_runtime_toolsets(toolset, expected):+ assert tool_category({"toolset": toolset}) == expected+++def test_tool_category_does_not_classify_raw_tool_names():+ assert tool_category({"tool_name": "read_file"}) == "unknown"+++ ("status", "expected"),+ [+ ("ok", "success"),+ ("error", "failed"),+ ("blocked", "blocked"),+ ("cancelled", "cancelled"),+ ("timeout", "timed_out"),+ ("private", "unknown"),+ (None, "unknown"),+ ],+)+def test_tool_outcome_is_bounded(status, expected):+ assert tool_outcome({"status": status}) == expected+++ ("choice", "expected"),+ [+ ("once", "approved"),+ ("session", "approved"),+ ("always", "approved"),+ ("smart_approve", "approved"),+ ("deny", "denied"),+ ("smart_deny", "denied"),+ ("timeout", "timed_out"),+ (None, "unknown"),+ ],+)+def test_tool_approval_outcome_is_bounded(choice, expected):+ assert tool_approval_outcome({"choice": choice}) == expected+++ ("duration_ms", "expected"),+ [+ (0, "lt_100ms"),+ (100, "100ms_to_250ms"),+ (250, "250ms_to_500ms"),+ (500, "500ms_to_1s"),+ (1_000, "1s_to_2s"),+ (2_000, "2s_to_5s"),+ (5_000, "5s_to_10s"),+ (10_000, "10s_to_30s"),+ (30_000, "gte_30s"),+ (-1, "unknown"),+ (True, "unknown"),+ ("100", "unknown"),+ ],+)+def test_tool_latency_bucket_is_bounded(duration_ms, expected):+ assert tool_latency_bucket(duration_ms) == expected+++ ("retry_count", "expected"),+ [+ (0, "0"),+ (1, "1"),+ (2, "2"),+ (3, "3_to_5"),+ (6, "6_to_10"),+ (11, "gte_11"),+ (None, "unknown"),+ (-1, "unknown"),+ (True, "unknown"),+ ],+)+def test_tool_retry_bucket_requires_an_explicit_non_negative_count(+ retry_count,+ expected,+):+ assert tool_retry_bucket(retry_count) == expected++def test_model_call_fields_report_terminal_model_and_provider_without_a_catalog():assert model_call_fields({"model": "fallback/model",@@@ -398,368 -425,47 +567,91 @@@ def test_model_call_fields_collapse_malassert 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)--- @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--- @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={"hermes.metrics.schema_version": "hermes.metrics.event.v1"},- 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={"hermes.metrics.schema_version": "hermes.metrics.event.v1"},- 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_tool_subscriber_contract_accepts_only_bounded_events():+ terminal = SimpleNamespace(+ kind="scope",+ category="tool",+ category_profile={},+ name="hermes.tool_call",+ scope_category="end",- metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v1"},++ metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v2"},+ data={+ "approval_outcome": "approved",+ "latency_bucket": "250ms_to_500ms",+ "outcome": "success",+ "retry_count_bucket": "0",+ "tool_category": "terminal",+ },+ )+ assert tool_call_dimensions(terminal) == terminal.data++ terminal.data["result"] = "must-not-pass"+ assert tool_call_dimensions(terminal) is None+ terminal.data.pop("result")+ terminal.data["tool_category"] = "private-tool-name"+ assert tool_call_dimensions(terminal) is None+ terminal.data["tool_category"] = "terminal"+ terminal.category_profile["tool_name"] = "must-not-pass"+ assert tool_call_dimensions(terminal) is None++ approval = SimpleNamespace(+ kind="mark",+ category=None,+ category_profile=None,+ name="hermes.tool_approval",+ scope_category=None,- metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v1"},++ metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v2"},+ data={"attribution": "unattributed", "outcome": "denied"},+ )+ assert tool_approval_counter(approval) == (+ "hermes.tool_approval.count",+ approval.data,+ )+ approval.data["command"] = "must-not-pass"+ assert tool_approval_counter(approval) 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')"+ 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",)- with pytest.raises(RuntimeError, match="Unsupported shared-metrics store schema"):- SharedMetricsStore(database_path, tmp_path / "outbox")+ assert store.counter_snapshot() == []++++++- 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(- "hermes.model_call.count",- {"prompt": "must-not-be-persisted"},- "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 40a9a8b2cce,9f77ed9f919..3e8526b3d7b--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@@ -365,38 -279,15 +365,38 @@@ def test_direct_runtime_records_withoutpackage = json.loads(packages[0].read_text(encoding="utf-8"))metrics = {metric["name"]: metric for metric in package["metrics"]}assert set(metrics) == {- "hermes.model_call.count",+ "hermes.model_route.count","hermes.task_run.finished","hermes.task_run.started",+ "hermes.tool_approval.count",+ "hermes.tool_call.count",}- assert metrics["hermes.model_call.count"]["dimensions"] == {+ assert metrics["hermes.model_route.count"]["dimensions"] == {"model": "claude-sonnet","provider": "anthropic",}- assert metrics["hermes.model_call.count"]["value"] == 1+ assert metrics["hermes.model_route.count"]["value"] == 1+ assert metrics["hermes.tool_call.count"] == {+ "name": "hermes.tool_call.count",+ "type": "counter",+ "dimensions": {+ "approval_outcome": "approved",+ "latency_bucket": "250ms_to_500ms",+ "outcome": "success",+ "retry_count_bucket": "0",+ "tool_category": "terminal",+ },+ "value": 1,+ }+ assert metrics["hermes.tool_approval.count"] == {+ "name": "hermes.tool_approval.count",+ "type": "counter",+ "dimensions": {+ "attribution": "tool_call",+ "outcome": "approved",+ },+ "value": 1,+ }assert metrics["hermes.task_run.started"] == {"name": "hermes.task_run.started","type": "counter",@@@ -691,218 -491,8 +691,178 @@@ def test_real_binding_drives_lifecycle_assert canary not in serialized_analytics+def test_real_binding_correlates_plugin_approval_denial_to_tool_metric(+ real_binding_runtime,+ tmp_path,+ monkeypatch,+):+ from hermes_cli.observability.shared_metrics import SharedMetricsStore+ from tools import approval++ assert real_binding_runtime._native is not None+ base = {+ "session_id": "sensitive-session",+ "task_id": "sensitive-task",+ "turn_id": "sensitive-turn",+ "api_request_id": "sensitive-request",+ "platform": "cli",+ }++ def plugin_hook(hook_name: str, **kwargs: Any) -> list[dict[str, str]]:+ if hook_name == "pre_tool_call":+ return [{"action": "approve", "message": "sensitive-rule"}]+ return []++ monkeypatch.setattr(plugins, "invoke_hook", plugin_hook)+ monkeypatch.setattr(approval, "_YOLO_MODE_FROZEN", False)+ monkeypatch.setattr(approval, "is_current_session_yolo_enabled", lambda: False)+ monkeypatch.setattr(approval, "is_approved", lambda *args: False)+ monkeypatch.setattr(approval, "get_current_session_key", lambda: "session-key")+ monkeypatch.setattr(approval, "_is_interactive_cli", lambda: True)+ monkeypatch.setattr(approval, "_is_gateway_approval_context", lambda: False)+ monkeypatch.setattr(approval, "prompt_dangerous_approval", lambda *args, **kwargs: "deny")++ lifecycle.invoke_hook("on_session_start", **base)+ lifecycle.invoke_hook("pre_llm_call", **base, messages=["sensitive-prompt"])+ block_message = plugins.resolve_pre_tool_block(+ "write_file",+ {"path": "sensitive-path"},+ task_id=base["task_id"],+ session_id=base["session_id"],+ turn_id=base["turn_id"],+ api_request_id=base["api_request_id"],+ tool_call_id="sensitive-tool-call",+ )+ assert block_message is not None+ assert "User denied" in block_message++ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ tool_call_id="sensitive-tool-call",+ tool_name="write_file",+ args={"path": "sensitive-path"},+ result={"error": block_message},+ status="blocked",+ duration_ms=12,+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="approval_denied",+ )+ lifecycle.finalize_session(session_id=base["session_id"])++ root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"+ store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")+ snapshot = store.counter_snapshot()+ tool_metrics = [+ counter+ for counter in snapshot+ if counter["metric_name"] == "hermes.tool_call.count"+ ]+ assert len(tool_metrics) == 1+ assert tool_metrics[0]["dimensions"] == {+ "approval_outcome": "denied",+ "latency_bucket": "lt_100ms",+ "outcome": "blocked",+ "retry_count_bucket": "unknown",+ "tool_category": "file",+ }+ approval_metrics = [+ counter+ for counter in snapshot+ if counter["metric_name"] == "hermes.tool_approval.count"+ ]+ assert len(approval_metrics) == 1+ assert approval_metrics[0]["dimensions"] == {+ "attribution": "tool_call",+ "outcome": "denied",+ }+ assert "sensitive" not in json.dumps(snapshot)+++def test_real_binding_aggregates_tool_and_approval_timeouts(+ real_binding_runtime,+ tmp_path,+):+ from hermes_cli.observability.shared_metrics import SharedMetricsStore++ assert real_binding_runtime._native is not None+ base = {+ "session_id": "timeout-sensitive-session",+ "task_id": "timeout-sensitive-task",+ "turn_id": "timeout-sensitive-turn",+ "platform": "cli",+ }++ lifecycle.invoke_hook("on_session_start", **base)+ lifecycle.invoke_hook("pre_llm_call", **base, messages=["timeout-sensitive-prompt"])+ lifecycle.invoke_hook(+ "pre_tool_call",+ **base,+ tool_call_id="timeout-sensitive-tool-call",+ tool_name="terminal",+ args={"command": "timeout-sensitive-command"},+ )+ lifecycle.invoke_hook(+ "post_approval_response",+ **base,+ tool_call_id="timeout-sensitive-tool-call",+ choice="timeout",+ command="timeout-sensitive-command",+ )+ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ tool_call_id="timeout-sensitive-tool-call",+ tool_name="terminal",+ result={"error": "timeout-sensitive-result"},+ status="timeout",+ duration_ms=30_000,+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="provider_timeout",+ )+ lifecycle.finalize_session(session_id=base["session_id"])++ root = tmp_path / "hermes-home" / "telemetry" / "shared_metrics"+ snapshot = SharedMetricsStore(+ root / "metrics.sqlite3",+ root / "outbox",+ ).counter_snapshot()+ [tool_metric] = [+ counter+ for counter in snapshot+ if counter["metric_name"] == "hermes.tool_call.count"+ ]+ assert tool_metric["dimensions"] == {+ "approval_outcome": "timed_out",+ "latency_bucket": "gte_30s",+ "outcome": "timed_out",+ "retry_count_bucket": "unknown",+ "tool_category": "terminal",+ }+ [approval_metric] = [+ counter+ for counter in snapshot+ if counter["metric_name"] == "hermes.tool_approval.count"+ ]+ assert approval_metric["dimensions"] == {+ "attribution": "tool_call",+ "outcome": "timed_out",+ }+ assert "timeout-sensitive" not in json.dumps(snapshot)- def test_direct_runtime_is_disabled_by_default(tmp_path, monkeypatch):- fake = _Relay()- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home"))- monkeypatch.setattr(relay_runtime, "_load_nemo_relay", lambda: fake)- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {})- relay_shared_metrics._reset_for_tests()- relay_runtime._reset_for_tests()- monkeypatch.setattr(plugins, "_plugin_manager", PluginManager())-- assert not plugins.has_hook("pre_api_request")- lifecycle.invoke_hook("on_session_start", session_id="s1", platform="cli")- lifecycle.finalize_session(session_id="s1")-- assert fake.events == []- assert not (tmp_path / "hermes-home" / "telemetry").exists()- relay_shared_metrics._reset_for_tests()- relay_runtime._reset_for_tests()--- def test_tool_intercept_bypass_does_not_create_relay_host(monkeypatch):- relay_runtime._reset_for_tests()- imports = []-- def load_relay():- imports.append("nemo_relay")- raise AssertionError("disabled helper created Relay host")-- monkeypatch.setattr(relay_runtime, "_load_nemo_relay", load_relay)- args = {"command": "true"}-- assert (- relay_runtime.apply_tool_request_intercepts(- session_id="s1",- tool_name="terminal",- args=args,- )- is args- )- assert relay_runtime.get_host(create=False) is None- assert imports == []def test_execution_adapters_do_not_create_relay_host_without_a_consumer(@@@ -2499,76 -1029,7 +1407,7 @@@ def test_same_request_id_is_isolated_beassert all(fields["retry_count_bucket"] == "0" for fields in task_ends)- def test_task_terminal_counts_logical_calls_retries_and_unique_tools(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",- }- tool_ends = [- event for event in direct_runtime.events if event[0] == "tool.call_end"- ]- assert len(tool_ends) == 2- assert all(event[2]["tool_category"] == "terminal" for event in tool_ends)- [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_retry_count_survives_provider_fallback_ordinal_reset(direct_runtime):+def test_reused_tool_call_id_is_counted_for_each_provider_request(direct_runtime):base = {"session_id": "s1","task_id": "t1",@@@ -2651,795 -1086,26 +1490,519 @@@ def test_partial_terminal_context_reusefor event in direct_runtime.eventsif event[0] == "scope.pop" and event[1][1] == "hermes.task_run"]- assert task_end[2]["output"]["retry_count_bucket"] == "2"+ assert task_end[2]["output"]["tool_call_count_bucket"] == "1"-def test_failed_flush_keeps_daily_export_open_for_later_task(- direct_runtime, tmp_path, monkeypatch, caplog+def test_partial_terminal_variants_do_not_double_count_a_completed_call(+ direct_runtime,):- current_time = datetime(2026, 7, 28, 9, tzinfo=timezone.utc)- monkeypatch.setattr(- "hermes_cli.observability.shared_metrics._utc_now",- lambda: current_time,- )- original_flush = direct_runtime.subscribers.flush- flush_attempts = 0-- def fail_first_flush() -> None:- nonlocal flush_attempts- flush_attempts += 1- if flush_attempts == 1:- raise RuntimeError("simulated flush failure")- original_flush()+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "api_request_id": "request-1",+ "platform": "cli",+ "tool_call_id": "tool-1",+ "tool_name": "terminal",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook("pre_tool_call", **base)+ for omitted_field in ("api_request_id", "turn_id"):+ lifecycle.invoke_hook(+ "post_tool_call",+ **{key: value for key, value in base.items() if key != omitted_field},+ result={"output": "private"},+ status="ok",+ )+ 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")++ tool_ends = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert len(tool_ends) == 1+ [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"]["tool_call_count_bucket"] == "1"+++def test_ambiguous_partial_terminal_does_not_create_a_phantom_tool_span(+ direct_runtime,+):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "cli",+ "tool_call_id": "provider-reused-id",+ "tool_name": "terminal",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ for api_request_id in ("request-1", "request-2"):+ lifecycle.invoke_hook(+ "pre_tool_call",+ **base,+ api_request_id=api_request_id,+ )++ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ result={"output": "ambiguous-private-result"},+ status="ok",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="system_aborted",+ )+ lifecycle.finalize_session(session_id="s1")++ tool_ends = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert len(tool_ends) == 2+ assert all(event[2]["outcome"] == "failed" for event in tool_ends)+ [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"]["tool_call_count_bucket"] == "2"+++def test_reused_task_id_starts_a_new_run_for_each_turn(direct_runtime):+ for turn_id in ("turn-1", "turn-2"):+ base = {+ "session_id": "reused-session",+ "task_id": "reused-session",+ "turn_id": turn_id,+ "platform": "api",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ api_request_id=f"request-{turn_id}",+ tool_call_id=f"tool-{turn_id}",+ tool_name="read_file",+ result={"output": "private"},+ status="ok",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=True,+ failed=False,+ interrupted=False,+ turn_exit_reason="text_response(stop)",+ )++ lifecycle.finalize_session(session_id="reused-session")++ 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"+ ]+ tool_ends = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert len(task_starts) == 2+ assert len(task_ends) == 2+ assert len(tool_ends) == 2+ assert all(+ event[2]["output"]["tool_call_count_bucket"] == "1" for event in task_ends+ )+++def test_late_tool_result_does_not_attach_to_reused_task_id(direct_runtime):+ first = {+ "session_id": "reused-session",+ "task_id": "reused-session",+ "turn_id": "turn-1",+ "platform": "api",+ }+ lifecycle.invoke_hook("pre_llm_call", **first)+ lifecycle.invoke_hook(+ "pre_tool_call",+ **first,+ api_request_id="request-1",+ tool_call_id="tool-1",+ tool_name="terminal",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **first,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="timed_out",+ )++ second = {**first, "turn_id": "turn-2"}+ runtime = relay_shared_metrics._get_runtime()+ assert runtime is not None+ assert runtime.start_task({+ "session_id": second["session_id"],+ "task_id": second["task_id"],+ "platform": second["platform"],+ })+ lifecycle.invoke_hook(+ "post_tool_call",+ **first,+ api_request_id="request-1",+ tool_call_id="tool-1",+ tool_name="terminal",+ result={"output": "late-private-result"},+ status="ok",+ )+ lifecycle.invoke_hook("pre_llm_call", **second)+ lifecycle.invoke_hook(+ "post_tool_call",+ **second,+ api_request_id="request-2",+ tool_call_id="tool-2",+ tool_name="read_file",+ result={"output": "current-private-result"},+ status="ok",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **second,+ completed=True,+ failed=False,+ interrupted=False,+ turn_exit_reason="text_response(stop)",+ )+ lifecycle.finalize_session(session_id="reused-session")++ tool_ends = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert len(tool_ends) == 2+ assert [event[2]["outcome"] for event in tool_ends] == [+ "timed_out",+ "success",+ ]+ assert [event[2]["tool_category"] for event in tool_ends] == [+ "terminal",+ "file",+ ]+ task_ends = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"+ ]+ assert [+ event[2]["output"]["tool_call_count_bucket"] for event in task_ends+ ] == ["1", "1"]+++def test_pending_tool_is_closed_and_counted_when_task_is_interrupted(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "cli",+ }++ lifecycle.invoke_hook("on_session_start", **base)+ lifecycle.invoke_hook(+ "pre_tool_call",+ **base,+ tool_call_id="tool-1",+ tool_name="terminal",+ args={"command": "must-not-pass"},+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=False,+ interrupted=True,+ turn_exit_reason="interrupted_by_user",+ )+ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ tool_call_id="tool-1",+ tool_name="terminal",+ result={"output": "late-result-must-not-pass"},+ status="ok",+ )+ lifecycle.finalize_session(session_id="s1")++ [tool_end] = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert tool_end[2] == {+ "approval_outcome": "not_required",+ "latency_bucket": tool_end[2]["latency_bucket"],+ "outcome": "cancelled",+ "retry_count_bucket": "unknown",+ "tool_category": "terminal",+ }+ [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"]["tool_call_count_bucket"] == "1"+ task_starts = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.push" and event[1] == "hermes.task_run"+ ]+ assert len(task_starts) == 1+++def test_pending_tool_uses_the_outer_task_timeout_outcome(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "api",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook(+ "pre_tool_call",+ **base,+ tool_call_id="tool-1",+ tool_name="web_search",+ )++ relay_shared_metrics.finish_task_run(+ session_id="s1",+ task_id="t1",+ platform="api",+ error=TimeoutError("private timeout detail"),+ )+ lifecycle.finalize_session(session_id="s1")++ [tool_end] = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert tool_end[2]["outcome"] == "timed_out"+ [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"]["outcome"] == "timed_out"+ assert task_end[2]["output"]["tool_call_count_bucket"] == "1"+ assert "private timeout detail" not in repr(direct_runtime.events)+++def test_approval_without_tool_context_is_counted_as_unattributed(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "cli",+ }++ lifecycle.invoke_hook("on_session_start", **base)+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook(+ "post_approval_response",+ turn_id="turn-1",+ choice="deny",+ command="must-not-pass",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="approval_denied",+ )+ lifecycle.finalize_session(session_id="s1")++ [approval] = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.event" and event[1] == "hermes.tool_approval"+ ]+ assert approval[2]["data"] == {+ "attribution": "unattributed",+ "outcome": "denied",+ }+++def test_approval_with_unmatched_tool_id_is_counted_as_unattributed(direct_runtime):+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "cli",+ }++ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook(+ "post_approval_response",+ **base,+ tool_call_id="spoofed-tool-call",+ choice="deny",+ command="must-not-pass",+ )+ lifecycle.invoke_hook(+ "on_session_end",+ **base,+ completed=False,+ failed=True,+ interrupted=False,+ turn_exit_reason="approval_denied",+ )+ lifecycle.finalize_session(session_id="s1")++ [approval] = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.event" and event[1] == "hermes.tool_approval"+ ]+ assert approval[2]["data"] == {+ "attribution": "unattributed",+ "outcome": "denied",+ }+++def test_tool_category_comes_from_runtime_registry_metadata(+ direct_runtime,+ monkeypatch,+):+ import model_tools++ monkeypatch.setattr(+ model_tools,+ "get_toolset_for_tool",+ lambda name: "terminal" if name == "runtime_only_tool" else None,+ )+ base = {+ "session_id": "s1",+ "task_id": "t1",+ "turn_id": "turn-1",+ "platform": "cli",+ }+ lifecycle.invoke_hook("pre_llm_call", **base)+ lifecycle.invoke_hook(+ "post_tool_call",+ **base,+ tool_call_id="tool-1",+ tool_name="runtime_only_tool",+ result={"output": "private"},+ status="ok",+ )+ 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")++ [tool_end] = [+ event for event in direct_runtime.events if event[0] == "tool.call_end"+ ]+ assert tool_end[2]["tool_category"] == "terminal"--- 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(+ "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+):+ current_time = datetime(2026, 7, 28, 9, tzinfo=timezone.utc)+ monkeypatch.setattr(+ "hermes_cli.observability.shared_metrics._utc_now",+ lambda: current_time,+ )+ original_flush = direct_runtime.subscribers.flush+ flush_attempts = 0++ def fail_first_flush() -> None:+ nonlocal flush_attempts+ flush_attempts += 1+ if flush_attempts == 1:+ raise RuntimeError("simulated flush failure")+ original_flush()direct_runtime.subscribers.flush = fail_first_flush@@@ -3480,187 -1146,10 +2043,3 @@@assert metrics["hermes.task_run.finished"]["value"] == 2assert flush_attempts == 2assert "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._sessionsdiff --cc tests/run_agent/test_run_agent.pyindex 344fbae180f,01225f241ec..b78af945716--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@@ -3003,197 -1757,12 +1801,11 @@@ class TestConcurrentToolExecutionassert messages[1]["tool_call_id"] == "c2"assert all("Python interpreter is shutting down" in m["content"] for m in messages)- def test_concurrent_timeout_returns_finished_tools_without_hanging(self, agent, monkeypatch):- """A wedged worker must not freeze the whole concurrent tool batch."""- import threading- import time as _time-- monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.1")- blocker = threading.Event()- tc1 = _mock_tool_call(name="web_search", arguments='{"q": "fast"}', call_id="c1")- tc2 = _mock_tool_call(name="web_search", arguments='{"q": "slow"}', call_id="c2")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc1, tc2])- messages = []- flushed = []-- def fake_handle(name, args, task_id, **kwargs):- if args.get("q") == "slow":- blocker.wait(5)- return "late"- return "fast-result"-- def record_flush(flush_messages, conversation_history=None):- flushed.append([m.copy() for m in flush_messages if m.get("role") == "tool"])-- agent._flush_messages_to_session_db = MagicMock(side_effect=record_flush)- terminal_hook = MagicMock()-- start = _time.monotonic()- try:- with (- patch("run_agent.handle_function_call", side_effect=fake_handle),- patch(- "model_tools._emit_post_tool_call_hook",- terminal_hook,- ),- ):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")- finally:- blocker.set()-- assert _time.monotonic() - start < 1.0- assert len(messages) == 2- assert messages[0]["tool_call_id"] == "c1"- assert "fast-result" in messages[0]["content"]- assert messages[1]["tool_call_id"] == "c2"- assert "timed out after" in messages[1]["content"]- assert messages[1]["effect_disposition"] == "unknown"- assert [batch[-1]["tool_call_id"] for batch in flushed] == ["c1", "c2"]- assert "fast-result" in flushed[0][-1]["content"]- assert "timed out after" in flushed[1][-1]["content"]- [timeout_hook] = [- call- for call in terminal_hook.call_args_list- if call.kwargs["tool_call_id"] == "c2"- ]- assert timeout_hook.kwargs["status"] == "timeout"- assert timeout_hook.kwargs["duration_ms"] == 100-- def test_concurrent_timeout_prefers_late_real_result_over_timeout_message(self, agent, monkeypatch):- """A worker that finishes in the window between the deadline snapshot- and the result loop must keep its real result, not be overwritten with- a fabricated 'timed out' message (late-completion race)."""- import concurrent.futures as _cf-- monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.1")- tc1 = _mock_tool_call(name="web_search", arguments='{"q": "a"}', call_id="c1")- tc2 = _mock_tool_call(name="web_search", arguments='{"q": "b"}', call_id="c2")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc1, tc2])- messages = []-- # Both tools return instantly, so results[*] are populated almost- # immediately. We still force the deadline path by making the FIRST- # wait() report everything as not-done (after crossing the deadline),- # so the loop snapshots both as timed-out even though the workers have- # in fact already written their results. The fix must surface the real- # results, not the timeout message.- real_wait = _cf.wait- calls = {"n": 0}-- def fake_wait(fs, timeout=None):- calls["n"] += 1- if calls["n"] == 1:- import time as _t- _t.sleep(0.15) # ensure monotonic() >= deadline- return set(), set(fs)- return real_wait(fs, timeout=timeout)-- with patch("agent.tool_executor.concurrent.futures.wait", side_effect=fake_wait), \- patch("run_agent.handle_function_call", side_effect=lambda name, args, task_id, **k: f"real-{args.get('q')}"):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")-- assert len(messages) == 2- joined = " ".join(m["content"] for m in messages)- assert "timed out after" not in joined, "late-completing real results must not be discarded"- assert "real-a" in messages[0]["content"]- assert "real-b" in messages[1]["content"]-- def test_concurrent_serializes_post_rewrite_authorization(self, agent, monkeypatch):- tc1 = _mock_tool_call(- name="web_search", arguments='{"q": "a"}', call_id="c1"- )- tc2 = _mock_tool_call(- name="web_search", arguments='{"q": "b"}', call_id="c2"- )- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc1, tc2])- messages = []- state_lock = threading.Lock()- active = 0- max_active = 0-- def authorize(*_args, **_kwargs):- nonlocal active, max_active- with state_lock:- active += 1- max_active = max(max_active, active)- try:- time.sleep(0.05)- return None- finally:- with state_lock:- active -= 1-- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- authorize,- )-- with patch(- "run_agent.handle_function_call",- side_effect=lambda _name, args, _task_id, **_kwargs: f"result-{args['q']}",- ):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")-- assert max_active == 1- assert [message["tool_call_id"] for message in messages] == ["c1", "c2"]-- def test_concurrent_timeout_excludes_authorization_wait(self, agent, monkeypatch):- monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.05")- tool_call = _mock_tool_call(- name="web_search", arguments='{"q": "approved"}', call_id="c1"- )- mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])- messages = []-- def authorize(*_args, **_kwargs):- time.sleep(0.15)- return None-- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- authorize,- )-- with patch("run_agent.handle_function_call", return_value="approved-result"):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")-- assert len(messages) == 1- assert "approved-result" in messages[0]["content"]- assert "timed out after" not in messages[0]["content"]-- def test_concurrent_interrupt_before_start(self, agent):- """If interrupt is requested before concurrent execution, all tools are skipped."""- tc1 = _mock_tool_call(name="web_search", arguments='{}', call_id="c1")- tc2 = _mock_tool_call(name="read_file", arguments='{}', call_id="c2")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc1, tc2])- messages = []-- with patch("run_agent._set_interrupt"):- agent.interrupt()- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")- assert len(messages) == 2- assert "cancelled" in messages[0]["content"].lower() or "skipped" in messages[0]["content"].lower()- assert "cancelled" in messages[1]["content"].lower() or "skipped" in messages[1]["content"].lower()- def test_concurrent_truncates_large_results(self, agent, tmp_path, monkeypatch):- """Concurrent path should save oversized results to file."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- (tmp_path / ".hermes").mkdir()- tc1 = _mock_tool_call(name="web_search", arguments='{}', call_id="c1")- tc2 = _mock_tool_call(name="web_search", arguments='{}', call_id="c2")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc1, tc2])- messages = []- big_result = "x" * 150_000- with patch("run_agent.handle_function_call", return_value=big_result):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")- assert len(messages) == 2- for m in messages:- assert len(m["content"]) < 150_000- assert ("Truncated" in m["content"] or "<persisted-output>" in m["content"])-def test_invoke_tool_dispatches_to_handle_function_call(self, agent):"""_invoke_tool should route regular tools through handle_function_call."""with patch("run_agent.handle_function_call", return_value="result") as mock_hfc:@@@ -3430,194 -1911,10 +1954,58 @@@assert messages[0]["role"] == "tool"assert json.loads(messages[0]["content"]) == {"error": "Blocked by policy"}- def test_sequential_blocked_tool_emits_terminal_post_tool_hook(self, agent, monkeypatch):- """Blocked pre_tool_call decisions still terminate observer tool spans."""- tool_call = _mock_tool_call(name="write_file",- arguments='{"path":"test.txt","content":"hello"}',- call_id="c1")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])- messages = []- hook_calls = []-- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- lambda *args, **kwargs: "Blocked by policy",- )- monkeypatch.setattr(- "hermes_cli.lifecycle.invoke_hook",- lambda hook_name, **kwargs: hook_calls.append((hook_name, kwargs)) or [],- )- monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)- with patch("run_agent.handle_function_call", side_effect=AssertionError("should not run")):- agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")- post_call = next(call for call in hook_calls if call[0] == "post_tool_call")- assert post_call[1]["tool_name"] == "write_file"- assert post_call[1]["tool_call_id"] == "c1"- assert post_call[1]["status"] == "blocked"- assert post_call[1]["error_type"] == "plugin_block"- assert post_call[1]["error_message"] == "Blocked by policy"- def test_sequential_agent_level_tool_emits_terminal_post_tool_hook(self, agent, monkeypatch):- """Sequential built-in tool paths should also close observer tool spans."""- tool_call = _mock_tool_call(name="todo", arguments='{"todos":[]}', call_id="todo-1")++ @pytest.mark.parametrize("concurrent", [False, True])++ def test_tool_execution_middleware_replacement_emits_one_terminal_hook(++ self,++ agent,++ monkeypatch,++ concurrent,++ ):++ """A middleware replacement owns the result but not lifecycle closure."""++ tool_call = _mock_tool_call(++ name="terminal",++ arguments='{"command":"must-not-run"}',++ call_id="terminal-1",++ )+ mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])+ messages = []+ hook_calls = []+- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- lambda *args, **kwargs: None,- )- monkeypatch.setattr(- "hermes_cli.lifecycle.invoke_hook",- lambda hook_name, **kwargs: hook_calls.append((hook_name, kwargs)) or [],- )- monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)-- with patch("tools.todo_tool.todo_tool", return_value='{"ok":true}') as mock_todo:- agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")-- mock_todo.assert_called_once()- post_call = next(call for call in hook_calls if call[0] == "post_tool_call")- assert post_call[1]["tool_name"] == "todo"- assert post_call[1]["tool_call_id"] == "todo-1"- assert post_call[1]["result"] == '{"ok":true}'- assert post_call[1]["status"] == "ok"-- def test_sequential_agent_level_tool_execution_middleware_wraps_inline_dispatch(self, agent, monkeypatch):- """Sequential built-in tool paths should expose the adaptive execution boundary."""- tool_call = _mock_tool_call(name="todo", arguments='{"todos":[]}', call_id="todo-1")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])- messages = []- hook_calls = []- seen = {}-- def request_middleware(**kwargs):- return {- "args": {**kwargs["args"], "request_rewritten": True},- "source": "request-test",- }-- def execution_middleware(**kwargs):- seen["middleware_args"] = kwargs["args"]- return kwargs["next_call"]({**kwargs["args"], "merge": True})-- manager = SimpleNamespace(_middleware={- "tool_request": [request_middleware],- "tool_execution": [execution_middleware],- })- monkeypatch.setattr("hermes_cli.plugins.get_plugin_manager", lambda: manager)- monkeypatch.setattr(- "hermes_cli.plugins.invoke_middleware",- lambda kind, **kwargs: [request_middleware(**kwargs)] if kind == "tool_request" else [],- )- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- lambda *args, **kwargs: None,- )- monkeypatch.setattr(- "hermes_cli.lifecycle.invoke_hook",- lambda hook_name, **kwargs: hook_calls.append((hook_name, kwargs)) or [],- )- monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)-- with patch("tools.todo_tool.todo_tool", return_value='{"ok":true}') as mock_todo:- agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")-- assert seen["middleware_args"] == {"todos": [], "request_rewritten": True}- mock_todo.assert_called_once_with(todos=[], merge=True, store=agent._todo_store)- post_call = next(call for call in hook_calls if call[0] == "post_tool_call")- assert post_call[1]["tool_name"] == "todo"- assert post_call[1]["args"] == {"todos": [], "request_rewritten": True, "merge": True}- assert post_call[1]["middleware_trace"] == [{"source": "request-test"}]-- @pytest.mark.parametrize("concurrent", [False, True])- def test_tool_execution_middleware_replacement_emits_one_terminal_hook(- self,- agent,- monkeypatch,- concurrent,- ):- """A middleware replacement owns the result but not lifecycle closure."""- tool_call = _mock_tool_call(- name="terminal",- arguments='{"command":"must-not-run"}',- call_id="terminal-1",- )- mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])- messages = []- hook_calls = []-- def execution_middleware(**kwargs):- return '{"intercepted":true}'-- manager = SimpleNamespace(_middleware={- "tool_request": [],- "tool_execution": [execution_middleware],- })- monkeypatch.setattr("hermes_cli.plugins.get_plugin_manager", lambda: manager)++ def execution_middleware(**kwargs):++ return '{"intercepted":true}'++++ manager = SimpleNamespace(_middleware={++ "tool_request": [],++ "tool_execution": [execution_middleware],++ })++ monkeypatch.setattr("hermes_cli.plugins.get_plugin_manager", lambda: manager)+ monkeypatch.setattr(+ "hermes_cli.lifecycle.invoke_hook",+ lambda hook_name, **kwargs: hook_calls.append((hook_name, kwargs)) or [],+ )+ monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)++ with patch(+ "run_agent.handle_function_call",+ side_effect=AssertionError("middleware replacement must not dispatch"),+ ):+ if concurrent:+ agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")+ else:+ agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")++ post_calls = [+ payload for name, payload in hook_calls if name == "post_tool_call"+ ]+ assert len(post_calls) == 1+ assert post_calls[0]["tool_name"] == "terminal"+ assert post_calls[0]["tool_call_id"] == "terminal-1"+ assert post_calls[0]["status"] == "ok"+ assert post_calls[0]["result"] == '{"intercepted":true}'- def test_concurrent_agent_level_tool_preserves_request_middleware_trace(self, agent, monkeypatch):- tool_call = _mock_tool_call(name="todo", arguments='{"todos":[]}', call_id="todo-1")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tool_call])- messages = []- hook_calls = []-- def request_middleware(**kwargs):- return {- "args": {**kwargs["args"], "request_rewritten": True},- "source": "request-test",- }-- manager = SimpleNamespace(_middleware={"tool_request": [request_middleware], "tool_execution": []})- monkeypatch.setattr("hermes_cli.plugins.get_plugin_manager", lambda: manager)- monkeypatch.setattr(- "hermes_cli.plugins.invoke_middleware",- lambda kind, **kwargs: [request_middleware(**kwargs)] if kind == "tool_request" else [],- )- monkeypatch.setattr(- "hermes_cli.plugins.resolve_pre_tool_block",- lambda *args, **kwargs: None,- )- monkeypatch.setattr(- "hermes_cli.lifecycle.invoke_hook",- lambda hook_name, **kwargs: hook_calls.append((hook_name, kwargs)) or [],- )- monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)-- with patch("tools.todo_tool.todo_tool", return_value='{"ok":true}'):- agent._execute_tool_calls_concurrent(mock_msg, messages, "task-1")-- post_call = next(call for call in hook_calls if call[0] == "post_tool_call")- assert post_call[1]["tool_name"] == "todo"- assert post_call[1]["args"] == {"todos": [], "request_rewritten": True}- assert post_call[1]["middleware_trace"] == [{"source": "request-test"}]-def test_agent_runtime_post_hook_ownership_predicate_covers_agent_tools(self, agent):"""Sequential and concurrent agent-level paths share post-hook ownership."""from agent.agent_runtime_helpers import agent_runtime_owns_post_tool_hook@@@ -9215,34 -5712,5 +5803,3 @@@ class TestMemoryContextSanitizationassert "memory-context" not in result.lower()assert "stale observation" not in resultassert "how is the honcho working" in result--- class TestMemoryProviderTurnStart:- """run_conversation() must call memory_manager.on_turn_start() before prefetch_all().-- Without this call, providers like Honcho never update _turn_count, so cadence- checks (contextCadence, dialecticCadence) are always satisfied — every turn- fires both context refresh and dialectic, ignoring the configured cadence.- """--- def test_on_turn_start_called_before_prefetch(self):- """Source-level check: on_turn_start appears before prefetch_all in the prologue."""- import inspect- from agent.turn_context import build_turn_context as _btc- src = inspect.getsource(_btc)- # Find the actual method calls, not comments- idx_turn_start = src.index(".on_turn_start(")- idx_prefetch = src.index(".prefetch_all(")- assert idx_turn_start < idx_prefetch, (- "on_turn_start() must be called before prefetch_all() in the turn prologue "- "so that memory providers have the correct turn count for cadence checks"- )--- def test_on_turn_start_uses_user_turn_count(self):- """Source-level check: on_turn_start receives the user_turn_count."""- import inspect- from agent.turn_context import build_turn_context as _btc- src = inspect.getsource(_btc)- # The extracted body uses ``agent.X`` rather than ``self.X``;- # assert the extracted-form spelling directly.- assert "on_turn_start(agent._user_turn_count" in srcdiff --cc tests/tools/test_approval.pyindex f56c4b4bd7c,3b6b1f797e2..fba860bd707--- a/tests/tools/test_approval.py+++ b/tests/tools/test_approval.py@@@ -2398,73 -1245,7 +1245,72 @@@ class TestApprovalTimeoutIsNotConsentassert "NOT consented" in r["message"]assert "rephrase" in r["message"].lower()+ def test_timeout_emits_post_hook_with_timeout_outcome(self, monkeypatch):+ """Plugins must be able to distinguish timeout from explicit deny.++ This is what an audit / notification plugin needs to alert+ operators on 'agent asked, user never replied' incidents like #24912.+ """+ from tools import approval as mod+ self._force_short_timeout(monkeypatch, seconds=1)+ mod.register_gateway_notify(self.SESSION_KEY, lambda data: None)++ hook_calls = []+ original_fire = mod._fire_approval_hook++ def _capture(event_name, **kwargs):+ hook_calls.append((event_name, kwargs))+ return original_fire(event_name, **kwargs)++ monkeypatch.setattr(mod, "_fire_approval_hook", _capture)++ mod.check_all_command_guards("rm -rf .git", "local")++ # post_approval_response must be in the hook log with choice=timeout+ posts = [c for c in hook_calls if c[0] == "post_approval_response"]+ assert posts, "post_approval_response hook did not fire"+ last_post = posts[-1][1]+ assert last_post.get("choice") == "timeout", (+ f"hook choice should be 'timeout' on no-response, got {last_post.get('choice')!r}"+ )++ def test_notify_failure_emits_post_hook_and_cleans_up(self, monkeypatch):+ """A failed notification still terminates the approval lifecycle."""+ from tools import approval as mod++ hook_calls = []++ def _capture(event_name, **kwargs):+ hook_calls.append((event_name, kwargs))++ monkeypatch.setattr(mod, "_fire_approval_hook", _capture)++ def _fail_notify(_data):+ raise RuntimeError("private gateway failure")++ decision = mod._await_gateway_decision(+ self.SESSION_KEY,+ _fail_notify,+ {+ "command": "redacted-command",+ "description": "redacted-description",+ "pattern_key": "dangerous",+ "pattern_keys": ["dangerous"],+ },+ )++ assert decision == {+ "resolved": False,+ "choice": None,+ "notify_failed": True,+ }+ assert self.SESSION_KEY not in mod._gateway_queues+ assert [name for name, _ in hook_calls] == [+ "pre_approval_request",+ "post_approval_response",+ ]+ assert hook_calls[-1][1]["choice"] == "notify_failed"-class TestTirithImportErrorFailOpenPolicy:"""Regression guard for #20733.