Skip to content

The agent that grows with you

test: preserve Kanban policy and cron cleanup owner invariants

Tekniume1b6f10ba19a
diff --git a/tests/plugins/test_kanban_model_override.py b/tests/plugins/test_kanban_model_override.py
index 25904790e69..208c636073b 100644
--- a/tests/plugins/test_kanban_model_override.py
+++ b/tests/plugins/test_kanban_model_override.py
@@ -2,16 +2,18 @@
Covers the model-dropdown feature: kanban_db.set_model_override(),
create_task(model_override=..., provider_override=...), the dispatcher
-passing ``-m <model> --provider <name>`` to the worker, and the dashboard
+passing task identity to the owner for trusted policy resolution, and the dashboard
PATCH/bulk/model-options surfaces.
"""
from __future__ import annotations
import importlib.util
+import json
import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
import pytest
from fastapi import FastAPI
@@ -115,40 +117,85 @@ def test_migration_adds_provider_override_column(conn):
# ---------------------------------------------------------------------------
-# Worker spawn — argv carries -m and --provider
+# Worker spawn — task identity resolves trusted owner policy
# ---------------------------------------------------------------------------
-def _spawn_and_capture(monkeypatch, tmp_path, task):
- monkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: ["hermes"])
+ "overrides, expected_model, expected_provider, expected_reasoning",
+ [
+ ({"model_override": "glm-5", "provider_override": "openrouter",
+ "reasoning_effort": "high"}, "glm-5", "openrouter", "high"),
+ ({"reasoning_effort": "high"}, "profile-model", "custom", "high"),
+ ({"reasoning_effort": "none"}, "profile-model", "custom", None),
+ ({}, "profile-model", "custom", "low"),
+ ],
+)
+def test_spawn_resolves_claimed_task_policy(
+ monkeypatch, tmp_path, conn, kanban_home, overrides,
+ expected_model, expected_provider, expected_reasoning,
+):
+ """The worker passes identity, while the owner reads overrides from SQLite."""
+ from gateway.session_contract import Principal
+ from gateway.session_kanban import build_kanban_policy
+ from hermes_cli import kanban_worker_client
+ from hermes_state_runtime import RuntimeStoreError
+
+ profile = kanban_home / "profiles" / "elias"
+ profile.mkdir(parents=True)
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+ tid = kb.create_task(conn, title="t", assignee="elias",
+ workspace_kind="dir", workspace_path=str(workspace), **overrides)
+ task = kb.claim_task(conn, tid)
+ assert task is not None
captured = {}
- class FakeProc:
- pid = 4245
-
- def fake_popen(cmd, *args, **kwargs):
- captured["cmd"] = list(cmd)
- return FakeProc()
+ def fake_popen(cmd, **kwargs):
+ captured.update(cmd=list(cmd), env=kwargs["env"])
+ kwargs["stdout"].close()
+ return SimpleNamespace(pid=4245)
monkeypatch.setattr(subprocess, "Popen", fake_popen)
- workspace = tmp_path / "ws"
- workspace.mkdir(exist_ok=True)
kbd._default_spawn(task, str(workspace))
- return captured["cmd"]
-
-
-def test_spawn_passes_model_and_provider(monkeypatch, tmp_path, conn):
- tid = kb.create_task(
- conn, title="t", assignee="elias",
- model_override="glm-5", provider_override="openrouter",
- )
- task = kb.get_task(conn, tid)
- cmd = _spawn_and_capture(monkeypatch, tmp_path, task)
- i = cmd.index("-m")
- assert cmd[i + 1] == "glm-5"
- j = cmd.index("--provider")
- assert j == i + 2
- assert cmd[j + 1] == "openrouter"
+ assert captured["cmd"] == [sys.executable, "-m", "hermes_cli.kanban_worker_client"]
+ assert captured["env"]["HERMES_HOME"] == str(profile)
+ actor = Principal("owner", str(profile), frozenset({"session:create"}), "transport")
+ connection = SimpleNamespace(
+ authority=SimpleNamespace(profile_id=str(profile)), actor=actor, native_owner=True)
+ config = {"model": {"default": "profile-model", "provider": "custom"},
+ "agent": {"reasoning_effort": "medium",
+ "reasoning_overrides": {"profile-model": "low", "glm-5": "low"}},
+ "platform_toolsets": {"cli": ["terminal"]}}
+ original_config = json.dumps(config, sort_keys=True)
+
+ async def resolve_at_owner(params, board_db):
+ params = dict(params, db=board_db)
+ policy, _ = build_kanban_policy(connection, params, config)
+ assert policy.model == expected_model
+ assert policy.provider == expected_provider
+ expected = ({"enabled": False} if expected_reasoning is None else
+ {"enabled": True, "effort": expected_reasoning})
+ assert policy.reasoning_config == expected
+ assert policy.cwd == str(workspace) and "kanban" in policy.toolsets
+ context = json.loads(policy.kanban_json)
+ assert (context["task_id"], context["run_id"], context["claim_lock"]) == (
+ task.id, task.current_run_id, task.claim_lock)
+ # A worker cannot replace trusted settings or reuse another claim.
+ with pytest.raises(RuntimeStoreError, match="invalid_params"):
+ build_kanban_policy(connection, params | {"model": "forged"}, config)
+ with pytest.raises(RuntimeStoreError, match="invalid_kanban_claim"):
+ build_kanban_policy(connection, params | {"claim_lock": "forged"}, config)
+ assert json.dumps(config, sort_keys=True) == original_config
+ captured["resolved"] = True
+ return 0
+
+ monkeypatch.setattr(kanban_worker_client, "run", resolve_at_owner)
+ with monkeypatch.context() as child:
+ for key, value in captured["env"].items():
+ child.setenv(key, value)
+ assert kanban_worker_client.main() == 0
+ assert captured["resolved"]
# ---------------------------------------------------------------------------
@@ -253,32 +300,6 @@ def test_reasoning_effort_without_a_model_override(conn):
assert t.reasoning_effort == "low"
-def test_spawn_passes_reasoning_without_a_model(monkeypatch, tmp_path, conn):
- tid = kb.create_task(conn, title="t", assignee="elias", reasoning_effort="high")
- task = kb.get_task(conn, tid)
- cmd = _spawn_and_capture(monkeypatch, tmp_path, task)
- assert "-m" not in cmd
- i = cmd.index("--reasoning")
- assert cmd[i + 1] == "high"
-
-
-def test_spawn_omits_reasoning_when_unset(monkeypatch, tmp_path, conn):
- tid = kb.create_task(conn, title="t", assignee="elias")
- task = kb.get_task(conn, tid)
- cmd = _spawn_and_capture(monkeypatch, tmp_path, task)
- assert "--reasoning" not in cmd
-
-
-def test_worker_cli_accepts_the_reasoning_flag():
- """The dispatcher's --reasoning must be a real flag on the worker's CLI —
- a spawn arg no parser accepts fails every dispatch."""
- from hermes_cli._parser import build_top_level_parser
-
- parser = build_top_level_parser()[0]
- args = parser.parse_args(["--cli", "chat", "-q", "hi", "--reasoning", "high"])
- assert args.reasoning == "high"
-
-
def test_patch_sets_and_clears_reasoning_effort(client):
task = _create(client)
r = client.patch(
diff --git a/tests/run_agent/test_exit_cleanup_interrupt.py b/tests/run_agent/test_exit_cleanup_interrupt.py
index d33d120369f..c6f52b98e0d 100644
--- a/tests/run_agent/test_exit_cleanup_interrupt.py
+++ b/tests/run_agent/test_exit_cleanup_interrupt.py
@@ -1,63 +1,68 @@
-"""Tests for KeyboardInterrupt handling in exit cleanup paths.
+"""A second Ctrl+C during cron finalization must not skip resource cleanup."""
-``except Exception`` does not catch ``KeyboardInterrupt`` (which inherits
-from ``BaseException``). A second Ctrl+C during exit cleanup must not
-abort remaining cleanup steps. These tests exercise the actual production
-code paths — not a copy of the try/except pattern.
-"""
-
-from unittest.mock import MagicMock, patch
+import json
+from types import SimpleNamespace
+from unittest.mock import patch
import pytest
[email protected](autouse=True)
-def _mock_runtime_provider(monkeypatch):
- """run_job calls resolve_runtime_provider which can try real network
- auto-detection (~4s of socket timeouts in hermetic CI). Mock it out
- since these tests don't care about provider resolution — the agent
- is mocked too."""
- import hermes_cli.runtime_provider as rp
- def _fake_resolve(*args, **kwargs):
- return {
- "provider": "openrouter",
- "api_key": "test-key",
- "base_url": "https://openrouter.ai/api/v1",
- "model": "test/model",
- "api_mode": "chat_completions",
- }
- monkeypatch.setattr(rp, "resolve_runtime_provider", _fake_resolve)
-
-
-class TestCronJobCleanup:
- """cron/scheduler.py — end_session + close in the finally block."""
-
- def test_keyboard_interrupt_in_end_session_does_not_skip_close(self):
- """If end_session raises KeyboardInterrupt, close() must still run."""
- mock_db = MagicMock()
- mock_db.end_session.side_effect = KeyboardInterrupt
-
- from cron import scheduler
- from cron import scheduler_delivery as sched_delivery
-
- job = {
- "id": "test-job-1",
- "name": "test cleanup",
- "prompt": "hello",
- "schedule": "0 9 * * *",
- "model": "test/model",
- }
-
- with patch("hermes_state_registry.acquire", return_value=mock_db), \
- patch.object(scheduler, "_build_job_prompt", return_value="hello"), \
- patch.object(sched_delivery, "_resolve_origin", return_value=None), \
- patch.object(scheduler, "_resolve_delivery_target", return_value=None), \
- patch("dotenv.load_dotenv", return_value=None), \
- patch("run_agent.AIAgent") as MockAgent:
- # Make the agent raise immediately so we hit the finally block
- MockAgent.return_value.run_conversation.side_effect = RuntimeError("boom")
- scheduler.run_job(job)
-
- mock_db.end_session.assert_called_once()
- mock_db.close.assert_called_once()
+async def test_keyboard_interrupt_in_end_session_does_not_skip_close(tmp_path, monkeypatch):
+ """Exercise owner execution and release its borrowed store despite Ctrl+C."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_cron import current_execution, execute
+ from hermes_state_registry import acquire, release
+
+ home = tmp_path / "owner"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HOME", str(tmp_path))
+ (home / "config.yaml").write_text("model:\n default: test/model\n provider: custom\n")
+ db = acquire(home / "state.db")
+ ref = SessionRef(str(home), "cron-cleanup-session")
+ db.create_session(ref.session_id, source="cron")
+ authority = SimpleNamespace(
+ db=db, sessions={ref.session_id: SimpleNamespace(
+ source=SimpleNamespace(user_id="cron-owner"))}, pending_results={})
+ job = {"id": "test-job-1", "name": "test cleanup", "prompt": "hello",
+ "schedule": "0 9 * * *", "model": "test/model"}
+ row = {"admission_id": "cleanup-admission", "request_id": "cleanup-request",
+ "principal_id": "cron-owner", "payload": {"text": ""}}
+ policy = SimpleNamespace(request_json=json.dumps({
+ "cron_job": job, "extra_prompt": None, "request_id": row["request_id"]}))
+ runtime = {"provider": "custom", "api_key": "test-key",
+ "base_url": "http://127.0.0.1:1/v1", "model": "test/model",
+ "api_mode": "chat_completions"}
+ reached = []
+
+ def fail_turn(*args, **kwargs):
+ reached.append(current_execution())
+ raise RuntimeError("boom")
+
+ try:
+ with patch("hermes_cli.runtime_provider.resolve_runtime_provider", return_value=runtime), \
+ patch("run_agent.AIAgent") as agent_class, \
+ patch.object(db, "end_session", side_effect=KeyboardInterrupt) as end_session, \
+ patch.object(db, "close", wraps=db.close) as close:
+ agent = agent_class.return_value
+ agent.session_id = ref.session_id
+ agent.run_conversation.side_effect = fail_turn
+ previous = current_execution()
+ with pytest.raises(RuntimeError, match="RuntimeError: boom"):
+ await execute(authority, ref, row, policy)
+ assert reached == [(authority, ref.session_id, job["id"], row["admission_id"])]
+ assert agent_class.call_args.kwargs["session_db"] is db
+ end_session.assert_called_once_with(ref.session_id, "cron_incomplete_no_output")
+ close.assert_called_once()
+ agent.close.assert_called_once()
+ assert current_execution() is previous
+ assert not authority._cron_cancellations
+ result = authority.pending_results[row["admission_id"]]["result"]["cron_result"]
+ assert result[0] is False and result[3] == "RuntimeError: boom"
+ # Cron released its borrow, not the owner's live SQLite connection.
+ saved = db.get_session(ref.session_id)
+ assert saved is not None and saved["title"].startswith(job["name"])
+ finally:
+ assert release(db)