Skip to content

The agent that grows with you

Merge updated tool metrics into skill metrics

Alex Fournier3d5fcab70f0e
diff --cc hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
index 00000000000,da8e7c78d0c..92562288534
mode 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,544 +1,658 @@@
+ {
+ "$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"
++ },
++ {
++ "$ref": "#/$defs/skill_lifecycle_counter"
++ },
++ {
++ "$ref": "#/$defs/skill_load_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
+ }
+ }
++ },
++ "skill_lifecycle_counter": {
++ "type": "object",
++ "additionalProperties": false,
++ "required": [
++ "name",
++ "type",
++ "dimensions",
++ "value"
++ ],
++ "properties": {
++ "name": {
++ "const": "hermes.skill.lifecycle.count"
++ },
++ "type": {
++ "const": "counter"
++ },
++ "dimensions": {
++ "type": "object",
++ "additionalProperties": false,
++ "required": [
++ "action",
++ "provenance"
++ ],
++ "properties": {
++ "action": {
++ "enum": [
++ "archived",
++ "created",
++ "edited",
++ "installed",
++ "patched",
++ "restored",
++ "stale"
++ ]
++ },
++ "provenance": {
++ "$ref": "#/$defs/skill_provenance"
++ }
++ }
++ },
++ "value": {
++ "type": "integer",
++ "minimum": 1
++ }
++ }
++ },
++ "skill_load_counter": {
++ "type": "object",
++ "additionalProperties": false,
++ "required": [
++ "name",
++ "type",
++ "dimensions",
++ "value"
++ ],
++ "properties": {
++ "name": {
++ "const": "hermes.skill.load.count"
++ },
++ "type": {
++ "const": "counter"
++ },
++ "dimensions": {
++ "type": "object",
++ "additionalProperties": false,
++ "required": [
++ "post_patch_state",
++ "provenance",
++ "reuse_state",
++ "use_count_bucket"
++ ],
++ "properties": {
++ "post_patch_state": {
++ "enum": [
++ "no_new_patch",
++ "not_applicable",
++ "reused_after_patch"
++ ]
++ },
++ "provenance": {
++ "$ref": "#/$defs/skill_provenance"
++ },
++ "reuse_state": {
++ "enum": [
++ "first_use",
++ "reused"
++ ]
++ },
++ "use_count_bucket": {
++ "$ref": "#/$defs/count_bucket"
++ }
++ }
++ },
++ "value": {
++ "type": "integer",
++ "minimum": 1
++ }
++ }
++ },
++ "skill_provenance": {
++ "enum": [
++ "agent_created",
++ "external",
++ "installed",
++ "local",
++ "unknown"
++ ]
+ }
+ }
+ }
diff --cc hermes_cli/observability/shared_metrics_contract.py
index bf6a3c9468d,870152634f5..0d8d3bbbb4e
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@@ -14,10 -19,9 +19,11 @@@ MODEL_CALL_PROFILE_MODEL = "unknown
TASK_SCOPE = "hermes.task_run"
TOOL_CALL_SCOPE = "hermes.tool_call"
TOOL_APPROVAL_MARK = "hermes.tool_approval"
+SKILL_LIFECYCLE_MARK = "hermes.skill.lifecycle"
+SKILL_LOAD_MARK = "hermes.skill.load"
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"
@@@ -150,30 -152,49 +156,71 @@@ TOOL_LATENCY_BUCKETS: frozenset[str] =
"unknown",
})
TOOL_RETRY_BUCKETS: frozenset[str] = COUNT_BUCKETS | frozenset({"unknown"})
+SKILL_LIFECYCLE_ACTIONS: frozenset[str] = frozenset({
+ "archived",
+ "created",
+ "edited",
+ "installed",
+ "patched",
+ "restored",
+ "stale",
+})
+SKILL_PROVENANCES: frozenset[str] = frozenset({
+ "agent_created",
+ "external",
+ "installed",
+ "local",
+ "unknown",
+})
+SKILL_REUSE_STATES: frozenset[str] = frozenset({"first_use", "reused"})
+SKILL_POST_PATCH_STATES: frozenset[str] = frozenset({
+ "no_new_patch",
+ "not_applicable",
+ "reused_after_patch",
+})
+ _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,
@@@ -200,20 -221,14 +247,26 @@@
"attribution": TOOL_APPROVAL_ATTRIBUTIONS,
"outcome": TOOL_APPROVAL_OUTCOMES - {"not_required"},
},
+ SKILL_LIFECYCLE_METRIC: {
+ "action": SKILL_LIFECYCLE_ACTIONS,
+ "provenance": SKILL_PROVENANCES,
+ },
+ SKILL_LOAD_METRIC: {
+ "post_patch_state": SKILL_POST_PATCH_STATES,
+ "provenance": SKILL_PROVENANCES,
+ "reuse_state": SKILL_REUSE_STATES,
+ "use_count_bucket": COUNT_BUCKETS,
+ },
}
- COUNTER_METRICS: frozenset[str] = frozenset(
- {*_COUNTER_DIMENSION_VALUES, MODEL_CALL_METRIC}
- )
+ COUNTER_METRICS: frozenset[str] = frozenset({
+ MODEL_ROUTE_METRIC,
++ SKILL_LIFECYCLE_METRIC,
++ SKILL_LOAD_METRIC,
+ TASK_FINISHED_METRIC,
+ TASK_STARTED_METRIC,
+ TOOL_APPROVAL_METRIC,
+ TOOL_CALL_METRIC,
+ })
def counter_dimensions_are_valid(
diff --cc hermes_cli/observability/shared_metrics_subscriber.py
index 8ca70804464,086f88d4c23..b1ae16141e6
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@@ -10,10 -10,9 +10,10 @@@ from agent.relay_runtime import RUNTIME
from .shared_metrics import SharedMetricsStore
from .shared_metrics_contract import (
- MODEL_CALL_METRIC,
+ MODEL_ROUTE_METRIC,
TOOL_CALL_METRIC,
model_call_dimensions,
+ skill_counter,
task_counter,
tool_approval_counter,
tool_call_dimensions,
diff --cc scripts/smoke_nemo_relay_shared_metrics.py
index ae3b1ee72c0,64c69bdc3c0..120665b3dd6
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@@ -298,9 -296,7 +298,9 @@@ def _validate_store(database_path: Path
for counter in counters:
by_name.setdefault(counter["name"], []).append(counter)
if set(by_name) != {
- "hermes.model_call.count",
+ "hermes.model_route.count",
+ "hermes.skill.lifecycle.count",
+ "hermes.skill.load.count",
"hermes.task_run.finished",
"hermes.task_run.started",
"hermes.tool_call.count",
@@@ -444,33 -394,25 +444,28 @@@ def _validate_packages
f"Exported package leaked prohibited value: {prohibited!r}"
)
metrics: dict[str, list[dict[str, Any]]] = {}
- for metric in package.get("metrics", []):
- metrics.setdefault(metric["name"], []).append(metric)
+ for package in packages:
+ for metric in package.get("metrics", []):
+ metrics.setdefault(metric["name"], []).append(metric)
if set(metrics) != {
- "hermes.model_call.count",
+ "hermes.model_route.count",
+ "hermes.skill.lifecycle.count",
+ "hermes.skill.load.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)}"
+ f"Unexpected package metrics:\n{json.dumps(metrics, indent=2)}"
)
- models = metrics["hermes.model_call.count"]
- if (
- sum(metric["value"] for metric in models) != 2
- or any(
- metric["dimensions"]
- != {
- "model": MODEL_CANARY,
- "provider": "custom",
- }
- for metric in models
+ [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_route.count']}"
)
- ):
- raise AssertionError(f"Unexpected model metrics: {models}")
[terminal] = metrics["hermes.task_run.finished"]
if terminal["dimensions"] != {
"duration_bucket": terminal["dimensions"].get("duration_bucket"),
diff --cc tests/agent/test_skill_commands.py
index 325711ce262,54c91bcc5e5..28f683086d5
--- a/tests/agent/test_skill_commands.py
+++ b/tests/agent/test_skill_commands.py
@@@ -516,34 -333,6 +333,24 @@@ class TestBuildPreloadedSkillsPrompt
assert "second-skill" in prompt
assert "preloaded" in prompt.lower()
+ def test_forwards_task_id_to_skill_usage(self, tmp_path):
+ with (
+ patch("tools.skills_tool.SKILLS_DIR", tmp_path),
+ patch("tools.skill_usage.bump_use") as bump_use,
+ ):
+ _make_skill(tmp_path, "preloaded-skill")
+ _prompt, loaded, missing = build_preloaded_skills_prompt(
+ ["preloaded-skill"],
+ task_id="task-preloaded",
+ )
+
+ assert loaded == ["preloaded-skill"]
+ assert missing == []
+ bump_use.assert_called_once_with(
+ "preloaded-skill",
+ task_id="task-preloaded",
+ )
+
- def test_reports_missing_named_skills(self, tmp_path):
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- _make_skill(tmp_path, "present-skill")
- prompt, loaded, missing = build_preloaded_skills_prompt(
- ["present-skill", "missing-skill"]
- )
-
- assert "present-skill" in prompt
- assert loaded == ["present-skill"]
- assert missing == ["missing-skill"]
def test_skips_disabled_skill(self, tmp_path, monkeypatch):
"""A globally-disabled skill must not be force-loaded via -s /
@@@ -569,82 -358,9 +376,24 @@@
class TestBuildSkillInvocationMessage:
- def test_loads_skill_by_stored_path_when_frontmatter_name_differs(self, tmp_path):
- skill_dir = tmp_path / "mlops" / "audiocraft"
- skill_dir.mkdir(parents=True, exist_ok=True)
- (skill_dir / "SKILL.md").write_text(
- """\
- ---
- name: audiocraft-audio-generation
- description: Generate audio with AudioCraft.
- ---
- # AudioCraft
- Generate some audio.
- """
- )
-
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- scan_skill_commands()
- msg = build_skill_invocation_message("/audiocraft-audio-generation", "compose")
-
- assert msg is not None
- assert "AudioCraft" in msg
- assert "compose" in msg
-
- def test_builds_message(self, tmp_path):
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- _make_skill(tmp_path, "test-skill")
- scan_skill_commands()
- msg = build_skill_invocation_message("/test-skill", "do stuff")
- assert msg is not None
- assert "test-skill" in msg
- assert "do stuff" in msg
+ def test_forwards_task_id_to_skill_usage(self, tmp_path):
+ with (
+ patch("tools.skills_tool.SKILLS_DIR", tmp_path),
+ patch("tools.skill_usage.bump_use") as bump_use,
+ ):
+ _make_skill(tmp_path, "test-skill")
+ scan_skill_commands()
+ msg = build_skill_invocation_message(
+ "/test-skill",
+ task_id="task-slash",
+ )
+
+ assert msg is not None
+ bump_use.assert_called_once_with("test-skill", task_id="task-slash")
+
- def test_returns_none_for_unknown(self, tmp_path):
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- scan_skill_commands()
- msg = build_skill_invocation_message("/nonexistent")
- assert msg is None
-
- def test_returns_none_when_skill_load_fails(self, tmp_path):
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- _make_skill(tmp_path, "broken-skill")
- scan_skill_commands()
- with patch("agent.skill_commands._load_skill_payload", return_value=None):
- msg = build_skill_invocation_message("/broken-skill", "do stuff")
- assert msg is None
def test_uses_shared_skill_loader_for_secure_setup(self, tmp_path, monkeypatch):
monkeypatch.delenv("TENOR_API_KEY", raising=False)
@@@ -1015,58 -618,8 +651,32 @@@ class TestStackedSkillCommands
assert len(keys) == 4
assert instruction.startswith("/stk-5")
- def test_split_dedupes_repeated_skill(self, tmp_path):
- from agent.skill_commands import split_stacked_skill_commands
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- self._setup_three_skills(tmp_path)
- scan_skill_commands()
- keys, instruction = split_stacked_skill_commands(
- "/skill-b /skill-b go"
- )
- # The duplicate stops parsing (treated as instruction text).
- assert keys == ["/skill-b"]
- assert instruction == "/skill-b go"
- def test_stacked_message_contains_all_bodies_and_instruction(self, tmp_path):
- from agent.skill_commands import build_stacked_skill_invocation_message
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- self._setup_three_skills(tmp_path)
- scan_skill_commands()
- result = build_stacked_skill_invocation_message(
- ["/skill-a", "/skill-b"], "do the thing"
- )
- assert result is not None
- msg, loaded, missing = result
- assert loaded == ["skill-a", "skill-b"]
- assert missing == []
- assert "Body A." in msg
- assert "Body B." in msg
- assert "User instruction: do the thing" in msg
+ def test_stacked_message_forwards_task_id_to_each_skill(self, tmp_path):
+ from agent.skill_commands import build_stacked_skill_invocation_message
+
+ with (
+ patch("tools.skills_tool.SKILLS_DIR", tmp_path),
+ patch("tools.skill_usage.bump_use") as bump_use,
+ ):
+ self._setup_three_skills(tmp_path)
+ scan_skill_commands()
+ result = build_stacked_skill_invocation_message(
+ ["/skill-a", "/skill-b"],
+ task_id="task-stacked",
+ )
+
+ assert result is not None
+ assert [call.args[0] for call in bump_use.call_args_list] == [
+ "skill-a",
+ "skill-b",
+ ]
+ assert all(
+ call.kwargs == {"task_id": "task-stacked"}
+ for call in bump_use.call_args_list
+ )
+
def test_stacked_message_skips_missing_skills(self, tmp_path):
from agent.skill_commands import build_stacked_skill_invocation_message
with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
@@@ -1080,42 -633,6 +690,3 @@@
assert loaded == ["skill-a"]
assert missing == ["gone"]
assert "Skills missing (skipped): gone" in msg
--
- def test_stacked_message_none_when_nothing_loads(self, tmp_path):
- from agent.skill_commands import build_stacked_skill_invocation_message
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- scan_skill_commands()
- result = build_stacked_skill_invocation_message(["/gone"], "go")
- assert result is None
--
- def test_memory_extractor_recovers_instruction_from_stacked_turn(self, tmp_path):
- """The stacked scaffolding reuses bundle markers so memory providers
- recover the user's instruction, not N skill bodies."""
- from agent.skill_commands import (
- build_stacked_skill_invocation_message,
- extract_user_instruction_from_skill_message,
- )
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- self._setup_three_skills(tmp_path)
- scan_skill_commands()
- result = build_stacked_skill_invocation_message(
- ["/skill-a", "/skill-b"], "summarize the repo"
- )
- assert result is not None
- msg, _, _ = result
- assert extract_user_instruction_from_skill_message(msg) == "summarize the repo"
--
- def test_memory_extractor_returns_none_for_bare_stacked_turn(self, tmp_path):
- from agent.skill_commands import (
- build_stacked_skill_invocation_message,
- extract_user_instruction_from_skill_message,
- )
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- self._setup_three_skills(tmp_path)
- scan_skill_commands()
- result = build_stacked_skill_invocation_message(
- ["/skill-a", "/skill-b"], ""
- )
- assert result is not None
- msg, _, _ = result
- assert extract_user_instruction_from_skill_message(msg) is None
diff --cc tests/cron/test_scheduler.py
index a075a71e01d,3b91c135798..58572dbd4a8
--- a/tests/cron/test_scheduler.py
+++ b/tests/cron/test_scheduler.py
@@@ -3740,597 -909,405 +909,413 @@@ class TestSilentDelivery
"origin": {"platform": "telegram", "chat_id": "123"},
}
- standalone_send = AsyncMock(return_value={"success": True})
-
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro), \
- patch("tools.send_message_tool._send_to_platform", new=standalone_send):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
-
- # 1. cancel() was attempted (returned False = in flight).
- assert cancel_calls == [True], "future.cancel() should be attempted on TimeoutError"
- # 2. Delivery is reported successful (no error string returned).
- assert result is None, f"expected successful delivery, got error: {result!r}"
- # 3. The standalone fallback must NOT run — that is the #38922 fix:
- # an in-flight confirmation timeout is assume-delivered, not a resend.
- standalone_send.assert_not_awaited()
-
- def test_live_adapter_timeout_before_dispatch_falls_back_to_standalone(self):
- """When the coroutine never started (loop wedged) — future.cancel()
- returns True — nothing was sent, so _deliver_result MUST fall through
- to the standalone path rather than silently dropping the message.
- This is the inverse of the assume-delivered case and guards against the
- wedged-loop silent drop."""
- from gateway.config import Platform
- from concurrent.futures import Future
-
- adapter = AsyncMock()
- adapter.send.return_value = MagicMock(success=True)
-
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
-
- loop = MagicMock()
- loop.is_running.return_value = True
-
- captured_future = Future()
- cancel_calls = []
-
- def never_dispatched_cancel():
- cancel_calls.append(True)
- return True # callback never ran — successfully cancelled
-
- captured_future.cancel = never_dispatched_cancel
- captured_future.result = MagicMock(side_effect=TimeoutError("timed out"))
-
- def fake_run_coro(coro, _loop):
- coro.close()
- return captured_future
-
- job = {
- "id": "timeout-undispatched-job",
- "deliver": "origin",
- "origin": {"platform": "telegram", "chat_id": "123"},
- }
+ def test_silent_response_suppresses_delivery(self, caplog):
+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \
+ patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT]", None)), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result") as deliver_mock, \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ with caplog.at_level(logging.INFO, logger="cron.scheduler"):
+ tick(verbose=False)
+ deliver_mock.assert_not_called()
+ assert any(SILENT_MARKER in r.message for r in caplog.records)
- standalone_send = AsyncMock(return_value={"success": True})
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro), \
- patch("tools.send_message_tool._send_to_platform", new=standalone_send):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ def test_report_quoting_marker_mid_sentence_still_delivers(self):
+ """A genuine report that merely mentions the token mid-sentence must
+ be delivered — the old substring check wrongly swallowed it."""
+ response = "I considered staying [SILENT] but here is the summary: 3 items merged."
+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \
+ patch("cron.scheduler.run_job", return_value=(True, "# output", response, None)), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result") as deliver_mock, \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ tick(verbose=False)
+ deliver_mock.assert_called_once()
- assert cancel_calls == [True], "future.cancel() should be attempted"
- # The standalone path MUST run — the message was never sent.
- standalone_send.assert_awaited_once()
- assert result is None, f"standalone should have delivered, got: {result!r}"
- def test_live_adapter_real_exception_falls_back_to_standalone(self):
- """A non-timeout send Exception (real failure, not a slow confirmation)
- must fall through to the standalone path so the message is still
- delivered. Guards the `except Exception: raise` branch — the bug class
- where broadening the timeout handler to swallow all exceptions would
- silently drop messages."""
- from gateway.config import Platform
- from concurrent.futures import Future
+ def test_failed_job_always_delivers(self):
+ """Failed jobs deliver regardless of [SILENT] in output."""
+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \
+ patch("cron.scheduler.run_job", return_value=(False, "# output", "", "some error")), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result") as deliver_mock, \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ tick(verbose=False)
+ deliver_mock.assert_called_once()
- adapter = AsyncMock()
- adapter.send.return_value = MagicMock(success=True)
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
+ def test_whitespace_only_response_is_marked_failed_not_delivered(self):
+ """Whitespace-only final responses should behave like empty responses."""
+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \
+ patch("cron.scheduler.run_job", return_value=(True, "# output", " \n\t ", None)), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result") as deliver_mock, \
+ patch("cron.scheduler.mark_job_run") as mark_mock:
+ from cron.scheduler import tick
+ tick(verbose=False)
- loop = MagicMock()
- loop.is_running.return_value = True
+ deliver_mock.assert_not_called()
+ mark_mock.assert_called_once_with(
+ "monitor-job",
+ False,
+ "Agent completed but produced empty response (model error, timeout, or misconfiguration)",
+ delivery_error=None,
+ )
- captured_future = Future()
- captured_future.result = MagicMock(side_effect=RuntimeError("adapter exploded"))
- def fake_run_coro(coro, _loop):
- coro.close()
- return captured_future
+ class TestOneShotDispatchClaim:
+ """run_one_job must claim a finite one-shot's dispatch BEFORE run_job so a
+ tick that dies mid-execution can't re-fire it forever (issue #38758)."""
- job = {
- "id": "send-error-job",
+ def _oneshot(self):
+ return {
+ "id": "monitor-job",
+ "name": "monitor",
"deliver": "origin",
"origin": {"platform": "telegram", "chat_id": "123"},
+ "schedule": {"kind": "once", "run_at": "2026-01-01T00:00:00+00:00"},
+ "repeat": {"times": 1, "completed": 0},
}
- standalone_send = AsyncMock(return_value={"success": True})
-
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro), \
- patch("tools.send_message_tool._send_to_platform", new=standalone_send):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
-
- # A real exception must NOT be assume-delivered: standalone runs.
- standalone_send.assert_awaited_once()
- assert result is None, f"standalone should have delivered, got: {result!r}"
-
- def test_live_adapter_forum_topic_in_private_chat_routes_via_message_thread_id(self):
- """#52060: a cron target to a PRIVATE Telegram chat with a numeric topic
- id is a normal forum-style topic — it must route via ``message_thread_id``,
- NOT ``direct_messages_topic_id``. The #22773 heuristic inferred a Bot API
- channel DM topic from positive chat_id + numeric thread and nulled
- ``message_thread_id``, so deliveries landed in General. We now probe the
- live adapter's ``get_chat_info``; a non-channel chat routes via
- ``message_thread_id``.
- """
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
-
- send_result = SendResult(success=True, message_id="42")
-
- class _ForumAdapter(MagicMock):
- async def get_chat_info(self, chat_id):
- return {"name": "Proyectos", "type": "forum", "is_forum": True}
-
- adapter = _ForumAdapter()
- adapter.send = AsyncMock(return_value=send_result)
-
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
-
- loop = MagicMock()
- loop.is_running.return_value = True
-
- job = {
- "id": "forum-topic-job",
- "deliver": "telegram:226252250:7072", # private chat + numeric forum topic
- }
+ def test_claim_runs_before_run_job(self):
+ order = []
+ with patch("cron.scheduler.get_due_jobs", return_value=[self._oneshot()]), \
+ patch("cron.scheduler.claim_dispatch", side_effect=lambda _id: order.append("claim") or True), \
+ patch("cron.scheduler.run_job", side_effect=lambda _j, **_kw: order.append("run") or (True, "# out", "ok", None)), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result"), \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ tick(verbose=False)
+ assert order == ["claim", "run"] # claim strictly before side effect
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ class TestBuildJobPromptSilentHint:
+ """Verify _build_job_prompt always injects [SILENT] guidance."""
- assert result is None, f"expected clean delivery, got: {result!r}"
- adapter.send.assert_called_once()
- sent_chat_id, sent_text = adapter.send.call_args[0][0], adapter.send.call_args[0][1]
- sent_metadata = adapter.send.call_args[1]["metadata"]
- assert sent_chat_id == "226252250"
- assert sent_text == "Hello world"
- # Forum topics route via message_thread_id (thread_id in metadata), NOT
- # direct_messages_topic_id.
- assert not sent_metadata.get("direct_messages_topic_id")
- assert str(sent_metadata.get("thread_id")) == "7072"
-
- def test_live_adapter_ambiguous_topic_probe_failure_falls_back_to_message_thread_id(self):
- """Fail SAFE: when the ``get_chat_info`` probe cannot resolve the chat
- type (adapter with no usable probe / raising probe), an ambiguous
- private-chat topic target defaults to ``message_thread_id`` — the common
- forum-topic case and pre-#22773 behaviour, never the DM-topic route.
- """
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
+ def test_hint_always_present(self):
+ job = {"prompt": "Check for updates"}
+ result = _build_job_prompt(job)
+ assert "[SILENT]" in result
+ assert "Check for updates" in result
- send_result = SendResult(success=True, message_id="42")
- # Plain MagicMock: its auto-created get_chat_info returns a MagicMock,
- # not an awaitable, so the scheduled coroutine raises and the probe
- # fails closed to message_thread_id.
- adapter = MagicMock()
- adapter.send = AsyncMock(return_value=send_result)
+ class TestParseWakeGate:
+ """Unit tests for _parse_wake_gate — pure function, no side effects."""
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ def test_empty_output_wakes(self):
+ from cron.scheduler import _parse_wake_gate
+ assert _parse_wake_gate("") is True
+ assert _parse_wake_gate(None) is True
- loop = MagicMock()
- loop.is_running.return_value = True
- job = {
- "id": "probe-fail-job",
- "deliver": "telegram:226252250:7072",
- }
+ def test_wake_gate_false_skips(self):
+ from cron.scheduler import _parse_wake_gate
+ assert _parse_wake_gate('{"wakeAgent": false}') is False
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ class TestRunJobWakeGate:
+ """Integration tests for run_job wake-gate short-circuit."""
- assert result is None, f"expected clean delivery, got: {result!r}"
- adapter.send.assert_called_once()
- sent_metadata = adapter.send.call_args[1]["metadata"]
- assert not sent_metadata.get("direct_messages_topic_id")
- assert str(sent_metadata.get("thread_id")) == "7072"
-
- def test_live_adapter_probe_returns_none_falls_back_to_message_thread_id(self):
- """Fail SAFE when the probe yields a non-dict result. A relay/proxy
- adapter (or a future ``get_chat_info`` variant) may return ``None``
- rather than a dict; the ``isinstance(info, dict)`` guard must still route
- via ``message_thread_id``, distinct from the raising-probe path.
-
- (The real Telegram adapter returns a dict on every path — a
- ``type="dm"`` dict with an ``error`` key on failure, covered separately
- by ``..._adapter_error_dict_falls_back...`` — never ``None``. This test
- locks the non-dict defensive branch for other adapters.)"""
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
+ @pytest.fixture(autouse=True)
+ def _stub_runtime_provider(self):
+ """Stub ``resolve_runtime_provider`` for wake-gate tests.
- send_result = SendResult(success=True, message_id="42")
+ ``run_job`` resolves the runtime provider BEFORE constructing
+ ``AIAgent``, so these tests must mock ``resolve_runtime_provider``
+ in addition to ``AIAgent`` — otherwise in a hermetic CI env (no
+ API keys), the resolver raises and the test fails before the
+ patched AIAgent is ever reached.
+ """
+ fake_runtime = {
+ "provider": "openrouter",
+ "api_mode": "chat_completions",
+ "base_url": "https://openrouter.ai/api/v1",
+ "api_key": "test-key",
+ "source": "stub",
+ "requested_provider": None,
+ }
+ with patch(
+ "hermes_cli.runtime_provider.resolve_runtime_provider",
+ return_value=fake_runtime,
+ ):
+ yield
- class _NoneProbeAdapter(MagicMock):
- async def get_chat_info(self, chat_id):
- return None
+ def _make_job(self, name="wake-gate-test", script="check.py"):
+ """Minimal valid cron job dict for run_job."""
+ return {
+ "id": f"job_{name}",
+ "name": name,
+ "prompt": "Do a thing",
+ "schedule": "*/5 * * * *",
+ "script": script,
+ }
- adapter = _NoneProbeAdapter()
- adapter.send = AsyncMock(return_value=send_result)
+ def test_wake_false_skips_agent_and_returns_silent(self, caplog):
+ """When _run_job_script output ends with {wakeAgent: false}, the agent
+ is not invoked and run_job returns the SILENT marker so delivery is
+ suppressed."""
+ from cron.scheduler import SILENT_MARKER
+ import cron.scheduler as scheduler
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ with patch.object(scheduler, "_run_job_script",
+ return_value=(True, '{"wakeAgent": false}')), \
+ patch("run_agent.AIAgent") as agent_cls:
+ success, doc, final, err = scheduler.run_job(self._make_job())
- loop = MagicMock()
- loop.is_running.return_value = True
+ assert success is True
+ assert err is None
+ assert final == SILENT_MARKER
+ assert "Script gate returned `wakeAgent=false`" in doc
+ agent_cls.assert_not_called()
- job = {
- "id": "none-probe-job",
- "deliver": "telegram:226252250:7072",
- }
+ def test_wake_true_runs_agent_with_injected_output(self):
+ """When the script returns {wakeAgent: true, data: ...}, the agent is
+ invoked and the data line still shows up in the prompt."""
+ import cron.scheduler as scheduler
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
+ script_output = '{"wakeAgent": true, "data": {"new": 3}}'
+ agent = MagicMock()
+ agent.run_conversation = MagicMock(return_value={
+ "final_response": "ok", "messages": []
+ })
+ with patch.object(scheduler, "_run_job_script",
+ return_value=(True, script_output)), \
+ patch("run_agent.AIAgent", return_value=agent) as agent_cls:
+ success, doc, final, err = scheduler.run_job(self._make_job())
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ agent_cls.assert_called_once()
+ # The script output should be visible in the prompt passed to
+ # run_conversation.
+ call_kwargs = agent.run_conversation.call_args
+ prompt_arg = call_kwargs.args[0] if call_kwargs.args else call_kwargs.kwargs.get("user_message", "")
+ assert script_output in prompt_arg
+ assert success is True
+ assert err is None
- assert result is None, f"expected clean delivery, got: {result!r}"
- adapter.send.assert_called_once()
- sent_metadata = adapter.send.call_args[1]["metadata"]
- assert not sent_metadata.get("direct_messages_topic_id")
- assert str(sent_metadata.get("thread_id")) == "7072"
-
- def test_live_adapter_error_dict_falls_back_to_message_thread_id(self):
- """Fail SAFE on the REAL Telegram adapter error contract: on a failed
- ``get_chat.get_chat`` the adapter returns ``{"type": "dm", "error": ...}``
- (plugins/platforms/telegram/adapter.py::get_chat_info), NOT ``None`` and
- NOT a raise. A ``type="dm"`` (or bot-missing ``{"type": "dm"}``) result
- must route via ``message_thread_id`` — only a genuine ``type="channel"``
- gets ``direct_messages_topic_id``. This locks the exact dict shape
- production emits so a forum-topic cron never mis-routes to General."""
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
- send_result = SendResult(success=True, message_id="42")
+ class TestBuildJobPromptMissingSkill:
+ """Verify that a missing skill logs a warning and does not crash the job."""
- class _ErrorDictAdapter(MagicMock):
- async def get_chat_info(self, chat_id):
- # Mirrors the real adapter's except-branch return shape.
- return {"name": str(chat_id), "type": "dm", "error": "Chat not found"}
+ def _missing_skill_view(self, name: str) -> str:
+ return json.dumps({"success": False, "error": f"Skill '{name}' not found."})
- adapter = _ErrorDictAdapter()
- adapter.send = AsyncMock(return_value=send_result)
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ def test_missing_skill_injects_user_notice_into_prompt(self):
+ """A system notice about the missing skill is injected into the prompt."""
+ with patch("tools.skills_tool.skill_view", side_effect=self._missing_skill_view):
+ result = _build_job_prompt({"skills": ["ghost-skill"], "prompt": "do something"})
+ assert "ghost-skill" in result
+ assert "not found" in result.lower() or "skipped" in result.lower()
- loop = MagicMock()
- loop.is_running.return_value = True
- job = {
- "id": "error-dict-job",
- "deliver": "telegram:226252250:7072",
- }
+ class TestBuildJobPromptAbsoluteSkillPath:
+ """Cron jobs may store absolute skill paths; normalize before skill_view."""
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
+ def test_absolute_skill_path_normalized_before_skill_view(self, tmp_path):
+ skills_dir = tmp_path / "skills"
+ skill_dir = skills_dir / "alpha-skill"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text("# Alpha\nDo alpha.")
+ absolute_path = str(skill_dir)
+ seen_names: list[str] = []
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ def _skill_view(name: str) -> str:
+ seen_names.append(name)
+ if name == "alpha-skill":
+ return json.dumps({"success": True, "content": "# Alpha\nDo alpha."})
+ return json.dumps({"success": False, "error": f"Skill '{name}' not found."})
- assert result is None, f"expected clean delivery, got: {result!r}"
- adapter.send.assert_called_once()
- sent_metadata = adapter.send.call_args[1]["metadata"]
- assert not sent_metadata.get("direct_messages_topic_id")
- assert str(sent_metadata.get("thread_id")) == "7072"
-
- def test_live_adapter_channel_dm_topic_routes_via_direct_messages_topic_id(self):
- """#22773 (done right): a genuine Bot API 10.0 *channel* Direct-Messages
- topic must be routed via ``direct_messages_topic_id`` (a bare
- ``message_thread_id`` is rejected / mis-routed there). We recognise it
- from the real runtime signal — ``get_chat_info`` reports the chat as a
- ``channel`` — not from a positive-chat-id + numeric-thread guess.
- """
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
+ with patch("tools.skills_tool.SKILLS_DIR", skills_dir), \
+ patch("tools.skills_tool.skill_view", side_effect=_skill_view):
+ result = _build_job_prompt({"skills": [absolute_path], "prompt": "go"})
- send_result = SendResult(success=True, message_id="42")
+ assert seen_names == ["alpha-skill"]
+ assert "Do alpha." in result
- class _ChannelAdapter(MagicMock):
- async def get_chat_info(self, chat_id):
- return {"name": "My Channel", "type": "channel", "is_forum": False}
- adapter = _ChannelAdapter()
- adapter.send = AsyncMock(return_value=send_result)
+ class TestBuildJobPromptBumpUse:
+ """Verify that cron jobs bump skill usage counters so the curator sees them as active."""
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ def test_bump_use_called_for_loaded_skill(self):
+ """bump_use is called for each successfully loaded skill."""
- loop = MagicMock()
- loop.is_running.return_value = True
+ def _skill_view(name: str) -> str:
+ return json.dumps({"success": True, "content": f"Content for {name}."})
- job = {
- "id": "channel-dm-topic-job",
- "deliver": "telegram:226252250:7072",
- }
+ with patch("tools.skills_tool.skill_view", side_effect=_skill_view), \
+ patch("tools.skill_usage.bump_use") as mock_bump:
- _build_job_prompt({"skills": ["alpha", "beta"], "prompt": "go"})
++ _build_job_prompt({
++ "id": "cron-task",
++ "skills": ["alpha", "beta"],
++ "prompt": "go",
++ })
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
+ assert mock_bump.call_count == 2
+ calls = [c[0][0] for c in mock_bump.call_args_list]
+ assert "alpha" in calls
+ assert "beta" in calls
++ assert all(
++ call.kwargs == {"task_id": "cron-task"}
++ for call in mock_bump.call_args_list
++ )
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- result = _deliver_result(
- job,
- "Hello world",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
- assert result is None, f"expected clean delivery, got: {result!r}"
- adapter.send.assert_called_once()
- sent_metadata = adapter.send.call_args[1]["metadata"]
- # Genuine channel DM topic routes via direct_messages_topic_id, no bare
- # message_thread_id.
- assert str(sent_metadata.get("direct_messages_topic_id")) == "7072"
- assert not sent_metadata.get("message_thread_id")
-
- def test_live_adapter_forum_topic_media_routes_via_message_thread_id(self, tmp_path, monkeypatch):
- """#52060 (media): MEDIA attachments to a forum-style topic in a private
- chat must also route via ``thread_id`` (message_thread_id), not
- ``direct_messages_topic_id``."""
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
+ class TestSendMediaViaAdapter:
+ """Unit tests for _send_media_via_adapter — routes files to typed adapter methods."""
- media_root = tmp_path / "media-cache"
- media_file = media_root / "chart.png"
+ def _safe_media_path(self, tmp_path, monkeypatch, name, data=b"media"):
+ root = tmp_path / "media-cache"
+ media_file = root / name
media_file.parent.mkdir(parents=True, exist_ok=True)
- media_file.write_bytes(b"media")
+ media_file.write_bytes(data)
monkeypatch.setattr(
"gateway.platforms.base.MEDIA_DELIVERY_SAFE_ROOTS",
- (media_root,),
+ (root,),
)
- media_path = media_file.resolve()
-
- probe_calls = {"n": 0}
+ return media_file.resolve()
- class _ForumAdapter(AsyncMock):
- async def get_chat_info(self, chat_id):
- probe_calls["n"] += 1
- return {"name": "Proyectos", "type": "forum", "is_forum": True}
+ @staticmethod
+ def _run_with_loop(adapter, chat_id, media_files, metadata, job):
+ """Helper: run _send_media_via_adapter with immediate scheduling."""
+ from concurrent.futures import Future
- adapter = _ForumAdapter()
- adapter.send.return_value = SendResult(success=True, message_id="1")
- adapter.send_image_file.return_value = SendResult(success=True, message_id="2")
+ def fake_run_coro(coro, _loop):
+ coro.close()
+ completed = Future()
+ completed.set_result(MagicMock(success=True))
+ return completed
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ with patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
+ _send_media_via_adapter(adapter, chat_id, media_files, metadata, MagicMock(), job)
- loop = MagicMock()
- loop.is_running.return_value = True
- job = {
- "id": "forum-topic-media-job",
- "deliver": "telegram:226252250:7072", # private chat + numeric forum topic
- }
+ def test_multiple_media_files_all_delivered(self, tmp_path, monkeypatch):
+ adapter = MagicMock()
+ adapter.send_voice = AsyncMock()
+ adapter.send_image_file = AsyncMock()
+ voice_path = self._safe_media_path(tmp_path, monkeypatch, "voice.mp3")
+ photo_path = self._safe_media_path(tmp_path, monkeypatch, "photo.jpg")
+ media_files = [(str(voice_path), False), (str(photo_path), False)]
+ self._run_with_loop(adapter, "123", media_files, None, {"id": "j3"})
+ adapter.send_voice.assert_called_once()
+ adapter.send_image_file.assert_called_once()
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- _deliver_result(
- job,
- f"Chart attached\nMEDIA:{media_path}",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
- )
+ class TestParallelTick:
+ """Verify that tick() runs due jobs concurrently and isolates ContextVars."""
- adapter.send_image_file.assert_called_once()
- media_metadata = adapter.send_image_file.call_args[1]["metadata"]
- assert str(media_metadata.get("thread_id")) == "7072"
- assert not media_metadata.get("direct_messages_topic_id")
- # Probe exactly once and reuse the result for BOTH the text and media
- # sends — never re-probe per send (the "compute ONCE" contract).
- assert probe_calls["n"] == 1
-
- def test_live_adapter_channel_dm_topic_media_routes_via_direct_messages_topic_id(self, tmp_path, monkeypatch):
- """#22773 (media, done right): MEDIA attachments to a genuine channel DM
- topic must route via ``direct_messages_topic_id``."""
- from gateway.config import Platform
- from gateway.platforms.base import SendResult
- from concurrent.futures import Future
+ @pytest.fixture(autouse=True)
+ def _isolate_tick_lock(self, tmp_path):
+ """Point the tick file lock at a per-test temp dir to avoid xdist contention."""
+ lock_dir = tmp_path / "cron"
+ lock_dir.mkdir()
+ lock_file = lock_dir / ".tick.lock"
+ with patch("cron.scheduler._get_lock_paths", return_value=(lock_dir, lock_file)):
+ yield
- media_root = tmp_path / "media-cache"
- media_file = media_root / "chart.png"
- media_file.parent.mkdir(parents=True, exist_ok=True)
- media_file.write_bytes(b"media")
- monkeypatch.setattr(
- "gateway.platforms.base.MEDIA_DELIVERY_SAFE_ROOTS",
- (media_root,),
- )
- media_path = media_file.resolve()
+ def test_parallel_jobs_run_concurrently(self):
+ """Two jobs launched in the same tick should overlap in time."""
+ import threading
- class _ChannelAdapter(AsyncMock):
- async def get_chat_info(self, chat_id):
- return {"name": "My Channel", "type": "channel", "is_forum": False}
+ barrier = threading.Barrier(2, timeout=5)
+ call_order = []
- adapter = _ChannelAdapter()
- adapter.send.return_value = SendResult(success=True, message_id="1")
- adapter.send_image_file.return_value = SendResult(success=True, message_id="2")
+ def mock_run_job(job, *, defer_agent_teardown=None):
+ """Each job hits a barrier — both must be active simultaneously."""
+ call_order.append(("start", job["id"]))
+ barrier.wait() # blocks until both threads reach here
+ call_order.append(("end", job["id"]))
+ return (True, "output", "response", None)
- pconfig = MagicMock()
- pconfig.enabled = True
- mock_cfg = MagicMock()
- mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
- mock_cfg.filter_silence_narration = False
+ jobs = [
+ {"id": "job-a", "name": "a", "deliver": "local"},
+ {"id": "job-b", "name": "b", "deliver": "local"},
+ ]
- loop = MagicMock()
- loop.is_running.return_value = True
+ with patch("cron.scheduler.get_due_jobs", return_value=jobs), \
+ patch("cron.scheduler.advance_next_run"), \
+ patch("cron.scheduler.run_job", side_effect=mock_run_job), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result", return_value=None), \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ result = tick(verbose=False)
- job = {
- "id": "channel-dm-topic-media-job",
- "deliver": "telegram:226252250:7072",
- }
+ assert result == 2
+ # Both starts happened before both ends — proof of concurrency
+ starts = [i for i, (action, _) in enumerate(call_order) if action == "start"]
+ ends = [i for i, (action, _) in enumerate(call_order) if action == "end"]
+ assert len(starts) == 2
+ assert len(ends) == 2
+ assert max(starts) < min(ends), f"Jobs not concurrent: {call_order}"
- def fake_run_coro(coro, _loop):
- import asyncio as _asyncio
- future = Future()
- try:
- future.set_result(_asyncio.run(coro))
- except BaseException as _e: # noqa: BLE001
- future.set_exception(_e)
- return future
+ def test_parallel_jobs_isolated_contextvars(self):
+ """Each job's ContextVars must be isolated — no cross-contamination."""
+ from gateway.session_context import get_session_env
+ seen = {}
- with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
- patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
- patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):
- _deliver_result(
- job,
- f"Chart attached\nMEDIA:{media_path}",
- adapters={Platform.TELEGRAM: adapter},
- loop=loop,
+ def mock_run_job(job, *, defer_agent_teardown=None):
+ origin = job.get("origin", {})
+ # run_job sets ContextVars — verify each job sees its own
+ from gateway.session_context import set_session_vars, clear_session_vars
+ tokens = set_session_vars(
+ platform=origin.get("platform", ""),
+ chat_id=str(origin.get("chat_id", "")),
)
+ import time
+ time.sleep(0.05) # give other thread time to set its vars
+ platform = get_session_env("HERMES_SESSION_PLATFORM")
+ chat_id = get_session_env("HERMES_SESSION_CHAT_ID")
+ seen[job["id"]] = {"platform": platform, "chat_id": chat_id}
+ clear_session_vars(tokens)
+ return (True, "output", "response", None)
- adapter.send_image_file.assert_called_once()
- media_metadata = adapter.send_image_file.call_args[1]["metadata"]
- assert str(media_metadata.get("direct_messages_topic_id")) == "7072"
- assert not media_metadata.get("message_thread_id")
- assert not media_metadata.get("thread_id")
-
- def test_live_adapter_forum_thread_fallback_records_delivery_error(self):
- """A forum/supergroup cron target whose configured topic is gone must
- NOT be reported as a clean delivery: when the Telegram adapter falls
- back to the base chat (raw_response thread_fallback), the scheduler must
- record the "delivered without thread_id" delivery error. Regression
- coverage for the thread_fallback-recording branch (kept distinct from
- the #22773 routing fix)."""
+ jobs = [
+ {"id": "tg-job", "name": "tg", "deliver": "local",
+ "origin": {"platform": "telegram", "chat_id": "111"}},
+ {"id": "dc-job", "name": "dc", "deliver": "local",
+ "origin": {"platform": "discord", "chat_id": "222"}},
+ ]
+
+ with patch("cron.scheduler.get_due_jobs", return_value=jobs), \
+ patch("cron.scheduler.advance_next_run"), \
+ patch("cron.scheduler.run_job", side_effect=mock_run_job), \
+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
+ patch("cron.scheduler._deliver_result", return_value=None), \
+ patch("cron.scheduler.mark_job_run"):
+ from cron.scheduler import tick
+ tick(verbose=False)
+
+ assert seen["tg-job"] == {"platform": "telegram", "chat_id": "111"}
+ assert seen["dc-job"] == {"platform": "discord", "chat_id": "222"}
+
+
+ class TestDeliverResultTimeoutCancelsFuture:
+ """When future.result(timeout=60) raises TimeoutError in the live adapter
+ delivery path, the outcome depends on whether the coroutine was already
+ running. future.cancel() returning False means it is in flight on the wire
+ (cannot be un-sent) → treat as DELIVERED and skip the standalone fallback to
+ avoid a duplicate (#38922). future.cancel() returning True means it never
+ started (wedged loop) → nothing was sent, so fall through to standalone or
+ the message is silently dropped. Regression for #38922.
+ """
+
+ def test_live_adapter_timeout_assumes_delivered_no_duplicate(self):
+ """End-to-end: live adapter confirmation times out past the 60s budget.
+ The fix (#38922) treats the send as already-dispatched/delivered and
+ does NOT run the standalone fallback — otherwise the message is sent
+ twice."""
from gateway.config import Platform
- from gateway.platforms.base import SendResult
from concurrent.futures import Future
- send_result = SendResult(
- success=True,
- message_id="42",
- raw_response={
- "requested_thread_id": 17,
- "thread_fallback": True,
- },
- )
- adapter = MagicMock()
- adapter.send = AsyncMock(return_value=send_result)
+ # Live adapter whose send() coroutine never resolves within the budget
+ adapter = AsyncMock()
+ adapter.send.return_value = MagicMock(success=True)
pconfig = MagicMock()
pconfig.enabled = True
diff --cc tests/hermes_cli/test_relay_shared_metrics.py
index e2c5c9f66fe,18190d9cb19..6e4eaca2e80
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@@ -24,13 -25,13 +25,17 @@@ from hermes_cli.observability.shared_me
COUNT_BUCKETS,
DURATION_BUCKETS,
EXECUTION_SURFACES,
+ LEGACY_MODEL_CALL_METRIC,
MODEL_CALL_PROFILE_MODEL,
MODEL_IDENTIFIER_MAX_LENGTH,
+ MODEL_ROUTE_METRIC,
PROVIDER_IDENTIFIER_MAX_LENGTH,
+ SCHEMA_KEY,
+ SCHEMA_VERSION,
+ SKILL_LIFECYCLE_ACTIONS,
+ SKILL_POST_PATCH_STATES,
+ SKILL_PROVENANCES,
+ SKILL_REUSE_STATES,
TASK_END_REASONS,
TASK_ENTRYPOINTS,
TASK_OUTCOMES,
@@@ -654,207 -611,47 +630,121 @@@ def test_tool_subscriber_contract_accep
assert tool_approval_counter(approval) is None
+def test_skill_subscriber_contract_accepts_only_bounded_marks():
- metadata = {"hermes.metrics.schema_version": "hermes.metrics.event.v1"}
++ metadata = {"hermes.metrics.schema_version": "hermes.metrics.event.v2"}
+ lifecycle = SimpleNamespace(
+ kind="mark",
+ category=None,
+ category_profile=None,
+ name="hermes.skill.lifecycle",
+ scope_category=None,
+ metadata=metadata,
+ data={"action": "patched", "provenance": "agent_created"},
+ )
+ assert skill_counter(lifecycle) == (
+ "hermes.skill.lifecycle.count",
+ lifecycle.data,
+ )
+
+ load = SimpleNamespace(**{
+ **lifecycle.__dict__,
+ "name": "hermes.skill.load",
+ "data": {
+ "post_patch_state": "reused_after_patch",
+ "provenance": "agent_created",
+ "reuse_state": "reused",
+ "use_count_bucket": "3_to_5",
+ },
+ })
+ assert skill_counter(load) == ("hermes.skill.load.count", load.data)
+
+ load.data["skill_name"] = "privacy-canary"
+ assert skill_counter(load) is None
+ load.data.pop("skill_name")
+ load.data["provenance"] = "private-repository"
+ assert skill_counter(load) is None
+ lifecycle.metadata["skill_name"] = "privacy-canary"
+ assert skill_counter(lifecycle) is None
+
-
+def test_skill_event_fields_are_bounded_and_reject_malformed_usage():
+ assert skill_lifecycle_fields({
+ "action": "patched",
+ "provenance": "agent_created",
+ "skill_name": "privacy-canary",
+ }) == {"action": "patched", "provenance": "agent_created"}
+ assert skill_lifecycle_fields({"action": "deleted"}) is None
+ assert skill_load_fields({
+ "provenance": "private-repository",
+ "use_count": 2,
+ "reused": True,
+ "reuse_after_patch": False,
+ "skill_name": "privacy-canary",
+ }) == {
+ "post_patch_state": "no_new_patch",
+ "provenance": "unknown",
+ "reuse_state": "reused",
+ "use_count_bucket": "2",
+ }
+ assert skill_load_fields({
+ "use_count": 1,
+ "reused": False,
+ "reuse_after_patch": False,
+ }) == {
+ "post_patch_state": "not_applicable",
+ "provenance": "unknown",
+ "reuse_state": "first_use",
+ "use_count_bucket": "1",
+ }
+ assert (
+ skill_load_fields({
+ "use_count": 1,
+ "reused": False,
+ "reuse_after_patch": True,
+ })
+ is None
+ )
+
+ def test_store_does_not_record_the_retired_model_metric(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
- def test_store_rejects_an_unsupported_schema_version(tmp_path):
- database_path = tmp_path / "metrics.sqlite3"
- with sqlite3.connect(database_path) as connection:
- connection.execute(
- "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
- )
- connection.execute(
- "INSERT INTO telemetry_state(key, value) VALUES ('schema_version', '999')"
+ with pytest.raises(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.py
index 7022e5ac1af,3e8526b3d7b..67a72ccc358
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@@ -3514,356 -2043,3 +2077,166 @@@ def test_failed_flush_keeps_daily_expor
assert metrics["hermes.task_run.finished"]["value"] == 2
assert flush_attempts == 2
assert "Hermes shared-metrics task flush failed" in caplog.text
-
-
- def test_task_ownership_survives_session_id_rotation(direct_runtime):
- lifecycle.invoke_hook(
- "pre_llm_call",
- session_id="before-compression",
- task_id="t1",
- platform="cli",
- )
- lifecycle.invoke_hook(
- "pre_api_request",
- session_id="after-compression",
- task_id="t1",
- api_request_id="r1",
- platform="cli",
- provider="nvidia",
- model="nvidia/nemotron-3-super-120b-a12b",
- )
- lifecycle.invoke_hook(
- "post_api_request",
- session_id="after-compression",
- task_id="t1",
- api_request_id="r1",
- platform="cli",
- provider="nvidia",
- model="nvidia/nemotron-3-super-120b-a12b",
- )
- lifecycle.invoke_hook(
- "on_session_end",
- session_id="after-compression",
- task_id="t1",
- platform="cli",
- completed=True,
- failed=False,
- interrupted=False,
- turn_exit_reason="text_response(stop)",
- )
- lifecycle.finalize_session(session_id="before-compression")
-
- task_starts = [
- event
- for event in direct_runtime.events
- if event[0] == "scope.push" and event[1] == "hermes.task_run"
- ]
- task_ends = [
- event
- for event in direct_runtime.events
- if event[0] == "scope.pop" and event[1][1] == "hermes.task_run"
- ]
- model_ends = [
- event for event in direct_runtime.events if event[0] == "llm.call_end"
- ]
- assert len(task_starts) == 1
- assert len(task_ends) == 1
- assert len(model_ends) == 1
- assert model_ends[0][2] == {
- "model": "nvidia/nemotron-3-super-120b-a12b",
- "provider": "nvidia",
- }
- assert task_ends[0][2]["output"]["model_call_count_bucket"] == "1"
- assert task_ends[0][2]["output"]["outcome"] == "success"
-
-
- def test_gateway_and_delegated_entrypoints_flow_through_relay(direct_runtime):
- tasks = [
- {
- "session_id": "gateway-session",
- "task_id": "gateway-task",
- "platform": "whatsapp_cloud",
- },
- {
- "session_id": "child-session",
- "task_id": "delegated-task",
- "platform": "cli",
- "parent_session_id": "private-parent-session",
- },
- ]
- for task in tasks:
- lifecycle.invoke_hook("pre_llm_call", **task)
- lifecycle.invoke_hook(
- "on_session_end",
- **task,
- completed=True,
- failed=False,
- interrupted=False,
- turn_exit_reason="text_response(stop)",
- )
-
- starts = [
- event[3]["input"]
- for event in direct_runtime.events
- if event[0] == "scope.push" and event[1] == "hermes.task_run"
- ]
- assert starts == [
- {"entrypoint": "gateway_message", "execution_surface": "gateway"},
- {"entrypoint": "delegated", "execution_surface": "cli"},
- ]
- assert "private-parent-session" not in json.dumps(direct_runtime.events)
-
-
+def test_skill_lifecycle_flows_through_relay_to_a_privacy_safe_package(
+ direct_runtime,
+ tmp_path,
+):
+ common = {
+ "skill_name": "private-skill-name",
+ "provenance": "agent_created",
+ }
+ lifecycle.invoke_hook("on_skill_lifecycle", **common, action="created")
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ **common,
+ action="loaded",
+ use_count=1,
+ reused=False,
+ reuse_after_patch=False,
+ )
+ lifecycle.invoke_hook("on_skill_lifecycle", **common, action="patched")
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ **common,
+ action="loaded",
+ use_count=2,
+ reused=True,
+ reuse_after_patch=True,
+ )
+
+ runtime = relay_shared_metrics._get_runtime()
+ assert runtime is not None
+ runtime.shutdown()
+
+ marks = [event for event in direct_runtime.events if event[0] == "scope.event"]
+ assert [event[1] for event in marks] == [
+ "hermes.skill.lifecycle",
+ "hermes.skill.load",
+ "hermes.skill.lifecycle",
+ "hermes.skill.load",
+ ]
+ assert "private-skill-name" not in json.dumps(marks)
+
+ outbox = tmp_path / "hermes-home" / "telemetry" / "shared_metrics" / "outbox"
+ [package_path] = list(outbox.glob("*.json"))
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+ skill_metrics = [
+ metric
+ for metric in package["metrics"]
+ if metric["name"].startswith("hermes.skill.")
+ ]
+ assert {metric["name"] for metric in skill_metrics} == {
+ "hermes.skill.lifecycle.count",
+ "hermes.skill.load.count",
+ }
+ assert "private-skill-name" not in json.dumps(package)
+
-
+def test_skill_lifecycle_with_only_task_id_uses_unique_task_scope(direct_runtime):
+ runtime = relay_shared_metrics._get_runtime()
+ assert runtime is not None
+ task = runtime.start_task({
+ "session_id": "session-1",
+ "task_id": "task-1",
+ "platform": "cli",
+ })
+ assert task is not None
+
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ action="created",
+ skill_name="private-skill-name",
+ provenance="agent_created",
+ task_id="task-1",
+ )
+
+ [mark] = [
+ event
+ for event in direct_runtime.events
+ if event[0] == "scope.event" and event[1] == "hermes.skill.lifecycle"
+ ]
+ assert mark[2]["handle"] == task.handle
+
-
+def test_skill_task_only_correlation_does_not_guess_across_sessions(direct_runtime):
+ runtime = relay_shared_metrics._get_runtime()
+ assert runtime is not None
+ for session_id in ("session-1", "session-2"):
+ assert runtime.start_task({
+ "session_id": session_id,
+ "task_id": "shared-task",
+ "platform": "cli",
+ }) is not None
+
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ action="created",
+ skill_name="private-skill-name",
+ provenance="agent_created",
+ task_id="shared-task",
+ )
+
+ [mark] = [
+ event
+ for event in direct_runtime.events
+ if event[0] == "scope.event" and event[1] == "hermes.skill.lifecycle"
+ ]
+ assert "handle" not in mark[2]
+
-
+def test_late_skill_lifecycle_is_not_reemitted_at_the_root(direct_runtime):
+ base = {
+ "session_id": "session-1",
+ "task_id": "task-1",
+ "turn_id": "turn-1",
+ "platform": "cli",
+ }
+ lifecycle.invoke_hook("pre_llm_call", **base)
+ lifecycle.invoke_hook(
+ "on_session_end",
+ **base,
+ completed=True,
+ failed=False,
+ interrupted=False,
+ turn_exit_reason="text_response(stop)",
+ )
+
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ **base,
+ action="loaded",
+ skill_name="private-skill-name",
+ provenance="local",
+ use_count=2,
+ reused=True,
+ reuse_after_patch=False,
+ )
+
+ assert [
+ event
+ for event in direct_runtime.events
+ if event[0] == "scope.event" and event[1] == "hermes.skill.load"
+ ] == []
+
-
+def test_skill_lifecycle_does_not_fallback_across_an_explicit_session(
+ direct_runtime,
+):
+ runtime = relay_shared_metrics._get_runtime()
+ assert runtime is not None
+ assert runtime.start_task({
+ "session_id": "session-1",
+ "task_id": "task-1",
+ "platform": "cli",
+ }) is not None
+
+ lifecycle.invoke_hook(
+ "on_skill_lifecycle",
+ action="created",
+ skill_name="private-skill-name",
+ provenance="local",
+ session_id="wrong-session",
+ task_id="task-1",
+ )
+
+ assert [
+ event
+ for event in direct_runtime.events
+ if event[0] == "scope.event" and event[1] == "hermes.skill.lifecycle"
+ ] == []
-
-
- def test_persistence_failure_does_not_escape_the_hook(
- direct_runtime,
- monkeypatch,
- caplog,
- ):
- runtime = relay_shared_metrics._get_runtime()
- assert runtime is not None
-
- def fail_record(*_args: Any, **_kwargs: Any) -> None:
- raise OSError("store unavailable")
-
- monkeypatch.setattr(runtime.subscriber.store, "record_counter", fail_record)
- lifecycle.invoke_hook(
- "pre_api_request",
- session_id="s1",
- task_id="t1",
- api_request_id="r1",
- provider="openai",
- model="gpt-5",
- )
- lifecycle.invoke_hook(
- "post_api_request",
- session_id="s1",
- task_id="t1",
- api_request_id="r1",
- provider="openai",
- model="gpt-5",
- )
-
- assert "Unable to persist the Hermes shared metric" in caplog.text
-
-
- def test_close_does_not_reopen_a_session_after_scope_start_failure(
- direct_runtime,
- monkeypatch,
- ):
- runtime = relay_runtime.get_runtime()
- assert runtime is not None
- original_push = direct_runtime.scope.push
- push_attempts = 0
-
- def fail_first_push(*args: Any, **kwargs: Any) -> Any:
- nonlocal push_attempts
- push_attempts += 1
- if push_attempts == 1:
- raise RuntimeError("simulated scope failure")
- return original_push(*args, **kwargs)
-
- direct_runtime.scope.push = fail_first_push
- with pytest.raises(RuntimeError, match="simulated scope failure"):
- runtime.ensure_session({"session_id": "s1"})
-
- close_started = threading.Event()
- allow_close = threading.Event()
- original_flush = direct_runtime.subscribers.flush
-
- def block_flush():
- session = runtime._sessions["s1"]
- assert session.closing is True
- close_started.set()
- assert allow_close.wait(timeout=5)
- original_flush()
-
- direct_runtime.subscribers.flush = block_flush
- close_thread = threading.Thread(
- target=runtime.close_session,
- args=({"session_id": "s1"},),
- )
- close_thread.start()
- assert close_started.wait(timeout=5)
-
- ensure_thread = threading.Thread(
- target=runtime.ensure_session,
- args=({"session_id": "s1"},),
- )
- ensure_thread.start()
- allow_close.set()
- close_thread.join(timeout=5)
- ensure_thread.join(timeout=5)
-
- assert not close_thread.is_alive()
- assert not ensure_thread.is_alive()
- assert push_attempts == 1
- assert "s1" not in runtime._sessions
diff --cc tests/tools/test_skill_manager_tool.py
index e043edce03f,1598129f169..edde6441d01
--- a/tests/tools/test_skill_manager_tool.py
+++ b/tests/tools/test_skill_manager_tool.py
@@@ -627,115 -360,6 +360,79 @@@ class TestSkillManageDispatcher
rec = usage.get("test-skill") or {}
assert rec.get("created_by") in {None, "", False}
+ def test_successful_mutations_emit_lifecycle_with_correlation(self, tmp_path):
+ with (
+ _skill_dir(tmp_path),
+ patch("tools.skill_provenance.is_background_review", return_value=False),
+ patch("tools.skill_usage.record_created") as record_created,
+ patch("tools.skill_usage.bump_patch") as bump_patch,
+ ):
+ created = json.loads(skill_manage(
+ action="create",
+ name="test-skill",
+ content=VALID_SKILL_CONTENT,
+ task_id="task-mutation",
+ session_id="session-mutation",
+ ))
+ patched = json.loads(skill_manage(
+ action="patch",
+ name="test-skill",
+ old_string="Step 1: Do the thing.",
+ new_string="Step 1: Do the thing safely.",
+ task_id="task-mutation",
+ session_id="session-mutation",
+ ))
+ edited = json.loads(skill_manage(
+ action="edit",
+ name="test-skill",
+ content=VALID_SKILL_CONTENT_2,
+ task_id="task-mutation",
+ session_id="session-mutation",
+ ))
+
+ assert created["success"] is True
+ assert patched["success"] is True
+ assert edited["success"] is True
+ record_created.assert_called_once_with(
+ "test-skill",
+ agent_created=False,
+ task_id="task-mutation",
+ session_id="session-mutation",
+ )
+ assert [call.kwargs for call in bump_patch.call_args_list] == [
+ {
+ "action": "patch",
+ "task_id": "task-mutation",
+ "session_id": "session-mutation",
+ },
+ {
+ "action": "edit",
+ "task_id": "task-mutation",
+ "session_id": "session-mutation",
+ },
+ ]
+ assert all(call.args == ("test-skill",) for call in bump_patch.call_args_list)
+
+ def test_failed_mutations_do_not_emit_lifecycle(self, tmp_path):
+ with (
+ _skill_dir(tmp_path),
+ patch("tools.skill_usage.record_created") as record_created,
+ patch("tools.skill_usage.bump_patch") as bump_patch,
+ ):
+ create_result = json.loads(skill_manage(
+ action="create",
+ name="test-skill",
+ ))
+ patch_result = json.loads(skill_manage(
+ action="patch",
+ name="test-skill",
+ ))
+
+ assert create_result["success"] is False
+ assert patch_result["success"] is False
+ record_created.assert_not_called()
+ bump_patch.assert_not_called()
+
- def test_create_from_background_review_marks_agent_created(self, tmp_path):
- """Background-review fork creates ARE marked as agent-created."""
- from tools.skill_provenance import set_current_write_origin, BACKGROUND_REVIEW
- token = set_current_write_origin(BACKGROUND_REVIEW)
- try:
- with _skill_dir(tmp_path):
- raw = skill_manage(
- action="create", name="review-sediment", content=VALID_SKILL_CONTENT
- )
- from tools.skill_usage import load_usage
- usage = load_usage()
- finally:
- from tools.skill_provenance import reset_current_write_origin
- reset_current_write_origin(token)
- result = json.loads(raw)
- assert result["success"] is True
- assert usage["review-sediment"]["created_by"] == "agent"
-
- def test_delete_via_dispatcher_threads_absorbed_into(self, tmp_path):
- # Dispatcher must plumb absorbed_into through to _delete_skill so the
- # validation + message suffix paths are exercised end-to-end.
- with _skill_dir(tmp_path):
- skill_manage(action="create", name="umbrella", content=VALID_SKILL_CONTENT)
- skill_manage(action="create", name="narrow", content=VALID_SKILL_CONTENT)
- raw = skill_manage(action="delete", name="narrow", absorbed_into="umbrella")
- result = json.loads(raw)
- assert result["success"] is True
- assert "absorbed into 'umbrella'" in result["message"]
-
- def test_delete_via_dispatcher_rejects_missing_absorbed_target(self, tmp_path):
- with _skill_dir(tmp_path):
- skill_manage(action="create", name="narrow", content=VALID_SKILL_CONTENT)
- raw = skill_manage(action="delete", name="narrow", absorbed_into="ghost")
- result = json.loads(raw)
- assert result["success"] is False
- assert "does not exist" in result["error"]
def test_background_review_delete_refuses_bundled_even_with_absorbed_into(self, tmp_path):
from tools.skill_provenance import (
diff --cc tests/tools/test_skill_usage.py
index 549bb005a0b,1931a93307c..05a4bcef8a9
--- a/tests/tools/test_skill_usage.py
+++ b/tests/tools/test_skill_usage.py
@@@ -123,224 -105,6 +105,196 @@@ def test_bump_view_increments_and_times
assert rec["last_viewed_at"] is not None
- def test_bump_use_increments_and_timestamps(skills_home):
- from tools.skill_usage import bump_use, get_record
- bump_use("my-skill")
- rec = get_record("my-skill")
- assert rec["use_count"] == 1
- assert rec["last_used_at"] is not None
-
-
- def test_bump_patch_increments_and_timestamps(skills_home):
- from tools.skill_usage import bump_patch, get_record
- bump_patch("my-skill")
- rec = get_record("my-skill")
- assert rec["patch_count"] == 1
- assert rec["last_patched_at"] is not None
-
-
+def test_skill_reuse_and_post_patch_reuse_are_derived_atomically(
+ skills_home,
+ monkeypatch,
+):
+ from hermes_cli import lifecycle
+ from tools.skill_usage import bump_patch, bump_use, get_record, record_created
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append((name, kwargs)),
+ )
+
+ record_created("private-skill-name", agent_created=True, task_id="task")
+ bump_use("private-skill-name", task_id="task")
+ bump_use("private-skill-name", task_id="task")
+ bump_patch("private-skill-name", task_id="task")
+ bump_use("private-skill-name", task_id="task")
+ bump_use("private-skill-name", task_id="task")
+
+ loaded = [event for _, event in events if event["action"] == "loaded"]
+ assert [event["reused"] for event in loaded] == [False, True, True, True]
+ assert [event["reuse_after_patch"] for event in loaded] == [
+ False,
+ False,
+ True,
+ False,
+ ]
+ assert all(event["provenance"] == "agent_created" for event in loaded)
+ record = get_record("private-skill-name")
+ assert record["use_count"] == 4
+ assert record["patch_generation"] == 1
+ assert record["last_reused_patch_generation"] == 1
+
-
+def test_skill_state_events_emit_only_for_real_transitions(skills_home, monkeypatch):
+ from hermes_cli import lifecycle
+ from tools.skill_usage import (
+ STATE_ACTIVE,
+ STATE_ARCHIVED,
+ STATE_STALE,
+ record_created,
+ set_state,
+ )
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append(kwargs),
+ )
+
+ record_created("my-skill", agent_created=True)
+ set_state("my-skill", STATE_STALE)
+ set_state("my-skill", STATE_STALE)
+ set_state("my-skill", STATE_ARCHIVED)
+ set_state("my-skill", STATE_ARCHIVED)
+ set_state("my-skill", STATE_ACTIVE)
+ set_state("my-skill", STATE_ACTIVE)
+
+ assert [event["action"] for event in events] == [
+ "created",
+ "stale",
+ "archived",
+ "restored",
+ ]
+
-
+def test_skill_event_is_not_emitted_when_usage_state_cannot_commit(
+ skills_home,
+ monkeypatch,
+):
+ from hermes_cli import lifecycle
+ from tools import skill_usage
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append(kwargs),
+ )
+ monkeypatch.setattr(skill_usage, "save_usage", lambda data: False)
+
+ skill_usage.bump_use("private-skill-name")
+
+ assert events == []
+
-
+def test_installed_lifecycle_uses_persisted_provenance_when_hub_lookup_misses(
+ skills_home,
+ monkeypatch,
+):
+ from hermes_cli import lifecycle
+ from tools import skill_usage
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append(kwargs),
+ )
+ monkeypatch.setattr(skill_usage, "is_hub_installed", lambda _name: False)
+ monkeypatch.setattr(skill_usage, "is_bundled", lambda _name: False)
+
+ skill_usage.record_installed("private-installed-skill")
+
+ assert len(events) == 1
+ assert events[0]["action"] == "installed"
+ assert events[0]["provenance"] == "installed"
+
-
+def test_created_skill_does_not_inherit_stale_identity_or_continuity(
+ skills_home,
+ monkeypatch,
+):
+ from hermes_cli import lifecycle
+ from tools import skill_usage
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append(kwargs),
+ )
+ skill_usage.save_usage({
+ "recreated": {
+ "created_by": "agent",
+ "use_count": 11,
+ "patch_count": 4,
+ "patch_generation": 4,
+ "last_reused_patch_generation": 3,
+ "pinned": True,
+ "state": skill_usage.STATE_ARCHIVED,
+ }
+ })
+
+ skill_usage.record_created("recreated", agent_created=False)
+ skill_usage.bump_use("recreated")
+
+ record = skill_usage.get_record("recreated")
+ assert record["created_by"] is None
+ assert record["use_count"] == 1
+ assert record["patch_count"] == 0
+ assert record["patch_generation"] == 0
+ assert record["last_reused_patch_generation"] == 0
+ assert record["pinned"] is False
+ assert record["state"] == skill_usage.STATE_ACTIVE
+ assert [event["provenance"] for event in events] == ["local", "local"]
+ assert events[-1]["reused"] is False
+ assert events[-1]["reuse_after_patch"] is False
+
-
+def test_malformed_usage_counters_recover_without_losing_patch_reuse(
+ skills_home,
+ monkeypatch,
+):
+ from hermes_cli import lifecycle
+ from tools import skill_usage
+
+ events = []
+ monkeypatch.setattr(lifecycle, "has_hook", lambda name: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "invoke_hook",
+ lambda name, **kwargs: events.append(kwargs),
+ )
+ skill_usage.save_usage({
+ "damaged": {
+ "view_count": "not-a-number",
+ "use_count": "not-a-number",
+ "patch_generation": 1,
+ "last_reused_patch_generation": 999,
+ }
+ })
+
+ skill_usage.bump_view("damaged")
+ skill_usage.bump_use("damaged")
+ skill_usage.bump_patch("damaged")
+ skill_usage.bump_use("damaged")
+
+ record = skill_usage.get_record("damaged")
+ assert record["view_count"] == 1
+ assert record["use_count"] == 2
+ assert record["patch_generation"] == 2
+ assert record["last_reused_patch_generation"] == 2
+ loaded = [event for event in events if event["action"] == "loaded"]
+ assert [event["reused"] for event in loaded] == [False, True]
+ assert [event["reuse_after_patch"] for event in loaded] == [False, True]
+
-
- def test_bump_on_empty_name_is_noop(skills_home):
- from tools.skill_usage import bump_view, load_usage
- bump_view("")
- assert load_usage() == {}
-
-
def test_bumps_do_not_corrupt_other_skills(skills_home):
from tools.skill_usage import bump_view, bump_use, get_record
bump_view("skill-a")
diff --cc tests/tools/test_skills_tool.py
index ba29e654f83,1a193a12e0f..656d02e3556
--- a/tests/tools/test_skills_tool.py
+++ b/tests/tools/test_skills_tool.py
@@@ -375,132 -302,40 +302,63 @@@ class TestSkillsList
class TestSkillView:
- def test_view_existing_skill(self, tmp_path):
+ def test_view_resolves_by_dir_name_and_frontmatter_name(self, tmp_path):
with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- _make_skill(tmp_path, "my-skill")
- raw = skill_view("my-skill")
- result = json.loads(raw)
- assert result["success"] is True
- assert result["name"] == "my-skill"
- assert "Step 1" in result["content"]
+ _make_skill(
+ tmp_path,
+ "my-skill",
+ frontmatter_extra="metadata:\n hermes:\n tags: [fine-tuning, llm]\n",
+ )
+ # The on-disk directory ("alias-dir") differs from the skill's
+ # frontmatter name ("real-skill-name"). skills_list() exposes the
+ # frontmatter name, so skill_view(name) must resolve it too.
+ alias_dir = tmp_path / "alias-dir"
+ alias_dir.mkdir(parents=True, exist_ok=True)
+ (alias_dir / "SKILL.md").write_text(
+ "---\n"
+ "name: real-skill-name\n"
+ "description: A skill whose directory name differs from its name.\n"
+ "---\n\n"
+ "# real-skill-name\n\n"
+ "Step 1: Do the thing.\n"
+ )
+ by_dir = json.loads(skill_view("my-skill"))
+ by_name = json.loads(skill_view("real-skill-name"))
+
+ assert by_dir["success"] is True
+ assert by_dir["name"] == "my-skill"
+ assert "Step 1" in by_dir["content"]
+ assert "fine-tuning" in by_dir["tags"]
+ assert "llm" in by_dir["tags"]
+
+ assert by_name["success"] is True
+ assert "Step 1" in by_name["content"]
+ def test_registered_view_tracks_use_with_task_and_session(self, tmp_path):
+ from tools.skills_tool import _skill_view_with_bump
+
+ with (
+ patch("tools.skills_tool.SKILLS_DIR", tmp_path),
+ patch("tools.skill_usage.bump_view") as bump_view,
+ patch("tools.skill_usage.bump_use") as bump_use,
+ ):
+ _make_skill(tmp_path, "my-skill")
+ raw = _skill_view_with_bump(
+ {"name": "my-skill"},
+ task_id="task-view",
+ session_id="session-view",
+ )
+
+ assert json.loads(raw)["success"] is True
+ bump_view.assert_called_once_with("my-skill")
+ bump_use.assert_called_once_with(
+ "my-skill",
+ task_id="task-view",
+ session_id="session-view",
+ )
+
- def test_view_skill_by_frontmatter_name_when_dir_differs(self, tmp_path):
- # The on-disk directory ("alias-dir") differs from the skill's
- # frontmatter name ("real-skill-name"). skills_list() exposes the
- # frontmatter name, so skill_view(name) must resolve it too.
- skill_dir = tmp_path / "alias-dir"
- skill_dir.mkdir(parents=True, exist_ok=True)
- (skill_dir / "SKILL.md").write_text(
- "---\n"
- "name: real-skill-name\n"
- "description: A skill whose directory name differs from its name.\n"
- "---\n\n"
- "# real-skill-name\n\n"
- "Step 1: Do the thing.\n"
- )
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- raw = skill_view("real-skill-name")
- result = json.loads(raw)
- assert result["success"] is True
- assert "Step 1" in result["content"]
-
- def test_skill_view_applies_template_vars(self, tmp_path):
- with (
- patch("tools.skills_tool.SKILLS_DIR", tmp_path),
- patch(
- "agent.skill_preprocessing.load_skills_config",
- return_value={"template_vars": True, "inline_shell": False},
- ),
- ):
- skill_dir = _make_skill(
- tmp_path,
- "templated",
- body="Run ${HERMES_SKILL_DIR}/scripts/do.sh in ${HERMES_SESSION_ID}",
- )
- raw = skill_view("templated", task_id="session-123")
-
- result = json.loads(raw)
- assert result["success"] is True
- assert f"Run {skill_dir}/scripts/do.sh in session-123" in result["content"]
- assert "${HERMES_SKILL_DIR}" not in result["content"]
-
- def test_skill_view_applies_inline_shell_when_enabled(self, tmp_path):
- with (
- patch("tools.skills_tool.SKILLS_DIR", tmp_path),
- patch(
- "agent.skill_preprocessing.load_skills_config",
- return_value={
- "template_vars": True,
- "inline_shell": True,
- "inline_shell_timeout": 5,
- },
- ),
- ):
- _make_skill(
- tmp_path,
- "dynamic",
- body="Current date: !`printf 2026-04-24`",
- )
- raw = skill_view("dynamic")
-
- result = json.loads(raw)
- assert result["success"] is True
- assert "Current date: 2026-04-24" in result["content"]
- assert "!`printf 2026-04-24`" not in result["content"]
- def test_skill_view_leaves_inline_shell_literal_when_disabled(self, tmp_path):
- with (
- patch("tools.skills_tool.SKILLS_DIR", tmp_path),
- patch(
- "agent.skill_preprocessing.load_skills_config",
- return_value={"template_vars": True, "inline_shell": False},
- ),
- ):
- _make_skill(
- tmp_path,
- "static",
- body="Current date: !`printf SHOULD_NOT_RUN`",
- )
- raw = skill_view("static")
-
- result = json.loads(raw)
- assert result["success"] is True
- assert "Current date: !`printf SHOULD_NOT_RUN`" in result["content"]
- assert "Current date: SHOULD_NOT_RUN" not in result["content"]
-
- def test_view_nonexistent_skill(self, tmp_path):
- with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
- _make_skill(tmp_path, "other-skill")
- raw = skill_view("nonexistent")
- result = json.loads(raw)
- assert result["success"] is False
- assert "not found" in result["error"].lower()
- assert "available_skills" in result
-
- def test_view_reference_file(self, tmp_path):
+ def test_view_reference_files(self, tmp_path):
with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
skill_dir = _make_skill(tmp_path, "my-skill")
refs_dir = skill_dir / "references"