The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): harness-accuracy shared metrics for the agent loop
teknium18d8836ddb13f
diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex 53efc4e1c21..b89a9bda395 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -1072,6 +1072,9 @@ def _commit_tool_result(pre-persist content for UI previews) or ``None`` when the flush failed (stop the batch)."""function_name, function_args, tool_call_id, effective_task_id = ref.name, ref.args, ref.call_id, ref.task_id+ from hermes_cli.observability.shared_metrics_harness import observe_tool_outcome++ observe_tool_outcome(agent, function_name, is_error)if observed:if not blocked:function_result = agent._append_guardrail_observation(diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.pyindex b68a9ff5835..50601f87dd0 100644--- a/agent/tool_guardrails.py+++ b/agent/tool_guardrails.py@@ -154,10 +154,12 @@ class ToolCallGuardrailConfig:@dataclass(frozen=True)class IdenticalCallObservation:- """``notice`` is appended after the result, ``stub`` replaces a byte-identical duplicate result."""+ """``notice`` is appended after the result, ``stub`` replaces a byte-identical duplicate result;+ ``kind`` names the detector behind the notice (``identical_call_streak`` / ``identical_cycle``)."""notice: str | None = Nonestub: str | None = None+ kind: str | None = None@dataclass(frozen=True)@@ -458,9 +460,9 @@ class ToolCallGuardrailController:self._identical_streak_first_call_id = tool_call_id or ""count = self._identical_streak_count- notice = None+ notice = kind = Noneif not is_stall_guard_repeatable(tool_name) and count >= STALL_GUARD_IDENTICAL_CALL_THRESHOLD:- notice = _IDENTICAL_CALL_NOTICE.format(ordinal=_ordinal(count), tool_name=tool_name)+ notice, kind = _IDENTICAL_CALL_NOTICE.format(ordinal=_ordinal(count), tool_name=tool_name), "identical_call_streak"# The no-progress BLOCK in before_call only covers idempotent_tools; this streak# is tool-agnostic, so with hard stops on, halt at the same threshold (a model# replaying a successful `terminal` call otherwise runs to the budget).@@ -477,14 +479,14 @@ class ToolCallGuardrailController:cycle = self._detect_identical_cycle()if cycle is not None:period, laps = cycle- notice = _IDENTICAL_CYCLE_NOTICE.format(count=laps, period=period, tool_name=tool_name)+ notice, kind = _IDENTICAL_CYCLE_NOTICE.format(count=laps, period=period, tool_name=tool_name), "identical_cycle"if self.config.hard_stop_enabled and laps >= self.config.no_progress_block_after and self._halt_decision is None:self._decide("halt", "identical_cycle_halt", tool_name, laps, signature, period=period)stub = Noneif is_plain_str and count >= 2 and not failed and len(result) >= IDENTICAL_RESULT_STUB_MIN_CHARS:stub = self._build_result_reference_stub(tool_name, args)- return IdenticalCallObservation(notice=notice, stub=stub)+ return IdenticalCallObservation(notice=notice, stub=stub, kind=kind)def _detect_identical_cycle(self) -> tuple[int, int] | None:"""Detect a repeating identical-call cycle ending at the latest observed call.diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 14dd74be320..635e7fac658 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -573,6 +573,7 @@ _PER_TURN_RESET_STATE: Tuple[Tuple[str, Any], ...] = (("_last_content_with_tools", None), ("_last_content_tools_all_housekeeping", False),("_mute_post_response", False), ("_unicode_sanitization_passes", 0),("_tool_guardrail_halt_decision", None),+ ("_harness_metrics_turn", None),("_iteration_budget_warning_injected", False),("_run_budget_wrapup_injected", False), ("_verification_stop_nudges", 0),("_pre_verify_nudges", 0),diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 9c44467439d..555285b4b66 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -578,6 +578,9 @@ def finalize_turn(_rollback_interrupted_preflight_display(agent, interrupted)+ from hermes_cli.observability.shared_metrics_harness import finish_turn+ finish_turn(agent, _turn_exit_reason, final_response, interrupted=interrupted, failed=failed)+_cleanup_errors: List[str] = []# The model has answered (or the loop gave up): a title upgrade held back because it shares a# self-hosted endpoint with the main request (#117296) may go out now.diff --git a/agent/turn_response_check.py b/agent/turn_response_check.pyindex e762c488cdd..c79fe2b4680 100644--- a/agent/turn_response_check.py+++ b/agent/turn_response_check.py@@ -149,6 +149,8 @@ def check_api_response(agent._turn_received_provider_response = Truefinish_reason = _derive_finish_reason(agent, response, messages)+ from hermes_cli.observability.shared_metrics_harness import record_reply_finish+ record_reply_finish(agent, response, finish_reason)# HTTP-200 refusals are deterministic: one fallback try, else return the refusal.if finish_reason == "content_filter":diff --git a/agent/turn_response_intake.py b/agent/turn_response_intake.pyindex 35f63802333..eebd9d12deb 100644--- a/agent/turn_response_intake.py+++ b/agent/turn_response_intake.py@@ -145,6 +145,8 @@ def normalize_model_response(api_call_count=api_call_count, api_duration=api_duration, api_start_time=api_start_time,api_request_id=api_request_id, effective_task_id=effective_task_id, turn_id=turn_id,)+ from hermes_cli.observability.shared_metrics_harness import record_reply_content+ record_reply_content(agent, response, assistant_message)content = assistant_message.contentif content and not agent.quiet_mode:diff --git a/agent/turn_tool_round.py b/agent/turn_tool_round.pyindex 10211a8895d..0a98b93a89b 100644--- a/agent/turn_tool_round.py+++ b/agent/turn_tool_round.py@@ -152,6 +152,9 @@ def run_tool_round(agent.stream_delta_callback(None)agent._execute_tool_calls(assistant_message, messages, effective_task_id, api_call_count)+ from hermes_cli.observability.shared_metrics_harness import finish_tool_round++ finish_tool_round(agent)if getattr(agent, "_incremental_persistence_failed", False):# Tool result could not be made canonical: never send the in-memory result todiff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex ebe32e7fd00..f9f9195c19c 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -195,6 +195,21 @@},{"$ref": "#/$defs/process_exit_counter"+ },+ {+ "$ref": "#/$defs/file_edit_counter"+ },+ {+ "$ref": "#/$defs/loop_guard_counter"+ },+ {+ "$ref": "#/$defs/tool_recovery_counter"+ },+ {+ "$ref": "#/$defs/terminal_outcome_counter"+ },+ {+ "$ref": "#/$defs/model_reply_issue_counter"}]}@@ -2477,6 +2492,326 @@"minimum": 1}}+ },+ "file_edit_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.file_edit.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "match_strategy",+ "mode",+ "outcome",+ "tool"+ ],+ "properties": {+ "match_strategy": {+ "enum": [+ "block_anchor",+ "context_aware",+ "escape_normalized",+ "exact",+ "indentation_flexible",+ "line_trimmed",+ "none",+ "trimmed_boundary",+ "unicode_normalized",+ "whitespace_normalized"+ ]+ },+ "mode": {+ "enum": [+ "replace",+ "v4a",+ "whole_file"+ ]+ },+ "outcome": {+ "enum": [+ "already_applied",+ "ambiguous",+ "applied",+ "failed",+ "no_match"+ ]+ },+ "tool": {+ "enum": [+ "patch",+ "write_file"+ ]+ }+ },+ "description": "One per patch/write_file tool call; match_strategy is the fuzzy-match strategy that landed an applied patch (the loosest one for a multi-hunk V4A patch), none otherwise."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "loop_guard_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.loop_guard.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "detector",+ "model",+ "provider",+ "signal"+ ],+ "properties": {+ "detector": {+ "enum": [+ "exact_failure",+ "idempotent_no_progress",+ "identical_call_streak",+ "identical_cycle",+ "iteration_budget",+ "same_tool_failure",+ "subagent_cap",+ "web_search_cap"+ ]+ },+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "signal": {+ "enum": [+ "iteration_cap",+ "loop_detected",+ "repeated_tool_call"+ ]+ }+ },+ "description": "At most once per turn per (signal, detector): repeated_tool_call = a warning the call still ran with, loop_detected = the harness blocked or halted, iteration_cap = the turn spent its iteration budget."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "tool_recovery_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_recovery.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "model",+ "next_outcome",+ "next_tool",+ "provider",+ "tool"+ ],+ "properties": {+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "next_outcome": {+ "enum": [+ "error",+ "gave_up",+ "no_tool_call",+ "success"+ ]+ },+ "next_tool": {+ "enum": [+ "different",+ "none",+ "same"+ ]+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "tool": {+ "$ref": "#/$defs/vocabulary_identifier"+ }+ },+ "description": "One per failed tool call: what the model's next tool call did (the next call to the same tool, else its first call), or no_tool_call / gave_up when the turn ended without one."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "terminal_outcome_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.terminal.outcome.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "backend",+ "command_kind",+ "outcome"+ ],+ "properties": {+ "backend": {+ "enum": [+ "daytona",+ "docker",+ "local",+ "managed_modal",+ "modal",+ "other",+ "singularity",+ "ssh",+ "vercel_sandbox"+ ]+ },+ "command_kind": {+ "enum": [+ "build",+ "container",+ "file_ops",+ "git",+ "network",+ "node",+ "other",+ "package_manager",+ "python",+ "shell",+ "shell_builtin",+ "test_runner"+ ]+ },+ "outcome": {+ "enum": [+ "killed",+ "nonzero",+ "ok",+ "timeout"+ ]+ }+ },+ "description": "One per foreground terminal command that reached an exit status; command_kind comes from a fixed table of first program words, never the command text."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "model_reply_issue_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.model_reply_issue.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "issue",+ "model",+ "provider"+ ],+ "properties": {+ "issue": {+ "enum": [+ "empty",+ "none",+ "reasoning_only",+ "refusal",+ "truncated_length"+ ]+ },+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ }+ },+ "description": "One per primary model response; issue=none when the response is usable, so issue rates have a denominator."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }}}}diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 37f296ace60..6c87cb8b90b 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -334,6 +334,45 @@ def version_age_bucket(age_ms: Any) -> str:return "unknown" if value is None else _bucket(value, _VERSION_AGE_THRESHOLDS, "gte_90d")# ---- end v4 reliability ----+# ---- v5 harness ----+FILE_EDIT_MARK = "hermes.file_edit"+LOOP_GUARD_MARK = "hermes.loop_guard"+TOOL_RECOVERY_MARK = "hermes.tool_recovery"+TERMINAL_OUTCOME_MARK = "hermes.terminal.outcome"+MODEL_REPLY_ISSUE_MARK = "hermes.model_reply_issue"+FILE_EDIT_METRIC = "hermes.file_edit.count"+LOOP_GUARD_METRIC = "hermes.loop_guard.count"+TOOL_RECOVERY_METRIC = "hermes.tool_recovery.count"+TERMINAL_OUTCOME_METRIC = "hermes.terminal.outcome.count"+MODEL_REPLY_ISSUE_METRIC = "hermes.model_reply_issue.count"+FILE_EDIT_TOOLS = frozenset({"patch", "write_file"})+FILE_EDIT_MODES = frozenset({"replace", "v4a", "whole_file"})+FILE_EDIT_OUTCOMES = frozenset({"already_applied", "ambiguous", "applied", "failed", "no_match"})+++def _fuzzy_match_strategies() -> frozenset[str]:+ # The patch tool's own strategy chain, so a new strategy is a new bucket, never "none".+ from tools.fuzzy_match import STRATEGIES++ return frozenset(name for name, _fn in STRATEGIES)+++FILE_EDIT_STRATEGIES = _fuzzy_match_strategies() | {"none"}+LOOP_GUARD_SIGNALS = frozenset({"iteration_cap", "loop_detected", "repeated_tool_call"})+LOOP_GUARD_DETECTORS = frozenset({+ "exact_failure", "idempotent_no_progress", "identical_call_streak", "identical_cycle", "iteration_budget",+ "same_tool_failure", "subagent_cap", "web_search_cap",+})+TOOL_RECOVERY_OUTCOMES = frozenset({"error", "gave_up", "no_tool_call", "success"})+TOOL_RECOVERY_NEXT_TOOLS = frozenset({"different", "none", "same"})+TERMINAL_COMMAND_KINDS = frozenset({+ "build", "container", "file_ops", "git", "network", "node", "other", "package_manager", "python",+ "shell", "shell_builtin", "test_runner",+})+TERMINAL_OUTCOMES = frozenset({"killed", "nonzero", "ok", "timeout"})+MODEL_REPLY_ISSUES = frozenset({"empty", "none", "reasoning_only", "refusal", "truncated_length"})+# ---- end v5 harness ----+_ARCHITECTURE_ALIASES = {"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64","aarch64": "arm64", "arm64": "arm64",@@ -526,6 +565,20 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"crash_class": CRASH_CLASSES, "exit_kind": PROCESS_EXIT_KINDS, "process_kind": PROCESS_KINDS,},# ---- end v4 reliability ----+ # ---- v5 harness ----+ FILE_EDIT_METRIC: {+ "match_strategy": FILE_EDIT_STRATEGIES, "mode": FILE_EDIT_MODES, "outcome": FILE_EDIT_OUTCOMES,+ "tool": FILE_EDIT_TOOLS,+ },+ LOOP_GUARD_METRIC: {"detector": LOOP_GUARD_DETECTORS, "signal": LOOP_GUARD_SIGNALS},+ TOOL_RECOVERY_METRIC: {+ "next_outcome": TOOL_RECOVERY_OUTCOMES, "next_tool": TOOL_RECOVERY_NEXT_TOOLS, "tool": TOOL_NAMES,+ },+ TERMINAL_OUTCOME_METRIC: {+ "backend": TERMINAL_BACKENDS, "command_kind": TERMINAL_COMMAND_KINDS, "outcome": TERMINAL_OUTCOMES,+ },+ MODEL_REPLY_ISSUE_METRIC: {"issue": MODEL_REPLY_ISSUES},+ # ---- end v5 harness ----}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,@@ -543,6 +596,11 @@ _IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {MODEL_FRICTION_METRIC: _MODEL_ROUTE_MAX_LENGTHS,CONTEXT_PEAK_METRIC: _MODEL_ROUTE_MAX_LENGTHS,# ---- end v4 model ----+ # ---- v5 harness ----+ LOOP_GUARD_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ TOOL_RECOVERY_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ MODEL_REPLY_ISSUE_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ # ---- end v5 harness ----}# metric -> closed dimension field set_METRIC_FIELDS: dict[str, frozenset[str]] = {@@ -594,6 +652,11 @@ _DECISION_MARK_METRICS = {UPDATE_RUN_MARK: UPDATE_RUN_METRIC, UPDATE_STAGE_MARK: UPDATE_STAGE_METRIC,PROCESS_EXIT_MARK: PROCESS_EXIT_METRIC,# ---- end v4 reliability ----+ # ---- v5 harness ----+ FILE_EDIT_MARK: FILE_EDIT_METRIC, LOOP_GUARD_MARK: LOOP_GUARD_METRIC,+ TOOL_RECOVERY_MARK: TOOL_RECOVERY_METRIC, TERMINAL_OUTCOME_MARK: TERMINAL_OUTCOME_METRIC,+ MODEL_REPLY_ISSUE_MARK: MODEL_REPLY_ISSUE_METRIC,+ # ---- end v5 harness ----}diff --git a/hermes_cli/observability/shared_metrics_harness.py b/hermes_cli/observability/shared_metrics_harness.pynew file mode 100644index 00000000000..eb72c5c954b--- /dev/null+++ b/hermes_cli/observability/shared_metrics_harness.py@@ -0,0 +1,472 @@+"""Agent-harness accuracy shared metrics: file-edit matching, loop guards, recovery after a tool+error, terminal command outcomes and bad model replies.++These tune the agent loop itself: which fuzzy-match strategies earn their keep, how often the loop+guards fire, whether a model recovers after a failed tool call, which kinds of commands fail, and+which models return empty / refused / truncated replies. Producers pass RAW values; every builder+maps them onto closed enums. Nothing here reads command text, file paths, tool arguments or reply+text beyond the structural checks Hermes already makes (think-block stripping for "visible text").++Hermes-owned agent loops (the background self-improvement review and the curator fork) are not user+work and never count. Recording is a no-op unless shared metrics are enabled for the owning profile,+and never raises into the caller. Stdlib-only at import time: tool modules import this on their hot+path.+"""++from __future__ import annotations++import contextvars+import json+import logging+import re+from dataclasses import dataclass, field+from typing import Any, Callable++logger = logging.getLogger(__name__)++_BACKGROUND_ORIGIN = "background_review"+++def _enabled() -> bool:+ try:+ from .relay_shared_metrics import enabled++ return enabled()+ except Exception:+ return False+++def _record(mark_attr: str, data: dict[str, str]) -> None:+ try:+ from . import shared_metrics_contract as contract+ from .relay_shared_metrics import record_process_mark++ record_process_mark(getattr(contract, mark_attr), data)+ except Exception:+ logger.debug("Shared-metrics %s not recorded", mark_attr, exc_info=True)+++def _background_tool_call() -> bool:+ try:+ from tools.skill_provenance import is_background_review++ return is_background_review()+ except Exception:+ return False+++def _user_agent(agent: Any) -> bool:+ """The review/curator forks tag themselves with the background write origin."""+ return agent is not None and getattr(agent, "_memory_write_origin", None) != _BACKGROUND_ORIGIN+++def _route(agent: Any) -> dict[str, str]:+ from .shared_metrics_model import model_route++ return model_route(getattr(agent, "provider", None), getattr(agent, "model", None))+++# ---- file edits ------------------------------------------------------------------------------++@dataclass+class _EditProbe:+ """What the fuzzy matcher saw during one edit tool call (several hunks for V4A)."""++ strategies: list[str] = field(default_factory=list)+ misses: list[str] = field(default_factory=list)+++_EDIT_PROBE: contextvars.ContextVar[_EditProbe | None] = contextvars.ContextVar(+ "shared_metrics_edit_probe", default=None,+)+++def note_edit_match(strategy: str | None, miss: str | None = None) -> None:+ """Called by the fuzzy matcher: the strategy that landed a replacement, or why none did+ (``no_match`` / ``ambiguous``). A no-op outside a metered edit tool call."""+ probe = _EDIT_PROBE.get()+ if probe is None:+ return+ if strategy:+ probe.strategies.append(strategy)+ elif miss:+ probe.misses.append(miss)+++def _strategy_rank() -> dict[str, int]:+ from tools.fuzzy_match import STRATEGIES++ return {name: index for index, (name, _fn) in enumerate(STRATEGIES)}+++# The patch tool's ``mode`` argument: ``patch`` is the V4A multi-hunk format.+_EDIT_MODES = {"replace": "replace", "patch": "v4a", "whole_file": "whole_file"}+++def file_edit_fields(*, tool: str, mode: Any, result: Any, probe: _EditProbe) -> dict[str, str]:+ from .shared_metrics_contract import FILE_EDIT_MODES, FILE_EDIT_STRATEGIES++ data = _parsed(result)+ # patch results carry ``success``; write_file reports bytes written, or an ``error``.+ if data.get("success") is True or (data and "success" not in data and not data.get("error")):+ outcome = "already_applied" if data.get("no_change") is True else "applied"+ elif "ambiguous" in probe.misses:+ outcome = "ambiguous"+ elif "no_match" in probe.misses:+ outcome = "no_match"+ else:+ outcome = "failed"+ strategy = "none"+ if outcome == "applied" and probe.strategies:+ # A V4A patch lands several hunks: report the loosest strategy it needed.+ rank = _strategy_rank()+ strategy = max(probe.strategies, key=lambda name: rank.get(name, -1))+ mode_value = _EDIT_MODES.get(str(mode or "").strip().lower(), "replace")+ return {+ "match_strategy": strategy if strategy in FILE_EDIT_STRATEGIES else "none",+ "mode": mode_value if mode_value in FILE_EDIT_MODES else "replace",+ "outcome": outcome,+ "tool": tool,+ }+++def record_file_edit(tool: str, mode: str, call: Callable[[], str]) -> str:+ """Run one ``patch`` / ``write_file`` tool call and count how its edit landed; returns the+ call's result unchanged. The matcher reports into a context-local probe, so strategies from+ unrelated callers (skill patches, V4A validation of another call) never mix in."""+ if not _enabled() or _background_tool_call():+ return call()+ probe = _EditProbe()+ token = _EDIT_PROBE.set(probe)+ try:+ result = call()+ finally:+ _EDIT_PROBE.reset(token)+ try:+ _record("FILE_EDIT_MARK", file_edit_fields(tool=tool, mode=mode, result=result, probe=probe))+ except Exception:+ logger.debug("Shared-metrics file edit not recorded", exc_info=True)+ return result+++def _parsed(result: Any) -> dict[str, Any]:+ if isinstance(result, dict):+ return result+ try:+ data = json.loads(result) if isinstance(result, (str, bytes)) else None+ except (TypeError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}+++# ---- terminal command outcomes ---------------------------------------------------------------++def _kinds(kind: str, *names: str) -> dict[str, str]:+ return dict.fromkeys(names, kind)+++_COMMAND_KINDS: dict[str, str] = {+ **_kinds("git", "git", "gh", "hub", "git-lfs", "tig"),+ **_kinds(+ "package_manager", "pip", "pip3", "uv", "uvx", "poetry", "pipx", "conda", "mamba", "micromamba",+ "npm", "pnpm", "yarn", "apt", "apt-get", "brew", "dnf", "yum", "pacman", "apk", "gem", "bundle",+ "composer", "nix", "snap", "choco", "winget", "port",+ ),+ **_kinds(+ "build", "make", "cmake", "ninja", "cargo", "go", "gradle", "gradlew", "mvn", "bazel", "meson",+ "gcc", "g++", "cc", "clang", "clang++", "rustc", "javac", "tsc", "dotnet", "msbuild", "scons",+ "swift", "xcodebuild", "zig",+ ),+ **_kinds(+ "test_runner", "pytest", "py.test", "tox", "nox", "jest", "vitest", "mocha", "rspec", "phpunit",+ "ctest", "playwright",+ ),+ **_kinds("python", "python", "python3", "ipython", "pypy", "pypy3"),+ **_kinds("node", "node", "npx", "deno", "bun", "ts-node", "tsx", "nodejs"),+ **_kinds(+ "shell_builtin", "cd", "echo", "export", "source", ".", "set", "unset", "pwd", "printf", "test",+ "[", "[[", "true", "false", "exit", "alias", "read", "eval", "type", "hash", "ulimit", "umask",+ "wait", "pushd", "popd", "shopt", "trap", "declare", "local", "if", "for", "while", "case", "{",+ ),+ **_kinds("shell", "bash", "sh", "zsh", "dash", "fish", "ksh", "pwsh", "powershell", "cmd"),+ **_kinds(+ "file_ops", "ls", "cat", "head", "tail", "cp", "mv", "rm", "mkdir", "rmdir", "touch", "find",+ "grep", "egrep", "rg", "sed", "awk", "chmod", "chown", "ln", "du", "df", "tree", "wc", "sort",+ "uniq", "diff", "tar", "zip", "unzip", "gzip", "gunzip", "fd", "stat", "file", "less", "more",+ "realpath", "readlink", "basename", "dirname", "cut", "tr", "xargs", "tee", "jq", "patch",+ "md5sum", "sha256sum", "truncate", "which",+ ),+ **_kinds(+ "network", "curl", "wget", "ssh", "scp", "rsync", "ping", "nc", "dig", "nslookup", "http", "telnet",+ "sftp", "ftp", "traceroute",+ ),+ **_kinds(+ "container", "docker", "podman", "kubectl", "docker-compose", "helm", "nerdctl", "minikube", "kind",+ "k9s", "apptainer", "singularity",+ ),+}+# Prefixes that only change how the real program runs; the program after them is the kind.+_COMMAND_WRAPPERS = frozenset({"sudo", "env", "time", "nohup", "exec", "command", "builtin", "nice", "stdbuf"})+_TOKEN_RE = re.compile(r"\s*([^\s;|&()<>]+)")+_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")+_PYTHON_RE = re.compile(r"python\d+(\.\d+)?")+# Only the command's opening is inspected; a huge heredoc never gets scanned.+_COMMAND_HEAD_CHARS = 256+_MAX_PREFIX_TOKENS = 4+++def command_kind(command: Any) -> str:+ """A closed kind from the command's first program word (after env assignments and wrappers+ like ``sudo``). The word itself is never exported."""+ text = command[:_COMMAND_HEAD_CHARS] if isinstance(command, str) else ""+ position = 0+ for _ in range(_MAX_PREFIX_TOKENS + 1):+ match = _TOKEN_RE.match(text, position)+ if match is None:+ return "other"+ position = match.end()+ word = match.group(1).strip("'\"")+ if _ASSIGNMENT_RE.match(word) or word.lower() in _COMMAND_WRAPPERS or word.startswith("-"):+ continue # env assignments, wrappers and their flags (``sudo -E``)+ name = word.rsplit("/", 1)[-1].lower()+ if name in _COMMAND_KINDS:+ return _COMMAND_KINDS[name]+ return "python" if _PYTHON_RE.fullmatch(name) else "other"+ return "other"+++# Exit statuses a shell reports for a foreground child killed by SIGKILL / SIGTERM (OOM killer,+# an external kill); a negative status is Python's own "terminated by signal N".+_KILLED_STATUSES = frozenset({137, 143})+++def terminal_outcome(result: Any) -> str | None:+ """How one foreground command ended, from the backend's raw result dict. Hermes' own deadline+ and interrupt set flags on the result, so a command's own ``exit 124`` reads ``nonzero``."""+ if not isinstance(result, dict):+ return None+ if result.get("hermes_timed_out") is True:+ return "timeout"+ if result.get("hermes_interrupted") is True:+ return "killed"+ code = result.get("returncode")+ if not isinstance(code, int) or isinstance(code, bool):+ return None+ if code == 0:+ return "ok"+ return "killed" if code < 0 or code in _KILLED_STATUSES else "nonzero"+++def terminal_outcome_fields(*, command: Any, backend: Any, outcome: str) -> dict[str, str]:+ from .shared_metrics_contract import TERMINAL_BACKENDS++ backend_value = str(backend or "").strip().lower()+ return {+ "backend": backend_value if backend_value in TERMINAL_BACKENDS else "other",+ "command_kind": command_kind(command),+ "outcome": outcome,+ }+++def record_terminal_outcome(command: Any, backend: Any, result: Any = None, *, outcome: str | None = None) -> None:+ """Count one foreground terminal command that reached an exit status (or Hermes' deadline).+ Commands handed to the background, refused by a guard, or whose backend failed never ran to+ an exit status and are not counted here (``hermes.execution_backend.count`` covers them)."""+ try:+ if not _enabled() or _background_tool_call():+ return+ from .shared_metrics_loop import _UNMETERED++ if _UNMETERED.get():+ return+ resolved = outcome or terminal_outcome(result)+ if resolved is None:+ return+ _record("TERMINAL_OUTCOME_MARK", terminal_outcome_fields(command=command, backend=backend, outcome=resolved))+ except Exception:+ logger.debug("Shared-metrics terminal outcome not recorded", exc_info=True)+++# ---- per-turn agent state (loop guards, recovery) -----------------------------------------------++@dataclass+class _TurnState:+ """Per-turn harness bookkeeping; ``agent._harness_metrics_turn`` is reset at turn start."""++ round_outcomes: list[tuple[str, bool]] = field(default_factory=list)+ pending_errors: list[str] = field(default_factory=list)+ guard_signals: set[tuple[str, str]] = field(default_factory=set)+++def _turn_state(agent: Any) -> _TurnState:+ state = getattr(agent, "_harness_metrics_turn", None)+ if not isinstance(state, _TurnState):+ state = _TurnState()+ agent._harness_metrics_turn = state+ return state+++def _active(agent: Any) -> bool:+ return _user_agent(agent) and _enabled()+++# ---- loop guards -----------------------------------------------------------------------------++_GUARD_DETECTORS = {+ **dict.fromkeys(("repeated_exact_failure_block", "repeated_exact_failure_warning"), "exact_failure"),+ **dict.fromkeys(("idempotent_no_progress_block", "idempotent_no_progress_warning"), "idempotent_no_progress"),+ **dict.fromkeys(("same_tool_failure_halt", "same_tool_failure_warning"), "same_tool_failure"),+ "identical_call_streak_halt": "identical_call_streak", "identical_call_streak": "identical_call_streak",+ "identical_cycle_halt": "identical_cycle", "identical_cycle": "identical_cycle",+ "loop_web_search_cap": "web_search_cap", "loop_subagent_cap": "subagent_cap",+}+++def _record_guard(agent: Any, signal: str, detector: str) -> None:+ state = _turn_state(agent)+ if (signal, detector) in state.guard_signals:+ return # a detector that keeps firing is one stuck turn, not N+ state.guard_signals.add((signal, detector))+ _record("LOOP_GUARD_MARK", {**_route(agent), "detector": detector, "signal": signal})+++def record_guardrail_decision(agent: Any, action: Any, code: Any) -> None:+ """A tool-loop guardrail verdict: ``warn`` (the call ran, the model was told it is repeating)+ is ``repeated_tool_call``; ``block``/``halt`` (the harness stopped it) is ``loop_detected``.+ Once per turn per detector and signal."""+ try:+ detector = _GUARD_DETECTORS.get(str(code or ""))+ signal = {"warn": "repeated_tool_call", "block": "loop_detected", "halt": "loop_detected"}.get(str(action or ""))+ if detector is None or signal is None or not _active(agent):+ return+ _record_guard(agent, signal, detector)+ except Exception:+ logger.debug("Shared-metrics loop guard not recorded", exc_info=True)+++def record_guardrail_warnings(agent: Any, decision: Any, stall_kind: str | None) -> None:+ """The warnings one tool result carried: a guardrail ``warn`` verdict and/or an identical-call+ stall notice (``stall_kind`` names its detector)."""+ if getattr(decision, "action", None) == "warn":+ record_guardrail_decision(agent, "warn", getattr(decision, "code", None))+ if stall_kind:+ record_guardrail_decision(agent, "warn", stall_kind)+++_BUDGET_EXIT_PREFIXES = ("budget_exhausted", "max_iterations_reached(")+++# ---- recovery after a tool error -------------------------------------------------------------++def _tool_name(name: Any) -> str:+ from .shared_metrics_contract import tool_metric_name++ return tool_metric_name({"tool_name": name})+++def observe_tool_outcome(agent: Any, tool_name: Any, is_error: bool) -> None:+ """Every committed tool result of the current round, in the model's emission order."""+ try:+ if _active(agent):+ _turn_state(agent).round_outcomes.append((str(tool_name or ""), bool(is_error)))+ except Exception:+ logger.debug("Shared-metrics tool outcome not observed", exc_info=True)+++def _record_recovery(agent: Any, route: dict[str, str], tool: str, next_tool: str, next_outcome: str) -> None:+ _record("TOOL_RECOVERY_MARK", {+ **route, "next_outcome": next_outcome, "next_tool": next_tool, "tool": _tool_name(tool),+ })+++def finish_tool_round(agent: Any) -> None:+ """Resolve the previous round's failed calls against this round's first calls, then carry+ this round's failures forward. The next call to the same tool is the retry; with none, the+ model switched tools and its first call is what it tried instead."""+ try:+ if not _active(agent):+ return+ state = _turn_state(agent)+ outcomes, state.round_outcomes = state.round_outcomes, []+ if not outcomes:+ return+ if state.pending_errors:+ route = _route(agent)+ for tool in state.pending_errors:+ same = next((failed for name, failed in outcomes if name == tool), None)+ failed = outcomes[0][1] if same is None else same+ _record_recovery(+ agent, route, tool, "different" if same is None else "same", "error" if failed else "success",+ )+ state.pending_errors = [name for name, failed in outcomes if failed]+ except Exception:+ logger.debug("Shared-metrics tool recovery not recorded", exc_info=True)+++def finish_turn(agent: Any, turn_exit_reason: Any, final_response: Any, *, interrupted: Any, failed: Any) -> None:+ """Turn end: the iteration cap, and failed calls the model never followed with another+ call — ``no_tool_call`` when it answered in text, ``gave_up`` when the turn ended without a+ reply from it (halted, budget spent, interrupted, errored)."""+ try:+ if not _active(agent):+ return+ state = _turn_state(agent)+ reason = str(turn_exit_reason or "")+ if reason.startswith(_BUDGET_EXIT_PREFIXES):+ _record_guard(agent, "iteration_cap", "iteration_budget")+ pending, state.pending_errors = state.pending_errors, []+ if not pending:+ return+ answered = (+ reason.startswith("text_response(") and bool(final_response) and not interrupted and not failed+ )+ route = _route(agent)+ for tool in pending:+ _record_recovery(agent, route, tool, "none", "no_tool_call" if answered else "gave_up")+ except Exception:+ logger.debug("Shared-metrics turn end not recorded", exc_info=True)+++# ---- model reply issues ------------------------------------------------------------------------++_FINISH_ISSUES = {"content_filter": "refusal", "length": "truncated_length", "incomplete": "truncated_length"}+++def record_reply_finish(agent: Any, response: Any, finish_reason: Any) -> None:+ """A primary response whose structured finish reason is a refusal or an output-length stop+ (transports already promote Anthropic ``stop_reason=refusal`` and an OpenAI ``message.refusal``+ to ``content_filter``). Those mostly leave the loop before normal intake, so they are counted+ where the reason is derived; the latch keeps intake from counting the same response again."""+ try:+ issue = _FINISH_ISSUES.get(str(finish_reason or ""))+ if issue is None or not _active(agent):+ return+ agent._harness_metrics_reply = response+ _record("MODEL_REPLY_ISSUE_MARK", {**_route(agent), "issue": issue})+ except Exception:+ logger.debug("Shared-metrics reply finish not recorded", exc_info=True)+++def reply_content_issue(agent: Any, assistant_message: Any) -> str:+ if getattr(assistant_message, "tool_calls", None):+ return "none"+ content = getattr(assistant_message, "content", None)+ if isinstance(content, str) and content.strip() and agent._has_content_after_think_block(content):+ return "none"+ return "reasoning_only" if agent._extract_reasoning(assistant_message) else "empty"+++def record_reply_content(agent: Any, response: Any, assistant_message: Any) -> None:+ """Every other primary response: ``empty`` (no visible text, no tool call, no reasoning),+ ``reasoning_only`` (reasoning but nothing to show or run), else ``none`` — one row per+ response, so issue rates have their own denominator."""+ try:+ if not _active(agent):+ return+ if getattr(agent, "_harness_metrics_reply", None) is response:+ agent._harness_metrics_reply = None # already counted at the finish reason+ return+ _record("MODEL_REPLY_ISSUE_MARK", {**_route(agent), "issue": reply_content_issue(agent, assistant_message)})+ except Exception:+ logger.debug("Shared-metrics reply content not recorded", exc_info=True)+diff --git a/run_agent.py b/run_agent.pyindex da24b910f03..b3528450531 100644--- a/run_agent.py+++ b/run_agent.py@@ -162,6 +162,7 @@ from agent.codex_responses_adapter import (_summarize_user_message_for_log,)from agent.tool_guardrails import ToolGuardrailDecision, append_toolguard_guidance, toolguard_synthetic_result+from hermes_cli.observability.shared_metrics_harness import record_guardrail_decision, record_guardrail_warningsfrom utils import base_url_host_matches, base_url_hostname, env_float, model_forces_max_completion_tokens@@ -1268,6 +1269,8 @@ class AIAgent("""Record the first guardrail decision that should stop this turn."""if decision.should_halt and self._tool_guardrail_halt_decision is None:self._tool_guardrail_halt_decision = decision+ if decision.should_halt:+ record_guardrail_decision(self, decision.action, decision.code)def _toolguard_controlled_halt_response(self, decision: ToolGuardrailDecision) -> str:# Shown to the user as the reply, so no decision codes; the code stays in result["guardrail"].@@ -1283,14 +1286,14 @@ class AIAgent(decision = self._tool_guardrails.after_call(tool_name, function_args, function_result, failed=failed)# Identical-call stall guards observe the RAW result (before the per-call loop suffix) and are applied# at result construction so tool results stay append-only / cache-safe.- stall_notice = result_stub = None+ stall_notice = result_stub = stall_kind = Noneif self._stall_guards_enabled():try:observation = self._tool_guardrails.observe_call(tool_name, function_args, function_result if isinstance(function_result, str) else None,tool_call_id=tool_call_id, failed=failed,)- stall_notice, result_stub = observation.notice, observation.stub+ stall_notice, result_stub, stall_kind = observation.notice, observation.stub, observation.kindexcept Exception as exc:logger.debug("stall-guard identical-call observation failed: %s", exc)# Result-reference stubbing: a 2nd+ identical call with a byte-identical FRESH result enters@@ -1299,6 +1302,7 @@ class AIAgent(function_result = result_stubif decision.action in {"warn", "halt"}:function_result = append_toolguard_guidance(function_result, decision)+ record_guardrail_warnings(self, decision, stall_kind if stall_notice else None)if decision.should_halt:self._set_tool_guardrail_halt(decision)else:diff --git a/tests/hermes_cli/test_shared_metrics_harness.py b/tests/hermes_cli/test_shared_metrics_harness.pynew file mode 100644index 00000000000..7a87dfd0c64--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_harness.py@@ -0,0 +1,252 @@+"""Agent-harness accuracy shared metrics: file edits, loop guards, tool-error recovery, terminal+command outcomes and model reply issues."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from hermes_cli.observability import relay_shared_metrics+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_harness as harness+from tests.hermes_cli.test_relay_shared_metrics_runtime import ( # noqa: F401 - fixture+ _stored_values,+ direct_runtime,+)+++def _flush() -> None:+ runtime = relay_shared_metrics._get_runtime(retry_failed=True)+ assert runtime is not None+ runtime.relay.subscribers.flush()+++def _rows(tmp_path, metric, *fields):+ _flush()+ return sorted((*(d[f] for f in fields), v) for d, v in _stored_values(tmp_path, metric))+++def _agent(provider="openrouter", model="anthropic/claude-sonnet", **extra):+ return SimpleNamespace(**{+ "provider": provider, "model": model, "_memory_write_origin": "assistant_tool",+ "_has_content_after_think_block": lambda text: bool(text.replace("<think>x</think>", "").strip()),+ "_extract_reasoning": lambda message: getattr(message, "reasoning", None),+ **extra,+ })+++# ---- file edits ------------------------------------------------------------------------------++def test_patch_and_write_file_count_outcome_and_the_strategy_that_landed(direct_runtime, tmp_path):+ from tools.file_tools import _handle_patch, _handle_write_file++ target = tmp_path / "work" / "a.py"+ _handle_write_file({"path": str(target), "content": "def f():\n return 1\n\nx = 1\nx = 1\n"}, task_id="t")+ _handle_patch({"path": str(target), "old_string": "return 1", "new_string": "return 2"}, task_id="t")+ # Wrong indentation: only a whitespace-tolerant strategy lands it.+ _handle_patch({"path": str(target), "old_string": "def f():\n return 2", "new_string": "def f():\n return 3"},+ task_id="t")+ _handle_patch({"path": str(target), "old_string": "nothing like this", "new_string": "y"}, task_id="t")+ _handle_patch({"path": str(target), "old_string": "x = 1", "new_string": "x = 2"}, task_id="t")+ _handle_patch({"mode": "patch", "patch": (+ f"*** Begin Patch\n*** Update File: {target}\n@@\n-def f():\n+def g():\n*** End Patch\n")}, task_id="t")+ assert "return 3" in target.read_text() and "def g" in target.read_text()++ rows = _rows(tmp_path, contract.FILE_EDIT_METRIC, "tool", "mode", "outcome", "match_strategy")+ fuzzy = [r for r in rows if r[3] not in {"exact", "none"}]+ assert len(fuzzy) == 1 and fuzzy[0][:3] == ("patch", "replace", "applied")+ assert fuzzy[0][3] in contract.FILE_EDIT_STRATEGIES+ assert [r for r in rows if r not in fuzzy] == sorted([+ ("patch", "replace", "ambiguous", "none", 1),+ ("patch", "replace", "applied", "exact", 1),+ ("patch", "replace", "no_match", "none", 1),+ ("patch", "v4a", "applied", "exact", 1),+ ("write_file", "whole_file", "applied", "none", 1),+ ])+++def test_matcher_calls_outside_an_edit_tool_call_are_not_counted(direct_runtime, tmp_path):+ from tools.fuzzy_match import fuzzy_find_and_replace++ fuzzy_find_and_replace("a = 1\n", "a = 1", "a = 2") # e.g. a skill patch, internal callers+ assert _rows(tmp_path, contract.FILE_EDIT_METRIC, "outcome") == []+++def test_v4a_patch_reports_its_loosest_hunk_strategy():+ probe = harness._EditProbe(strategies=["exact", "line_trimmed", "exact"])+ fields = harness.file_edit_fields(tool="patch", mode="patch", result='{"success": true}', probe=probe)+ assert fields == {"match_strategy": "line_trimmed", "mode": "v4a", "outcome": "applied", "tool": "patch"}+ probe = harness._EditProbe(misses=["no_match"])+ assert harness.file_edit_fields(+ tool="patch", mode="patch", result='{"success": true, "no_change": true}', probe=probe,+ )["outcome"] == "already_applied"+++# ---- terminal ----------------------------------------------------------------------------------+[email protected](("command", "kind"), [+ ("git status", "git"), ("FOO=1 sudo -E pip install x", "package_manager"), ("/usr/bin/python3.12 -c 1", "python"),+ ("pytest -q tests/", "test_runner"), (" cd /tmp && make", "shell_builtin"), ("npx tsc", "node"),+ ("docker ps", "container"), ("curl -s http://x", "network"), ("ls -la", "file_ops"), ("bash -lc 'x'", "shell"),+ ("cargo build", "build"), ("my-private-tool --secret", "other"), ("", "other"), (None, "other"),+])+def test_command_kind_comes_from_the_first_program_word(command, kind):+ assert harness.command_kind(command) == kind+ assert kind in contract.TERMINAL_COMMAND_KINDS+++def test_terminal_outcome_trusts_hermes_flags_not_exit_124():+ assert harness.terminal_outcome({"returncode": 124}) == "nonzero" # the command's own `exit 124`+ assert harness.terminal_outcome({"returncode": 124, "hermes_timed_out": True}) == "timeout"+ assert harness.terminal_outcome({"returncode": 130, "hermes_interrupted": True}) == "killed"+ assert harness.terminal_outcome({"returncode": 137}) == "killed"+ assert harness.terminal_outcome({"returncode": -9}) == "killed"+ assert harness.terminal_outcome({"returncode": 0}) == "ok"+ assert harness.terminal_outcome({"output": "x"}) is None+++def test_foreground_terminal_commands_count_by_kind_and_outcome(direct_runtime, tmp_path, monkeypatch):+ from tools.terminal_tool import terminal_tool++ monkeypatch.setenv("TERMINAL_ENV", "local")+ results = [json.loads(terminal_tool(command, task_id="harness", timeout=timeout)) for command, timeout in (+ ("ls /definitely/not/here", 30), ("echo ok", 30), ("sh -c 'exit 124'", 30), ("sleep 5", 1),+ )]+ assert [r["exit_code"] for r in results] == [2, 0, 124, 124]+ terminal_tool("true", task_id="harness", _host_local=True) # Hermes' own control plane: never counted+ rows = _rows(tmp_path, contract.TERMINAL_OUTCOME_METRIC, "backend", "command_kind", "outcome")+ assert rows == sorted([+ ("local", "file_ops", "nonzero", 1), ("local", "shell_builtin", "ok", 1),+ ("local", "shell", "nonzero", 1), ("local", "other", "timeout", 1),+ ])+ assert "definitely" not in json.dumps(_stored_values(tmp_path, contract.TERMINAL_OUTCOME_METRIC))+++# ---- loop guards -------------------------------------------------------------------------------++def test_loop_guards_count_once_per_turn_per_signal_and_detector(direct_runtime, tmp_path):+ agent = _agent()+ for _ in range(3):+ harness.record_guardrail_decision(agent, "warn", "same_tool_failure_warning")+ harness.record_guardrail_decision(agent, "halt", "same_tool_failure_halt")+ harness.record_guardrail_decision(agent, "warn", "identical_call_streak")+ harness.record_guardrail_decision(agent, "block", "loop_web_search_cap")+ harness.record_guardrail_decision(agent, "allow", "allow") # not a guard verdict+ harness.finish_turn(agent, "max_iterations_reached(90/90)", "", interrupted=False, failed=False)+ agent._harness_metrics_turn = None # next turn: the latch resets+ harness.record_guardrail_decision(agent, "warn", "same_tool_failure_warning")+ harness.record_guardrail_decision(_agent(_memory_write_origin="background_review"), "halt", "identical_cycle_halt")++ assert _rows(tmp_path, contract.LOOP_GUARD_METRIC, "provider", "model", "signal", "detector") == sorted([+ ("openrouter", "anthropic/claude-sonnet", "iteration_cap", "iteration_budget", 1),+ ("openrouter", "anthropic/claude-sonnet", "loop_detected", "same_tool_failure", 1),+ ("openrouter", "anthropic/claude-sonnet", "loop_detected", "web_search_cap", 1),+ ("openrouter", "anthropic/claude-sonnet", "repeated_tool_call", "identical_call_streak", 1),+ ("openrouter", "anthropic/claude-sonnet", "repeated_tool_call", "same_tool_failure", 2),+ ])+++def test_real_guardrail_halt_reaches_the_metric(direct_runtime, tmp_path):+ from agent.tool_guardrails import ToolCallGuardrailConfig, ToolCallGuardrailController+ from run_agent import AIAgent++ agent = _agent()+ agent._tool_guardrails = ToolCallGuardrailController(ToolCallGuardrailConfig(hard_stop_enabled=True))+ agent._tool_guardrail_halt_decision = None+ agent._stall_guards_enabled = lambda: True+ agent._set_tool_guardrail_halt = lambda decision: AIAgent._set_tool_guardrail_halt(agent, decision)+ for i in range(8):+ AIAgent._append_guardrail_observation(+ agent, "terminal", {"command": "false"}, '{"exit_code": 1, "error": "boom"}', failed=True,+ tool_call_id=f"c{i}",+ )+ halt = agent._tool_guardrail_halt_decision+ assert halt is not None+ signals = {(s, d) for s, d, _v in _rows(tmp_path, contract.LOOP_GUARD_METRIC, "signal", "detector")}+ assert ("loop_detected", harness._GUARD_DETECTORS[halt.code]) in signals+ assert any(s == "repeated_tool_call" for s, _d in signals)+++# ---- tool-error recovery -----------------------------------------------------------------------++def _round(agent, *outcomes):+ for name, failed in outcomes:+ harness.observe_tool_outcome(agent, name, failed)+ harness.finish_tool_round(agent)+++def test_each_failed_call_resolves_against_the_models_next_call(direct_runtime, tmp_path):+ agent = _agent()+ _round(agent, ("terminal", True), ("read_file", False))+ _round(agent, ("read_file", False), ("terminal", False)) # retried the same tool: success+ _round(agent, ("patch", True), ("mcp_acme_secret", True))+ _round(agent, ("search_files", True)) # patch: switched tools; mcp: switched+ harness.finish_turn(agent, "text_response(stop)", "done", interrupted=False, failed=False)+ agent._harness_metrics_turn = None+ _round(agent, ("web_search", True))+ harness.finish_turn(agent, "guardrail_halt", "stopped", interrupted=False, failed=True)++ rows = _rows(tmp_path, contract.TOOL_RECOVERY_METRIC, "tool", "next_tool", "next_outcome")+ assert rows == sorted([+ ("terminal", "same", "success", 1),+ ("patch", "different", "error", 1),+ ("mcp", "different", "error", 1),+ ("search_files", "none", "no_tool_call", 1),+ ("web_search", "none", "gave_up", 1),+ ])+ assert "acme" not in json.dumps(_stored_values(tmp_path, contract.TOOL_RECOVERY_METRIC))+++# ---- model reply issues ------------------------------------------------------------------------++def test_every_primary_reply_counts_once_with_its_issue(direct_runtime, tmp_path):+ agent = _agent()++ def reply(finish_reason, **message):+ response = object()+ harness.record_reply_finish(agent, response, finish_reason)+ harness.record_reply_content(agent, response, SimpleNamespace(**{"content": None, "tool_calls": None, **message}))++ reply("stop", content="hello")+ reply("tool_calls", tool_calls=[object()])+ reply("stop", content=" ")+ reply("stop", content="<think>x</think>", reasoning="x")+ reply("length", content="half an ans") # counted once, at the finish reason+ harness.record_reply_finish(agent, object(), "content_filter") # refusal never reaches intake+ harness.record_reply_content(_agent(_memory_write_origin="background_review"), object(),+ SimpleNamespace(content="", tool_calls=None))++ assert _rows(tmp_path, contract.MODEL_REPLY_ISSUE_METRIC, "issue") == sorted([+ ("empty", 1), ("none", 2), ("reasoning_only", 1), ("refusal", 1), ("truncated_length", 1),+ ])+++def test_everything_is_a_no_op_while_disabled(direct_runtime, tmp_path, monkeypatch):+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly", lambda: {})+ agent = _agent()+ harness.record_reply_finish(agent, object(), "length")+ _round(agent, ("terminal", True))+ harness.record_guardrail_decision(agent, "halt", "identical_cycle_halt")+ assert getattr(agent, "_harness_metrics_turn", None) is None+ assert harness.record_file_edit("patch", "replace", lambda: '{"success": true}') == '{"success": true}'+++# ---- schema ------------------------------------------------------------------------------------++def test_v3_schema_accepts_exactly_the_contract_values():+ import hermes_cli.observability as observability++ schema = json.loads((Path(observability.__file__).parent / "schemas/hermes.shared_metrics.v3.schema.json").read_text())+ by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}+ for metric in (contract.FILE_EDIT_METRIC, contract.LOOP_GUARD_METRIC, contract.TOOL_RECOVERY_METRIC,+ contract.TERMINAL_OUTCOME_METRIC, contract.MODEL_REPLY_ISSUE_METRIC):+ dims = by_name[metric]["properties"]["dimensions"]["properties"]+ closed = {field: set(spec["enum"]) for field, spec in dims.items() if "enum" in spec}+ assert closed == {+ field: set(values) for field, values in contract._COUNTER_DIMENSION_VALUES[metric].items()+ if values is not contract.TOOL_NAMES+ }+ assert ({"provider", "model"} <= set(dims)) == (metric in contract._IDENTIFIER_FIELDS)diff --git a/tools/environments/base.py b/tools/environments/base.pyindex 5f578e57e68..5bd33c036b7 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -493,7 +493,8 @@ class BaseEnvironment(ABC):if is_interrupted() or is_thread_interrupted(watch_interrupt_tid):trace.interrupted()_kill_and_join()- return self._finalize_wait_result(output, output.render(suffix="\n[Command interrupted]"), 130)+ return {**self._finalize_wait_result(output, output.render(suffix="\n[Command interrupted]"), 130),+ "hermes_interrupted": True}if yield_handler is not None and consume_yield(watch_interrupt_tid):drain_stop.set()drain_thread.join(timeout=1)@@ -513,7 +514,8 @@ class BaseEnvironment(ABC):rendered = output.render(suffix=f"\n[Command timed out after {timeout}s]")if output.total_chars == 0:rendered = rendered.lstrip()- return self._finalize_wait_result(output, rendered, 124)+ # The flag tells Hermes' own deadline apart from a command's own ``exit 124``.+ return {**self._finalize_wait_result(output, rendered, 124), "hermes_timed_out": True}touch_activity_if_due(_activity_state, "terminal command running")trace.heartbeat()time.sleep(_poll_sleep)@@ -706,6 +708,7 @@ class BaseEnvironment(ABC):result = self._finalize_wait_result(collector, collector.render(suffix=suffix).lstrip("\n"), 124)else:result = {"output": suffix.lstrip(), "returncode": 124}+ result["hermes_timed_out"] = Trueelse:result = bounded.valueself._update_cwd(result)diff --git a/tools/file_tools.py b/tools/file_tools.pyindex 6a8c64be443..56dca8c4986 100644--- a/tools/file_tools.py+++ b/tools/file_tools.py@@ -1326,22 +1326,27 @@ def _handle_write_file(args, **kw):f"write_file: 'content' must be a string, got "f"{type(args['content']).__name__}.")- return write_file_tool(+ from hermes_cli.observability.shared_metrics_harness import record_file_edit++ return record_file_edit("write_file", "whole_file", lambda: write_file_tool(path=args["path"], content=args["content"], task_id=tid,cross_profile=bool(args.get("cross_profile", False)),session_id=kw.get("session_id"),- )+ ))def _handle_patch(args, **kw):+ from hermes_cli.observability.shared_metrics_harness import record_file_edit+tid = kw.get("task_id") or "default"- return patch_tool(- mode=args.get("mode", "replace"), path=args.get("path"),+ mode = args.get("mode", "replace")+ return record_file_edit("patch", mode, lambda: patch_tool(+ mode=mode, path=args.get("path"),old_string=args.get("old_string"), new_string=args.get("new_string"),replace_all=args.get("replace_all", False), patch=args.get("patch"), task_id=tid,cross_profile=bool(args.get("cross_profile", False)),session_id=kw.get("session_id"),- )+ ))def _handle_search_files(args, **kw):diff --git a/tools/fuzzy_match.py b/tools/fuzzy_match.pyindex 655d4cb6b3c..46c725d87c7 100644--- a/tools/fuzzy_match.py+++ b/tools/fuzzy_match.py@@ -367,12 +367,14 @@ def fuzzy_find_and_replace(content: str, old_string: str, new_string: str,continueif len(matches) > 1 and not replace_all:+ _note_edit_match(None, "ambiguous")locations = _format_match_locations(content, matches)return content, 0, None, (f"Found {len(matches)} matches for old_string. "f"Provide more context to make it unique, or use replace_all=True. "f"Matches:\n{locations}")if replace_all and len(matches) > 1 and strategy_name in SIMILARITY_STRATEGIES:+ _note_edit_match(None, "ambiguous")return content, 0, None, (f"Found {len(matches)} approximate matches via the "f"'{strategy_name}' strategy; replace_all only applies to exact "@@ -392,11 +394,23 @@ def fuzzy_find_and_replace(content: str, old_string: str, new_string: str,new_content = _apply_replacements(content, matches, effective_new,old_string=old_string if strategy_name != "exact" else None)+ _note_edit_match(strategy_name)return new_content, len(matches), strategy_name, None+ _note_edit_match(None, "no_match")return content, 0, None, "Could not find a match for old_string in the file"+def _note_edit_match(strategy: Optional[str], miss: Optional[str] = None) -> None:+ """Report to shared metrics which strategy landed (or why none did); a no-op unless a+ metered patch tool call is in progress."""+ try:+ from hermes_cli.observability.shared_metrics_harness import note_edit_match+ except Exception:+ return+ note_edit_match(strategy, miss)++# ── Escape-drift guards ──────────────────────────────────────────────────def _detect_escape_drift(content: str, matches: list[Span],diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 6e195ab5eda..ba3db664868 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1239,8 +1239,11 @@ def _run_foreground(command: str, env: Any, plan: _ExecPlan, *,task_id: Optional[str], session_id: Optional[str], session_key: str,workdir: Optional[str], approval_note: Optional[str], clear_interrupt: bool,+ metered: bool = True,) -> str:- """Execute in the foreground with retry on transient errors, then finalize."""+ """Execute in the foreground with retry on transient errors, then finalize. ``metered``+ is False for Hermes' own control-plane commands (``_host_local``)."""+ from hermes_cli.observability.shared_metrics_harness import record_terminal_outcomemax_retries = 3env_type, eff, effective_timeout = plan.env_type, plan.effective_task_id, plan.effective_timeout@@ -1271,6 +1274,8 @@ def _run_foreground(breakexcept Exception as e:if "timeout" in str(e).lower():+ if metered:+ record_terminal_outcome(command, env_type, outcome="timeout")return _error_json(f"Command timed out after {effective_timeout} seconds", exit_code=124)# Retry on transient errorsif retry_count < max_retries:@@ -1283,12 +1288,14 @@ def _run_foreground(max_retries, _safe_command_preview(command), type(e).__name__, e, eff, env_type)return _error_json(_redact_terminal_error_text(f"Command execution failed: {type(e).__name__}: {e}"))- if result.get("yielded_session_id"):+ if result.get("yielded_session_id"): # handed to the background: no exit status yetreturn json.dumps({"output": result.get("output", ""), "exit_code": None, "error": None,"status": "yielded_to_background", "session_id": result["yielded_session_id"],"pid": result.get("pid"), "notify_on_complete": True, "note": _YIELDED_NOTE,}, ensure_ascii=False)+ if metered:+ record_terminal_outcome(command, env_type, result)return finalize_foreground_result(command=command, result=result, env=env, env_type=env_type, effective_task_id=eff,task_id=task_id, session_id=session_id, session_key=session_key, workdir=workdir,@@ -1469,6 +1476,7 @@ def terminal_tool(command, env, plan,task_id=task_id, session_id=session_id, session_key=session_key,workdir=workdir, approval_note=verdict.note, clear_interrupt=verdict.approved_run,+ metered=not _host_local,))except _Rejected as r:return r.result_jsondiff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 7f921ae0d91..de11386d02c 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -334,6 +334,22 @@ whose provider is unknown reads `custom`.| `hermes.model_friction.count` | provider, model, signal (`retry`, `undo`, `interrupt`, `quick_abandon`, `switch_away`) | Which models users fight with. Attributed to the model that produced the turn: `/retry` and `/undo` where they execute, a user interrupt of an interactive turn, a session that ends within 60 seconds of a failed turn, and `/model` switching away from the model. || `hermes.context_peak.count` | provider, model, peak fill bucket, window bucket (`lt_32k` … `gte_1m`), limit hit (`yes`/`no`) | How close sessions get to each model's context window, and how often they overflow it. One row per closed conversation: the session ids a compression rotation continues it under report once, with the fullest segment; `limit_hit` means a primary call was rejected as too large (context overflow or HTTP 413), the rejections Hermes answers with a forced compression. |+<!-- ---- v5 harness ---- -->+#### Agent-harness accuracy++These tune the agent loop itself. Hermes' own background review and curator+loops never count; command text, file paths, tool arguments and reply text never+leave — only the closed values below.++| Metric | Dimensions | Question it answers |+|---|---|---|+| `hermes.file_edit.count` | tool (`patch`, `write_file`), mode (`replace`, `v4a`, `whole_file`), outcome (`applied`, `already_applied`, `no_match`, `ambiguous`, `failed`), match strategy (the patch tool's fuzzy-match chain: `exact`, `line_trimmed`, `whitespace_normalized`, `indentation_flexible`, `escape_normalized`, `trimmed_boundary`, `unicode_normalized`, `block_anchor`, `context_aware`; `none` when nothing was matched) | Which fuzzy-match strategies earn their keep, and how often edits miss or are ambiguous. One row per edit tool call; a multi-hunk V4A patch reports the loosest strategy any hunk needed. |+| `hermes.loop_guard.count` | provider, model, signal (`repeated_tool_call`, `loop_detected`, `iteration_cap`), detector (`exact_failure`, `idempotent_no_progress`, `same_tool_failure`, `identical_call_streak`, `identical_cycle`, `web_search_cap`, `subagent_cap`, `iteration_budget`) | How often each stuck-loop guard fires, per model. `repeated_tool_call` is a warning the call still ran with, `loop_detected` a block or halt, `iteration_cap` a turn that spent its iteration budget. At most once per turn per signal and detector. |+| `hermes.tool_recovery.count` | provider, model, tool (built-in name, else `mcp` / `plugin`), next tool (`same`, `different`, `none`), next outcome (`success`, `error`, `no_tool_call`, `gave_up`) | Whether models recover after a failed tool call. One row per failed call, resolved against the model's next round: its next call to the same tool, else its first call; `no_tool_call` when it answered in text instead, `gave_up` when the turn ended without its reply (halted, budget spent, interrupted, errored). |+| `hermes.terminal.outcome.count` | backend (the terminal backends), command kind (`git`, `package_manager`, `build`, `test_runner`, `python`, `node`, `shell_builtin`, `shell`, `file_ops`, `network`, `container`, `other`), outcome (`ok`, `nonzero`, `timeout`, `killed`) | Which kinds of commands fail or time out, per backend. The kind comes from a fixed table of the first program word (after env assignments and `sudo`-style wrappers). One row per foreground command that reached an exit status; `timeout` / `killed` come from Hermes' own deadline and interrupt flags, so a command's own `exit 124` is `nonzero`. `hermes.execution_backend.count` counts the same calls by whether the backend served them — disjoint dimensions, not a second count of outcomes. |+| `hermes.model_reply_issue.count` | provider, model, issue (`none`, `empty`, `reasoning_only`, `refusal`, `truncated_length`) | Which models return unusable replies. One row per primary model response (usable ones as `none`, the rate denominator). `refusal` and `truncated_length` come only from the structured finish reason (`content_filter`, `length`); `empty` is a valid response with no visible text, tool call or reasoning. |+<!-- ---- end v5 harness ---- -->+Local state is written under:```text