Skip to content

The agent that grows with you

fix(kanban): persist active-profile identity in comment author / created_by when HERMES_PROFILE unpinned

max253a956144ed
diff --git a/tests/tools/test_kanban_comment_injection.py b/tests/tools/test_kanban_comment_injection.py
index 98938c7e7ff..cee39706112 100644
--- a/tests/tools/test_kanban_comment_injection.py
+++ b/tests/tools/test_kanban_comment_injection.py
@@ -158,3 +158,36 @@ def test_delegated_child_in_worker_process_neither_receives_nor_consumes_notes(w
_unthrottle()
assert kt.inject_new_comments_from_env(worker) is True
assert "operator note" in worker.steers[0]
+
+
+def test_skips_own_authored_comments_without_env_profile(worker_home, monkeypatch):
+ """Own comments are skipped even when ``HERMES_PROFILE`` is absent: the
+ injection filter resolves the worker's identity the same way the persisted
+ write side does (env → ``HERMES_HOME``-derived active profile), so a worker's
+ own notes can never steer its live turn as fake operator messages."""
+ conn = kbc.connect()
+ try:
+ tid = kb.create_task(conn, title="identity echo guard")
+ finally:
+ conn.close()
+
+ monkeypatch.setenv("HERMES_KANBAN_TASK", tid)
+ monkeypatch.delenv("HERMES_PROFILE", raising=False)
+ monkeypatch.delenv("HERMES_PROFILE_NAME", raising=False)
+ agent = FakeAgent()
+
+ _unthrottle()
+ kt.inject_new_comments_from_env(agent) # seed
+
+ identity = kt._persisted_identity()
+ assert identity != "worker" # resolved from HERMES_HOME, not the generic label
+
+ conn = kbc.connect()
+ try:
+ kb.add_comment(conn, tid, author=identity, body="note to self")
+ finally:
+ conn.close()
+
+ _unthrottle()
+ assert kt.inject_new_comments_from_env(agent) is False
+ assert agent.steers == []
diff --git a/tests/tools/test_kanban_persisted_identity.py b/tests/tools/test_kanban_persisted_identity.py
new file mode 100644
index 00000000000..af4a36c3c2f
--- /dev/null
+++ b/tests/tools/test_kanban_persisted_identity.py
@@ -0,0 +1,156 @@
+"""Persisted board identity resolves the ACTIVE profile, never a generic label.
+
+Regression: ``kanban_comment``/``kanban_create`` persisted ``"worker"`` whenever
+the dispatcher had not pinned ``HERMES_PROFILE``, even though the running Hermes
+profile was discoverable from ``HERMES_HOME`` via
+``hermes_cli.profiles.get_active_profile_name``. Comment authors are injected
+into future workers' prompts and ``created_by`` gates completion audits, so a
+generic label silently loses handoff provenance.
+
+Contract under test (``tools.kanban_tools._persisted_identity``): environment
+profile (``HERMES_PROFILE_NAME``/``HERMES_PROFILE``) → active profile API →
+generic ``"worker"`` fallback. Caller args can never override the persisted
+identity (#19713).
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+
+def board_env(tmp_path, monkeypatch):
+ """Worker on an isolated default board whose ``HERMES_HOME`` sits under a
+ NAMED profile dir (``<root>/profiles/qa-bot``) — the shape a profile launch
+ has when the dispatcher did not export ``HERMES_PROFILE``. The ``profiles``
+ parent makes ``get_default_hermes_root()`` resolve to ``<root>`` on every
+ platform, so the board DB stays inside tmp_path."""
+ profile_home = tmp_path / "hroot" / "profiles" / "qa-bot"
+ profile_home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(profile_home))
+ monkeypatch.delenv("HERMES_PROFILE", raising=False)
+ monkeypatch.delenv("HERMES_PROFILE_NAME", raising=False)
+ monkeypatch.delenv("HERMES_SESSION_ID", raising=False)
+ for var in ("HERMES_KANBAN_DB", "HERMES_KANBAN_HOME", "HERMES_KANBAN_BOARD",
+ "HERMES_KANBAN_WORKSPACES_ROOT"):
+ monkeypatch.delenv(var, raising=False)
+
+ from hermes_cli import kanban_db as kb
+ from hermes_cli import kanban_db_connect as kbc
+ kb._INITIALIZED_PATHS.clear()
+ kb.init_db()
+ conn = kbc.connect()
+ try:
+ tid = kb.create_task(conn, title="identity-test", assignee="qa-bot")
+ kb.claim_task(conn, tid)
+ finally:
+ conn.close()
+ monkeypatch.setenv("HERMES_KANBAN_TASK", tid)
+ return tid
+
+
+def _last_comment_author(tid: str) -> str:
+ from hermes_cli import kanban_db as kb
+ from hermes_cli import kanban_db_connect as kbc
+ conn = kbc.connect()
+ try:
+ return kb.list_comments(conn, tid)[-1].author
+ finally:
+ conn.close()
+
+
+def _created_by(tid: str) -> str:
+ from hermes_cli import kanban_db as kb
+ from hermes_cli import kanban_db_connect as kbc
+ conn = kbc.connect()
+ try:
+ return kb.get_task(conn, tid).created_by
+ finally:
+ conn.close()
+
+
+def test_env_profile_takes_precedence(board_env, monkeypatch):
+ """A dispatcher-pinned ``HERMES_PROFILE`` wins over the HERMES_HOME-derived
+ active profile for both persisted record kinds."""
+ from tools import kanban_tools as kt
+ monkeypatch.setenv("HERMES_PROFILE", "pinned-bot")
+
+ out = json.loads(kt._handle_comment({"task_id": board_env, "body": "from env"}))
+ assert out["ok"]
+ assert _last_comment_author(board_env) == "pinned-bot"
+
+ child = json.loads(kt._handle_create(
+ {"title": "env child", "assignee": "peer", "parents": [board_env]}))
+ assert child["ok"]
+ assert _created_by(child["task_id"]) == "pinned-bot"
+
+
+def test_active_profile_used_when_env_absent(board_env):
+ """The regression: no ``HERMES_PROFILE`` in the environment, but
+ ``HERMES_HOME`` names the active profile — persisted records must carry
+ that profile, not the generic ``"worker"`` label."""
+ from tools import kanban_tools as kt
+
+ out = json.loads(kt._handle_comment(
+ {"task_id": board_env, "body": "from active profile"}))
+ assert out["ok"]
+ assert _last_comment_author(board_env) == "qa-bot"
+
+ child = json.loads(kt._handle_create(
+ {"title": "profile child", "assignee": "peer", "parents": [board_env]}))
+ assert child["ok"]
+ assert _created_by(child["task_id"]) == "qa-bot"
+
+
+def _raiser():
+ raise RuntimeError("profile store unavailable")
+
+
[email protected]("stub", [lambda: "", _raiser])
+def test_generic_fallback_without_any_profile(board_env, monkeypatch, stub):
+ """No env profile AND an unusable active-profile API → generic ``"worker"``
+ (records stay attributable to *a* worker instead of failing the call)."""
+ import hermes_cli.profiles as profiles
+ monkeypatch.setattr(profiles, "get_active_profile_name", stub)
+ from tools import kanban_tools as kt
+
+ out = json.loads(kt._handle_comment({"task_id": board_env, "body": "anon"}))
+ assert out["ok"]
+ assert _last_comment_author(board_env) == "worker"
+
+ child = json.loads(kt._handle_create(
+ {"title": "anon child", "assignee": "peer", "parents": [board_env]}))
+ assert child["ok"]
+ assert _created_by(child["task_id"]) == "worker"
+
+
+def _comment_authors(tid: str) -> list[str]:
+ from hermes_cli import kanban_db as kb
+ from hermes_cli import kanban_db_connect as kbc
+ conn = kbc.connect()
+ try:
+ return [c.author for c in kb.list_comments(conn, tid)]
+ finally:
+ conn.close()
+
+
+def test_caller_args_cannot_override_persisted_identity(board_env):
+ """#19713 stays fixed — and got stronger upstream: ``author``/``created_by``
+ are undeclared parameters of ``kanban_comment``/``kanban_create``, so the
+ handler wrapper rejects the call outright ("Nothing changed") before it can
+ reach the handler. Identity can never come from tool args (see also
+ ``_persisted_identity``, which has no args surface)."""
+ from tools import kanban_tools as kt
+
+ out = json.loads(kt._handle_comment(
+ {"task_id": board_env, "body": "hi", "author": "hermes-system"}))
+ assert not out.get("ok")
+ assert "unknown parameter" in out["error"]
+ assert _comment_authors(board_env) == [] # nothing persisted
+
+ child = json.loads(kt._handle_create(
+ {"title": "forged child", "assignee": "peer", "parents": [board_env],
+ "created_by": "hermes-system"}))
+ assert not child.get("ok")
+ assert "unknown parameter" in child["error"]
diff --git a/tools/kanban_tools.py b/tools/kanban_tools.py
index 896c313049f..cfb98558155 100644
--- a/tools/kanban_tools.py
+++ b/tools/kanban_tools.py
@@ -136,6 +136,33 @@ _UNDECLARED_ARGS: dict[str, frozenset[str]] = {
}
+def _persisted_identity() -> str:
+ """Profile name persisted into board records (comment author, task creator).
+
+ Resolution mirrors ``hermes_cli.kanban._profile_author`` and
+ ``cron.lifecycle_guard._current_profile_name``: environment first (the
+ dispatcher pins ``HERMES_PROFILE``; some launchers set
+ ``HERMES_PROFILE_NAME``), else the active profile derived from
+ ``HERMES_HOME`` via ``hermes_cli.profiles.get_active_profile_name``, else
+ the generic ``"worker"`` fallback. Never taken from tool args: board
+ records are injected into future workers' prompts, so a caller-supplied
+ identity could forge an authoritative-looking author (see #19713).
+ """
+ for env_name in ("HERMES_PROFILE_NAME", "HERMES_PROFILE"):
+ value = (os.environ.get(env_name) or "").strip()
+ if value:
+ return value
+ try:
+ from hermes_cli.profiles import get_active_profile_name
+
+ active = (get_active_profile_name() or "").strip()
+ if active:
+ return active
+ except Exception:
+ logger.debug("kanban identity: active-profile lookup failed", exc_info=True)
+ return "worker"
+
+
def _kanban_handler(tool_name: str) -> Callable:
"""Wrap a handler so every failure is a structured tool error. ``ValueError``
(invalid board slug, DB validation such as cycle/self-link, ``AttachmentTooLarge``)
@@ -559,7 +586,7 @@ _comment_watermark: dict[str, int] = {}
def inject_new_comments_from_env(agent: Any) -> bool:
"""Steer new operator comments on the worker's task into ``agent``; True iff a
- steer was injected; never raises. Own comments (``HERMES_PROFILE``) are skipped."""
+ steer was injected; never raises. Own comments (``_persisted_identity``) are skipped."""
global _comment_poll_last_attempt
# Operator notes address the dispatcher-owned worker; a delegate_task child sharing
# this process must neither receive them nor advance the shared watermark (#112817).
@@ -582,7 +609,10 @@ def inject_new_comments_from_env(agent: Any) -> bool:
return False
# Advance past everything read (including our own notes) so nothing is re-injected.
_comment_watermark[tid] = max(c.id for c in rows)
- own = (os.environ.get("HERMES_PROFILE") or "").strip()
+ # Same resolution the write side used, so a worker skips its OWN comments even
+ # when the dispatcher did not pin HERMES_PROFILE (echoed notes would otherwise
+ # re-enter the live turn as fake operator steering).
+ own = _persisted_identity()
fresh = [c for c in rows if (c.author or "").strip() != own and (c.body or "").strip()]
if not fresh:
return False
@@ -862,15 +892,15 @@ def _handle_comment(args: dict, **kw) -> str:
_check(tid, "task_id is required (use the current task id if that's what "
"you mean — pulls from env but kept explicit here)")
body = _redact(_require_text(args, "body"))
- # Author comes from the worker's runtime identity, never caller args: comments are
- # injected into future workers' system prompts, so an args["author"] override could
- # forge a directive from ``hermes-system``. Cross-task commenting stays unrestricted —
- # it is the handoff channel between tasks.
+ # Author comes from the worker's runtime identity (``_persisted_identity``), never
+ # caller args: comments are injected into future workers' system prompts, so an
+ # args["author"] override could forge a directive from ``hermes-system``.
+ # Cross-task commenting stays unrestricted — it is the handoff channel between tasks.
# Comments are injected into the next worker's system prompt by ``build_worker_context`` as
# ``**{author}** (timestamp): {body}`` — accepting an ``args["author"]`` override let a worker forge a
# comment from an authoritative-looking name like ``hermes-system`` and poison the future-worker context
# with what reads as a system directive. See #19713.
- author = os.environ.get("HERMES_PROFILE") or "worker"
+ author = _persisted_identity()
with _board(args.get("board")) as (kb, conn):
cid = kb.add_comment(conn, tid, author=author, body=str(body))
return _ok(task_id=tid, comment_id=cid)
@@ -1049,7 +1079,7 @@ def _handle_create(args: dict, **kw) -> str:
goal_mode=goal_mode, goal_max_turns=_opt_int(args.get("goal_max_turns")),
completion_contract=args.get("completion_contract"),
initial_status=str(args.get("initial_status") or "running"),
- created_by=os.environ.get("HERMES_PROFILE") or "worker", session_id=session_id)
+ created_by=_persisted_identity(), session_id=session_id)
landed = _fields(kb.get_task(conn, new_tid), _CREATED_FIELDS)
wait = [e for e in kb.list_events(conn, new_tid) if e.kind == "dependency_wait"]
gate = {"gated": True, "gated_by": wait[-1].payload["parent"]} if wait else {"gated": False}