kanban_stop.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """Turn-end guard for kanban workers, which must end with a terminal board tool that hands
  2. the card to whoever owns it next (``kanban_complete``, ``kanban_block``,
  3. ``kanban_request_review``, ``kanban_request_changes``). Some models narrate the next step
  4. and stop with no tool calls; Hermes treats that as a clean exit → ``rc=0`` → dispatcher
  5. ``protocol_violation``. Policy-only: return a bounded synthetic nudge so the loop continues
  6. instead of exiting.
  7. """
  8. from __future__ import annotations
  9. import os
  10. from typing import Any, Iterable, Optional
  11. from agent.delegation_context import owned_kanban_task
  12. # Every tool that ends this worker's responsibility for the card, not just the two that
  13. # close it out: ``kanban_request_review`` moves it to ``review`` (goals.py's continuation /
  14. # finalize prompts tell builders to call it) and ``kanban_request_changes`` returns it to
  15. # ``ready`` (the sdlc-review skill tells reviewers to). Nudging after either asks a worker
  16. # that did the right thing to ``kanban_complete`` a card it must not close.
  17. _TERMINAL_KANBAN_TOOLS = frozenset({
  18. "kanban_complete",
  19. "kanban_block",
  20. "kanban_schedule",
  21. "kanban_request_review",
  22. "kanban_request_changes",
  23. })
  24. _DEFAULT_MAX_ATTEMPTS = 2
  25. def kanban_stop_nudge_enabled() -> bool:
  26. """On when ``HERMES_KANBAN_TASK`` is set for the dispatcher-owned worker, unless
  27. ``HERMES_KANBAN_STOP_NUDGE`` disables it. In-process delegate_task children and cron runs
  28. inherit the env var but own no board task and carry no kanban toolset."""
  29. if (os.environ.get("HERMES_KANBAN_STOP_NUDGE") or "").strip().lower() in {"0", "false", "no", "off"}:
  30. return False
  31. return bool(owned_kanban_task())
  32. def _tool_call_name(tc: Any) -> str:
  33. """Tool name from a dict or object tool call (``function.name`` first, then ``name``)."""
  34. if isinstance(tc, dict):
  35. fn = tc.get("function")
  36. return str((fn.get("name") if isinstance(fn, dict) else tc.get("name")) or "")
  37. fn = getattr(tc, "function", None)
  38. return str((getattr(fn, "name", "") if fn is not None else getattr(tc, "name", "")) or "")
  39. def session_called_kanban_terminal(messages: Iterable[dict] | None) -> bool:
  40. """True if this conversation already invoked a terminal kanban tool."""
  41. for msg in filter(lambda m: isinstance(m, dict), messages or ()):
  42. role = msg.get("role")
  43. if role == "assistant" and any(
  44. _tool_call_name(tc) in _TERMINAL_KANBAN_TOOLS for tc in msg.get("tool_calls") or []
  45. ):
  46. return True
  47. if role == "tool" and str(msg.get("name") or "") in _TERMINAL_KANBAN_TOOLS:
  48. return True
  49. return False
  50. def build_kanban_stop_nudge(
  51. *,
  52. messages: Iterable[dict] | None = None,
  53. attempts: int = 0,
  54. max_attempts: int = _DEFAULT_MAX_ATTEMPTS,
  55. task_id: Optional[str] = None,
  56. ) -> Optional[str]:
  57. """Synthetic follow-up when a kanban worker exits without a terminal tool; ``None`` when
  58. the guard should not fire (not a kanban worker, already completed/blocked, budget exhausted)."""
  59. if (
  60. not kanban_stop_nudge_enabled()
  61. or attempts >= max_attempts
  62. or session_called_kanban_terminal(messages)
  63. ):
  64. return None
  65. tid = (task_id or os.environ.get("HERMES_KANBAN_TASK") or "").strip() or "this task"
  66. # The transcript is the status source: this text is only reached when the session made no
  67. # handoff call, so it never tells a worker to close a card it already sent to review.
  68. return (
  69. "[System: You are a Hermes kanban worker. A plain-text reply is NOT a "
  70. "terminal state for the board.\n\n"
  71. f"Task `{tid}` has not been handed off: this session made no terminal board "
  72. "call (`kanban_complete` / `kanban_request_review` / `kanban_block`). Ending now "
  73. "causes a protocol violation (clean exit with the card still `running`).\n\n"
  74. "Do this immediately in your next response — do not narrate intent:\n"
  75. "1. Finish any remaining deliverable (write the required file(s) now).\n"
  76. "2. Call `kanban_complete(summary=..., artifacts=[...])` if the work is done "
  77. "and needs no review, `kanban_request_review(summary=...)` if it is a code "
  78. "change that needs same-card review, OR `kanban_block(reason=...)` if you are "
  79. "blocked. Reviewers approve with `kanban_complete` or send the card back with "
  80. "`kanban_request_changes(reason=...)`.\n\n"
  81. "Never end a turn with only a promise of future action. Repeated "
  82. "protocol violations will block this task and require manual intervention.]"
  83. )
  84. __all__ = ["build_kanban_stop_nudge", "kanban_stop_nudge_enabled", "session_called_kanban_terminal"]