Skip to content

The agent that grows with you

refactor(kanban): worker-log rotation and _relative_age move to topical siblings

Tekniume3f75a002557
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index e924027baa1..5f5e79f07d7 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -324,26 +324,6 @@ def _resolve_rate_limit_cooldown_seconds() -> int:
return _env_int("HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS", DEFAULT_RATE_LIMIT_COOLDOWN_SECONDS)
-def _relative_age(ts: Optional[int], now: Optional[int] = None) -> str:
- """``just now`` / ``18h ago`` / ``3d ago``; "" for a missing/invalid ts. An LLM
- reads a bare absolute timestamp as current fact — the relative age is what
- prompts a worker to re-verify stale sibling work."""
- try:
- ts = int(ts)
- except (TypeError, ValueError):
- return ""
- if now is None:
- now = int(time.time())
- delta = now - ts
- if delta < 60: # includes negative = clock skew across machines; never claim "in the future"
- return "just now"
- if delta < 3600:
- return f"{delta // 60}m ago"
- if delta < 86400:
- return f"{delta // 3600}h ago"
- return f"{delta // 86400}d ago"
-
-
# --- Paths ---
DEFAULT_BOARD = "default"
diff --git a/hermes_cli/kanban_db_context.py b/hermes_cli/kanban_db_context.py
index bdef72e14e2..4f204c7cc99 100644
--- a/hermes_cli/kanban_db_context.py
+++ b/hermes_cli/kanban_db_context.py
@@ -27,6 +27,26 @@ _CTX_MAX_BODY_BYTES = 8 * 1024 # per task.body (opening post)
_CTX_MAX_COMMENT_BYTES = 2 * 1024 # per comment
+def _relative_age(ts: Optional[int], now: Optional[int] = None) -> str:
+ """``just now`` / ``18h ago`` / ``3d ago``; "" for a missing/invalid ts. An LLM
+ reads a bare absolute timestamp as current fact — the relative age is what
+ prompts a worker to re-verify stale sibling work."""
+ try:
+ ts = int(ts)
+ except (TypeError, ValueError):
+ return ""
+ if now is None:
+ now = int(time.time())
+ delta = now - ts
+ if delta < 60: # includes negative = clock skew across machines; never claim "in the future"
+ return "just now"
+ if delta < 3600:
+ return f"{delta // 60}m ago"
+ if delta < 86400:
+ return f"{delta // 3600}h ago"
+ return f"{delta // 86400}d ago"
+
+
def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:
"""Truncate to ``limit`` chars with a visible ellipsis."""
if not s:
@@ -40,7 +60,7 @@ def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:
def _ctx_stamp(ts: int, now: int) -> str:
"""``YYYY-MM-DD HH:MM`` plus a relative age when one is available."""
disp = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts))
- age = _kb._relative_age(ts, now)
+ age = _relative_age(ts, now)
return f"{disp}, {age}" if age else disp
@@ -160,7 +180,7 @@ def _ctx_parent_results(lines: list[str], conn: sqlite3.Connection, task_id: str
)
wrote_header = True
done_ts = run.ended_at if run is not None and run.ended_at else (pt.completed_at or None)
- age = _kb._relative_age(done_ts, now)
+ age = _relative_age(done_ts, now)
lines.append(f"### {pid}" + (f" (completed {age})" if age else ""))
if run is not None and run.summary and run.summary.strip():
lines.append(_ctx_cap(run.summary))
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index d4be600af9c..de395318696 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -36,10 +36,6 @@ if TYPE_CHECKING:
# dispatcher parks the task in ``blocked`` with a reason — prevents retry storms.
DEFAULT_FAILURE_LIMIT = 2
-# Worker log files larger than this at spawn time are rotated.
-DEFAULT_LOG_ROTATE_BYTES = 2 * 1024 * 1024 # 2 MiB
-DEFAULT_LOG_BACKUP_COUNT = 1
-
# Keep a little wall-clock budget for the worker to observe a terminal timeout
# and make a terminal board call (kanban_block/kanban_complete/kanban_request_review)
# before max_runtime_seconds kills it.
@@ -2469,58 +2465,6 @@ def _positive_int(value: Any, default: int, *, minimum: int = 1) -> int:
return parsed if parsed >= minimum else default
-def worker_log_rotation_config(kanban_cfg: Optional[dict] = None) -> tuple[int, int]:
- """Return ``(rotate_bytes, backup_count)`` for worker log rotation.
- Defaults: rotate at 2 MiB, keep one backup (``.log.1``); both overridable
- from ``config.yaml``.
- """
- if kanban_cfg is None:
- try:
- from hermes_cli.config import load_config
-
- kanban_cfg = (load_config().get("kanban") or {})
- except Exception:
- kanban_cfg = {}
- kanban_cfg = kanban_cfg or {}
- max_bytes = _positive_int(kanban_cfg.get("worker_log_rotate_bytes"), DEFAULT_LOG_ROTATE_BYTES, minimum=1)
- backup_count = _positive_int(kanban_cfg.get("worker_log_backup_count"), DEFAULT_LOG_BACKUP_COUNT, minimum=0)
- return max_bytes, backup_count
-
-
-def _rotated_log_path(log_path: Path, generation: int) -> Path:
- return log_path.with_suffix(log_path.suffix + f".{generation}")
-
-
-def _rotate_worker_log(
- log_path: Path,
- max_bytes: int,
- backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
-) -> None:
- """Rotate ``<log>`` when it exceeds ``max_bytes``: ``<log>`` → ``<log>.1``,
- older generations shift up to ``backup_count``.
- """
- try:
- if not log_path.exists() or log_path.stat().st_size <= max_bytes:
- return
- backup_count = _positive_int(backup_count, DEFAULT_LOG_BACKUP_COUNT, minimum=0)
- if backup_count == 0:
- log_path.unlink()
- return
- oldest = _rotated_log_path(log_path, backup_count)
- with contextlib.suppress(OSError):
- if oldest.exists():
- oldest.unlink()
- for generation in range(backup_count - 1, 0, -1):
- src = _rotated_log_path(log_path, generation)
- if not src.exists():
- continue
- with contextlib.suppress(OSError):
- src.rename(_rotated_log_path(log_path, generation + 1))
- log_path.rename(_rotated_log_path(log_path, 1))
- except OSError:
- pass
-
-
def _module_hermes_argv() -> list[str]:
"""Interpreter-bound Hermes CLI invocation (``hermes_cli.main`` is the
console-script target — there is no top-level ``hermes`` package)."""
@@ -2765,8 +2709,8 @@ def _open_worker_log(task: Task, board: Optional[str]):
log_dir = _kb.worker_logs_dir(board=board)
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{task.id}.log"
- rotate_bytes, backup_count = worker_log_rotation_config()
- _rotate_worker_log(log_path, rotate_bytes, backup_count)
+ from hermes_cli.kanban_worker_log import rotate_worker_log, worker_log_rotation_config
+ rotate_worker_log(log_path, *worker_log_rotation_config())
return open(log_path, "ab")
diff --git a/hermes_cli/kanban_worker_log.py b/hermes_cli/kanban_worker_log.py
new file mode 100644
index 00000000000..78f1bd24a4a
--- /dev/null
+++ b/hermes_cli/kanban_worker_log.py
@@ -0,0 +1,64 @@
+"""Per-task worker log rotation, split out of ``hermes_cli.kanban_db_dispatch``."""
+
+from __future__ import annotations
+
+import contextlib
+from pathlib import Path
+from typing import Optional
+
+DEFAULT_LOG_ROTATE_BYTES = 2 * 1024 * 1024 # 2 MiB
+DEFAULT_LOG_BACKUP_COUNT = 1
+
+
+def worker_log_rotation_config(kanban_cfg: Optional[dict] = None) -> tuple[int, int]:
+ """Return ``(rotate_bytes, backup_count)`` for worker log rotation.
+ Defaults: rotate at 2 MiB, keep one backup (``.log.1``); both overridable
+ from ``config.yaml``.
+ """
+ if kanban_cfg is None:
+ try:
+ from hermes_cli.config import load_config
+
+ kanban_cfg = (load_config().get("kanban") or {})
+ except Exception:
+ kanban_cfg = {}
+ kanban_cfg = kanban_cfg or {}
+ from hermes_cli.kanban_db_dispatch import _positive_int
+ max_bytes = _positive_int(kanban_cfg.get("worker_log_rotate_bytes"), DEFAULT_LOG_ROTATE_BYTES, minimum=1)
+ backup_count = _positive_int(kanban_cfg.get("worker_log_backup_count"), DEFAULT_LOG_BACKUP_COUNT, minimum=0)
+ return max_bytes, backup_count
+
+
+def _rotated_log_path(log_path: Path, generation: int) -> Path:
+ return log_path.with_suffix(log_path.suffix + f".{generation}")
+
+
+def rotate_worker_log(
+ log_path: Path,
+ max_bytes: int,
+ backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
+) -> None:
+ """Rotate ``<log>`` when it exceeds ``max_bytes``: ``<log>`` → ``<log>.1``,
+ older generations shift up to ``backup_count``.
+ """
+ try:
+ if not log_path.exists() or log_path.stat().st_size <= max_bytes:
+ return
+ from hermes_cli.kanban_db_dispatch import _positive_int
+ backup_count = _positive_int(backup_count, DEFAULT_LOG_BACKUP_COUNT, minimum=0)
+ if backup_count == 0:
+ log_path.unlink()
+ return
+ oldest = _rotated_log_path(log_path, backup_count)
+ with contextlib.suppress(OSError):
+ if oldest.exists():
+ oldest.unlink()
+ for generation in range(backup_count - 1, 0, -1):
+ src = _rotated_log_path(log_path, generation)
+ if not src.exists():
+ continue
+ with contextlib.suppress(OSError):
+ src.rename(_rotated_log_path(log_path, generation + 1))
+ log_path.rename(_rotated_log_path(log_path, 1))
+ except OSError:
+ pass