Skip to content

The agent that grows with you

refactor(hermes_cli): join wrapped kanban call/arg lists; tighten env_loader guard comments (code AST-identical)

Tekniumf0b1d49d0f06
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index 003fe45c52e..e7bc1433d66 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -15,60 +15,44 @@ from utils import atomic_replace, fast_safe_load
logger = logging.getLogger(__name__)
-# Env var name suffixes that indicate credential values. These are the ONLY env vars whose
-# values we sanitize on load — we must not silently alter arbitrary user env vars, but
+# The ONLY env vars sanitized on load: we must not silently alter arbitrary user env vars, but
# credentials are known to require pure ASCII (they become HTTP header values).
_CREDENTIAL_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_KEY")
-# Names already warned about this process, so repeated load_hermes_dotenv() calls (user env +
-# project env, gateway hot-reload, tests) don't spam the same warning.
-_WARNED_KEYS: set[str] = set()
-
-# Paths already given the UTF-32 refuse-to-mangle warning (once per path is enough).
-_WARNED_UTF32_PATHS: set[str] = set()
+# Once-per-process guards: load_hermes_dotenv() is called repeatedly (user env + project env,
+# gateway hot-reload, lazy imports mid-turn, tests) so warnings/logs fire once per key/path/home.
+_WARNED_KEYS: set[str] = set() # credential names already given the non-ASCII warning
+_WARNED_UTF32_PATHS: set[str] = set() # .env paths already given the UTF-32 refuse-to-mangle warning
+_SCOPED_SKIP_LOGGED: set[str] = set() # routed profile homes whose multiplex dotenv skip was logged
# env-var name → source label ("bitwarden", …) for credentials injected by an external secret
-# source during load_hermes_dotenv(). Setup / `hermes model` use it to label detected credentials
-# so users know WHERE a key came from when their .env doesn't contain it directly.
+# source. Setup / `hermes model` use it so users know WHERE a key came from when .env lacks it.
_SECRET_SOURCES: dict[str, str] = {}
-# Applied values are immutable per-home snapshots. ``os.environ`` is shared across profiles and
+# Applied values are immutable per-home snapshots: ``os.environ`` is shared across profiles and
# may be overwritten by a later home's source apply.
_SECRET_SOURCE_VALUES_BY_HOME: dict[str, dict[str, str]] = {}
-
-# HERMES_HOME paths already pulled external secrets for this process. load_hermes_dotenv() runs
-# at import time from several hot modules (cli.py, hermes_cli/main.py, run_agent.py, gateway/
-# run.py, …); without this guard the Bitwarden status line prints 3-5x per startup and the config
-# re-parse + ASCII sweep re-run each time (Bitwarden's own cache only saves the network call).
+# HERMES_HOME paths already pulled external secrets for. load_hermes_dotenv() runs at import time
+# from several hot modules (cli.py, hermes_cli/main.py, run_agent.py, gateway/run.py, …); without
+# this the Bitwarden status line prints 3-5x per startup and the config re-parse + ASCII sweep
+# re-run each time (Bitwarden's own cache only saves the network call).
_APPLIED_HOMES: set[str] = set()
_SECRET_SOURCE_CACHE_LOCK = threading.RLock()
-# Routed profile homes whose dotenv load was skipped under multiplex, so the skip is logged once
-# per home rather than on every lazy import mid-turn.
-_SCOPED_SKIP_LOGGED: set[str] = set()
-
-
-# Behavioral routing keys a parent Hermes process injects into child env and that silently
-# redirect a profile onto the wrong provider path (ACP auth method, copilot-ACP endpoints).
-# These — and ONLY these — are scrubbed from os.environ at startup when absent from the
-# profile's .env. Credential keys are excluded: shell exports are a legitimate, documented way
-# to supply them, and read-time secret-scope checks (agent/secret_scope.py) own cross-profile
-# credential isolation.
+# Behavioral routing keys a parent Hermes process injects into child env that silently redirect a
+# profile onto the wrong provider path. These — and ONLY these — are scrubbed from os.environ at
+# startup when absent from the profile's .env. Credential keys are excluded: shell exports are a
+# legitimate, documented way to supply them, and read-time secret-scope checks
+# (agent/secret_scope.py) own cross-profile credential isolation.
_PROFILE_MANAGED_ENV_KEYS: frozenset[str] = frozenset({
- "HERMES_ACP_AUTH_METHOD",
- "HERMES_ACP_AUTO_APPROVE",
- "HERMES_COPILOT_ACP_COMMAND",
- "HERMES_COPILOT_ACP_ARGS",
- "COPILOT_CLI_PATH",
- "COPILOT_ACP_BASE_URL",
+ "HERMES_ACP_AUTH_METHOD", "HERMES_ACP_AUTO_APPROVE", "HERMES_COPILOT_ACP_COMMAND",
+ "HERMES_COPILOT_ACP_ARGS", "COPILOT_CLI_PATH", "COPILOT_ACP_BASE_URL",
})
def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
- """KEY names assigned in a dotenv file (including empty ``KEY=``).
-
- A fast line scanner rather than full dotenv parsing, so it works during early bootstrap without
- importing python-dotenv. Decode errors fall back to ``latin-1``, matching ``_load_dotenv_with_fallback``.
- """
+ """KEY names assigned in a dotenv file (including empty ``KEY=``). A fast line scanner, not full
+ dotenv parsing, so it works during early bootstrap without importing python-dotenv; decode
+ errors fall back to ``latin-1`` like ``_load_dotenv_with_fallback``."""
keys: set[str] = set()
try:
text = path.read_text(encoding="utf-8", errors="replace")
@@ -88,11 +72,8 @@ def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
def _clear_known_keys_missing_from_dotenv(path: Path) -> None:
- """Delete inherited ``_PROFILE_MANAGED_ENV_KEYS`` from ``os.environ`` that ``.env`` does not define.
-
- Runs after the profile's ``.env`` loaded with ``override=True``. Scope is deliberately NARROW:
- only the behavioral routing keys that change *which provider path* a profile uses.
- """
+ """After ``.env`` loaded with ``override=True``, delete inherited ``_PROFILE_MANAGED_ENV_KEYS``
+ it does not define. Deliberately NARROW: only keys that change *which provider path* is used."""
if not path.exists():
return
defined = _env_keys_defined_in_dotenv(path)
@@ -102,11 +83,9 @@ def _clear_known_keys_missing_from_dotenv(path: Path) -> None:
def get_secret_source(env_var: str) -> str | None:
- """Label of the secret source that supplied ``env_var`` (``"bitwarden"`` …), or None for .env/shell keys.
-
- Metadata only -- credential-pool persistence may store it to explain a borrowed secret's origin
- but must never treat it as authorization to persist the raw value.
- """
+ """Source label that supplied ``env_var`` (``"bitwarden"`` …), None for .env/shell keys. Metadata
+ only -- credential-pool persistence may store it to explain a borrowed secret's origin but must
+ never treat it as authorization to persist the raw value."""
return _SECRET_SOURCES.get(env_var)
@@ -119,11 +98,10 @@ def hydrate_profile_secret_sources(hermes_home: str | os.PathLike) -> dict[str,
"""Resolve one profile's configured sources without mutating ``os.environ``.
Multiplex gateways can route a first turn to a secondary profile that never ran the process-
- global dotenv startup path. Resolve its sources against a private mapping seeded from its own
- ``.env`` and record the usual per-home snapshot for ``build_profile_secret_scope()``.
-
- Fail-open and once-per-home semantics intentionally mirror ``_apply_external_secret_sources``.
- The result contains only values contributed by external sources, never plaintext ``.env`` entries.
+ global dotenv startup path: resolve against a private mapping seeded from its own ``.env`` and
+ record the per-home snapshot for ``build_profile_secret_scope()``. Fail-open and once-per-home
+ semantics mirror ``_apply_external_secret_sources``; the result holds only values contributed
+ by external sources, never plaintext ``.env`` entries.
"""
with _SECRET_SOURCE_CACHE_LOCK:
return _hydrate_profile_secret_sources(Path(hermes_home))
@@ -148,9 +126,8 @@ def _hydrate_profile_secret_sources(home: Path) -> dict[str, str]:
local_env = {name: value for name, value in os.environ.items() if _is_global_env(name)}
local_env.update(load_env_file(home / ".env"))
- # Mirror load_hermes_dotenv()'s .op.env bootstrap: the 1Password service-account token
- # lives in <home>/.op.env (gitignored), not .env; without it a cold profile on the .op.env
- # flow fails 1Password hydration. .env values win — never override an existing key.
+ # Mirror load_hermes_dotenv()'s .op.env bootstrap (1Password service-account token lives in
+ # gitignored <home>/.op.env, not .env) or cold profiles fail 1Password hydration. .env wins.
op_env = home / ".op.env"
if op_env.exists():
for _name, _value in load_env_file(op_env).items():
@@ -177,23 +154,21 @@ def _hydrate_profile_secret_sources(home: Path) -> dict[str, str]:
def reset_secret_source_cache() -> None:
- """Forget which HERMES_HOME paths already had external secrets applied, forcing a re-pull
- (tests, long-running processes after a config change)."""
+ """Forget applied homes so the next load re-pulls (tests, long-running processes after config edits)."""
_APPLIED_HOMES.clear()
_SECRET_SOURCES.clear()
_SECRET_SOURCE_VALUES_BY_HOME.clear()
def format_secret_source_suffix(env_var: str) -> str:
- """``" (from Bitwarden)"``-style suffix, or ``""`` for .env/shell credentials (the implicit
- default users already understand — only external sources get called out)."""
+ """``" (from Bitwarden)"``-style suffix; ``""`` for .env/shell credentials (the implicit default
+ users already understand — only external sources get called out)."""
source = get_secret_source(env_var)
if not source:
return ""
if source == "bitwarden":
return " (from Bitwarden)"
- # Registry label (e.g. "1Password"); raw source name for labels the registry doesn't know
- # (stale provenance from an uninstalled plugin, tests).
+ # Registry label (e.g. "1Password"); raw name for unknown sources (uninstalled plugin, tests).
try:
from agent.secret_sources.registry import get_source
@@ -221,10 +196,8 @@ def _format_offending_chars(value: str, limit: int = 3) -> str:
def _sanitize_loaded_credentials() -> None:
- """Strip non-ASCII characters from credential env vars (``_CREDENTIAL_SUFFIXES``) in os.environ.
-
- Called after dotenv loads so the rest of the codebase never sees non-ASCII API keys.
- """
+ """Strip non-ASCII from credential env vars (``_CREDENTIAL_SUFFIXES``) after dotenv loads, so the
+ rest of the codebase never sees non-ASCII API keys."""
for key, value in list(os.environ.items()):
if not any(key.endswith(suffix) for suffix in _CREDENTIAL_SUFFIXES):
continue
@@ -256,9 +229,8 @@ def _sanitize_loaded_credentials() -> None:
def _load_dotenv_with_fallback(path: Path, *, override: bool) -> None:
try:
- # utf-8-sig strips a leading UTF-8 BOM (PowerShell 5.1 Set-Content -Encoding UTF8 /
- # Notepad) and is a no-op otherwise. Plain "utf-8" would keep U+FEFF on the first key
- # name and silently drop it from os.environ under its canonical name.
+ # utf-8-sig strips a leading UTF-8 BOM (PowerShell 5.1 / Notepad); plain "utf-8" would keep
+ # U+FEFF on the first key name and silently drop it from os.environ under its canonical name.
load_dotenv(dotenv_path=path, override=override, encoding="utf-8-sig")
except UnicodeDecodeError:
# utf-8-sig can't strip a BOM once we fall back to latin-1 decode.
@@ -266,21 +238,18 @@ def _load_dotenv_with_fallback(path: Path, *, override: bool) -> None:
if raw.startswith(codecs.BOM_UTF8):
raw = raw[len(codecs.BOM_UTF8) :]
load_dotenv(stream=io.StringIO(raw.decode("latin-1")), override=override)
- # API keys must be pure ASCII (httpx encodes headers as ASCII); non-ASCII typically comes
- # from copy-pasting keys from PDFs / rich-text editors that substitute lookalike glyphs.
+ # API keys must be pure ASCII (httpx encodes headers as ASCII); non-ASCII typically comes from
+ # keys copy-pasted out of PDFs / rich-text editors that substitute lookalike glyphs.
_sanitize_loaded_credentials()
def _sanitize_env_file_if_needed(path: Path) -> None:
"""Pre-sanitize a .env file before python-dotenv reads it.
- Encoding: sniffs a leading BOM *before* any text decode. UTF-16 (Notepad "Unicode") is decoded
- correctly and rewritten as clean UTF-8. UTF-32 is refused (left untouched) so we never fall
- through to the errors=replace corruption path. Order of BOM checks matters: UTF-32-LE's BOM
- starts with UTF-16-LE's FF FE.
-
- ``hermes_cli.config._sanitize_env_lines`` normalizes line endings while treating content after
- the first ``=`` as opaque for boundary discovery.
+ Sniffs a leading BOM *before* any text decode: UTF-16 (Notepad "Unicode") is decoded and
+ rewritten as clean UTF-8; UTF-32 is refused (left untouched) so we never fall through to the
+ errors=replace corruption path. ``hermes_cli.config._sanitize_env_lines`` normalizes line
+ endings while treating content after the first ``=`` as opaque for boundary discovery.
"""
if not path.exists():
return
@@ -294,8 +263,8 @@ def _sanitize_env_file_if_needed(path: Path) -> None:
except Exception:
return
- # Sniff BOM bytes BEFORE decoding. ORDER MATTERS: BOM_UTF32_LE (FF FE 00 00) startswith
- # BOM_UTF16_LE (FF FE); checking UTF-16 first would misdetect UTF-32-LE and mangle the file.
+ # ORDER MATTERS: BOM_UTF32_LE (FF FE 00 00) startswith BOM_UTF16_LE (FF FE); checking UTF-16
+ # first would misdetect UTF-32-LE and mangle the file.
force_utf8_rewrite = False
if raw.startswith(codecs.BOM_UTF32_LE) or raw.startswith(codecs.BOM_UTF32_BE):
path_key = str(path.resolve())
@@ -308,17 +277,15 @@ def _sanitize_env_file_if_needed(path: Path) -> None:
)
return
if raw.startswith(codecs.BOM_UTF16_LE) or raw.startswith(codecs.BOM_UTF16_BE):
- # "utf-16" uses the BOM to select endianness and strips it. TextIOWrapper + newline=None
- # matches open()'s universal-newlines splitting (\n/\r\n/\r only — not splitlines()'s
- # extra Unicode boundaries like U+2028), so sanitize sees the same lines as the UTF-8 path.
+ # "utf-16" uses the BOM for endianness and strips it. newline=None matches open()'s
+ # universal-newlines splitting (\n/\r\n/\r only — not splitlines()'s extra Unicode
+ # boundaries like U+2028), so sanitize sees the same lines as the UTF-8 path.
try:
with io.TextIOWrapper(io.BytesIO(raw), encoding="utf-16", newline=None) as f:
original = f.readlines()
except UnicodeDecodeError:
return
- # Source is UTF-16 on disk; always rewrite as clean UTF-8 so the utf-8 dotenv load sees
- # a canonical file.
- force_utf8_rewrite = True
+ force_utf8_rewrite = True # always rewrite UTF-16 as UTF-8 so the dotenv load sees a canonical file
else:
# utf-8-sig strips a UTF-8 BOM; errors=replace so embedded NULs can be stripped below.
try:
@@ -326,16 +293,14 @@ def _sanitize_env_file_if_needed(path: Path) -> None:
original = f.readlines()
except Exception:
return
- # Defense-in-depth: errors=replace turns undecodable leading bytes into U+FFFD; persisting
- # that glues replacement chars onto the first key name and rewrites the file permanently.
- # Leave the file untouched rather than write the mangling.
+ # errors=replace turns undecodable leading bytes into U+FFFD; persisting that would glue
+ # replacement chars onto the first key name permanently. Leave the file untouched instead.
if original and original[0].startswith("\ufffd"):
return
try:
- # Strip NULs before _sanitize_env_lines so they never reach python-dotenv (which passes
- # them to os.environ and crashes with ValueError). Also intentionally repairs BOM-less
- # UTF-16 (NUL-padded ASCII) into clean UTF-8.
+ # Strip NULs so they never reach python-dotenv (os.environ raises ValueError on them); this
+ # also intentionally repairs BOM-less UTF-16 (NUL-padded ASCII) into clean UTF-8.
stripped = [line.replace("\x00", "") for line in original]
sanitized = _sanitize_env_lines(stripped)
if sanitized != original or force_utf8_rewrite:
@@ -363,19 +328,15 @@ def load_hermes_dotenv(
project_env: str | os.PathLike | None = None,
load_external_secrets: bool = True,
) -> list[Path]:
- """Load Hermes environment files with user config taking precedence.
-
- ``~/.hermes/.env`` overrides stale shell-exported values when present; project ``.env`` is a dev
- fallback that only fills missing values when the user env exists, and overrides stale shell vars
- when it does not.
- """
+ """Load Hermes env files, user config first: ``~/.hermes/.env`` overrides stale shell exports;
+ project ``.env`` is a dev fallback that only fills gaps when the user env exists (and overrides
+ stale shell vars when it does not)."""
home_path = Path(hermes_home or os.getenv("HERMES_HOME", Path.home() / ".hermes"))
- # A multiplex gateway hosts every profile in one process. While a routed profile-home override
- # is active, copying that profile's .env into os.environ would expose its credentials to
- # sibling turns and every subsequently spawned child. An unscoped startup load remains process
- # configuration and keeps the normal path. External secret sources still need their refresh,
- # so resolve them against the profile-local mapping instead of returning before hydration.
+ # A multiplex gateway hosts every profile in one process: while a routed profile-home override
+ # is active, copying that profile's .env into os.environ would expose its credentials to sibling
+ # turns and every spawned child. An unscoped startup load is process configuration and keeps the
+ # normal path. External sources still refresh, against the profile-local mapping.
from agent.secret_scope import is_multiplex_active
from hermes_constants import get_hermes_home_override
@@ -412,11 +373,10 @@ def load_hermes_dotenv(
# profile's .env do not leak into the runtime.
_clear_known_keys_missing_from_dotenv(user_env)
- # Load .op.env AFTER .env so .env values win, but the bootstrap token (OP_SERVICE_ACCOUNT_TOKEN)
- # is available for apply_onepassword_secrets() even in cron / subprocess environments that
- # inherit no shell state. .op.env is gitignored — the token never enters the committed .env.
- # A systemd `EnvironmentFile=-/path/to/.hermes/.op.env` takes precedence (override=False
- # ensures .op.env never clobbers a token already in the environment).
+ # .op.env AFTER .env so .env wins, but the bootstrap OP_SERVICE_ACCOUNT_TOKEN is available to
+ # apply_onepassword_secrets() even in cron / subprocesses with no shell state. It is gitignored
+ # so the token never enters the committed .env; override=False lets a systemd
+ # `EnvironmentFile=-…/.op.env` token take precedence.
op_env = home_path / ".op.env"
if op_env.exists() and not os.environ.get("OP_SERVICE_ACCOUNT_TOKEN"):
_load_dotenv_with_fallback(op_env, override=False)
@@ -425,40 +385,32 @@ def load_hermes_dotenv(
_load_dotenv_with_fallback(project_env_path, override=not loaded)
loaded.append(project_env_path)
- # External secret sources are skipped in two updater situations (dotenv and managed env still
- # load; only external source resolution is unnecessary for the updater):
- # 1. ``load_external_secrets=False`` — an ``update`` invocation that must not import optional
- # secret-manager libraries (Bitwarden → cryptography → ``_rust.pyd``) into the process that
- # replaces that same environment on Windows.
- # 2. A fresh ``hermes update`` retry just completed a deferred dependency install before
- # importing this module. Mapping native secret-source deps in that same updater process
- # would make the self-lock preflight recreate the marker and exit 2 again.
+ # External sources are skipped for the updater (dotenv + managed env still load):
+ # 1. ``load_external_secrets=False`` — ``update`` must not import optional secret-manager libs
+ # (Bitwarden → cryptography → ``_rust.pyd``) into the process replacing that env on Windows.
+ # 2. A fresh ``hermes update`` retry just completed a deferred dependency install; mapping native
+ # secret-source deps in that process would make the self-lock preflight exit 2 again.
from hermes_cli import _early_recovery
if load_external_secrets and not _early_recovery._should_skip_external_secret_sources():
_apply_external_secret_sources(home_path)
_apply_managed_env()
- # config.yaml is the source of truth for terminal.* settings, but the dotenv loads above run
- # with override=True — so a stale TERMINAL_ENV=docker left in ~/.hermes/.env (e.g. by an older
- # `hermes setup`) would silently win on every reload. Startup launchers bridge config→env
- # once, but long-lived processes (gateway per-turn reload, cron standalone runs) call this
- # repeatedly and used to flip the effective backend back to the stale .env value mid-session.
- # Re-apply config.yaml's explicit terminal keys LAST, after _apply_managed_env(), so the merged
- # config (already carrying the managed overlay) is what lands in the env.
+ # config.yaml owns terminal.* settings, but the override=True loads above let a stale
+ # TERMINAL_ENV=docker in ~/.hermes/.env (older `hermes setup`) win on every reload; long-lived
+ # processes (gateway per-turn reload, cron) call this repeatedly and used to flip the backend
+ # back mid-session. Re-apply config.yaml's explicit terminal keys LAST, after
+ # _apply_managed_env(), so the merged config (with the managed overlay) lands in the env.
_reapply_terminal_config_bridge(home_path)
return loaded
def _reapply_terminal_config_bridge(home_path: Path) -> None:
- """Re-assert config.yaml's explicit ``terminal.*`` keys over reloaded .env.
-
- Delegates to ``hermes_cli.config.apply_terminal_config_to_env`` — the single shared bridge
- (terminal_tool's fallback and the TUI/dashboard launchers use it too) — so key coverage,
- explicit-keys-only override semantics, cwd placeholder handling, and the managed-scope overlay
- can't drift between bridge sites.
- """
+ """Re-assert config.yaml's explicit ``terminal.*`` keys over reloaded .env via the single shared
+ bridge ``hermes_cli.config.apply_terminal_config_to_env`` (also used by terminal_tool's fallback
+ and the TUI/dashboard launchers) so coverage, explicit-keys-only semantics, cwd placeholders and
+ the managed-scope overlay can't drift between sites."""
try:
if Path(home_path).resolve() != _process_hermes_home().resolve():
return
@@ -472,10 +424,9 @@ def _reapply_terminal_config_bridge(home_path: Path) -> None:
def _apply_managed_env() -> None:
"""Apply the managed-scope .env last, with override, so it beats user/shell.
- This does NOT stop the agent from later mutating ``os.environ`` in-process or ``export``-ing in
- a subprocess shell; that hard boundary is a documented v2 item (design §8.1) — v1 relies on
- filesystem permissions only. Fail-open: a missing managed dir/.env is the common no-op case,
- and any error is swallowed so managed scope can never block startup.
+ Does NOT stop the agent from later mutating ``os.environ`` or ``export``-ing in a subprocess
+ shell — that hard boundary is a documented v2 item (design §8.1); v1 relies on filesystem
+ permissions. Fail-open: missing dir/.env is the common no-op; errors never block startup.
"""
try:
from hermes_cli import managed_scope
@@ -495,14 +446,11 @@ def _apply_managed_env() -> None:
def _apply_external_secret_sources(home_path: Path) -> None:
"""Pull secrets from every enabled external source into env.
- Runs AFTER dotenv loads so .env values are visible (sources use them to locate bootstrap tokens)
- but BEFORE the rest of Hermes reads ``os.environ`` for credentials. Any failure is logged and
- swallowed — external secret sources must never block startup.
-
- Source ordering, mapped-beats-bulk precedence, first-claim-wins conflicts, override semantics
- and provenance live in ``agent.secret_sources.registry.apply_all``; this wrapper owns the
- once-per-HERMES_HOME guard, the post-apply ASCII sweep, the ``_SECRET_SOURCES`` provenance map
- that UI surfaces read, and the startup status lines.
+ Runs AFTER dotenv loads (sources use .env values to locate bootstrap tokens) but BEFORE Hermes
+ reads ``os.environ`` for credentials; failures are swallowed — sources must never block startup.
+ Ordering, mapped-beats-bulk precedence, first-claim-wins conflicts and provenance live in
+ ``agent.secret_sources.registry.apply_all``; this wrapper owns the once-per-HERMES_HOME guard,
+ the post-apply ASCII sweep, the ``_SECRET_SOURCES`` map UI surfaces read, and status lines.
"""
home_key = str(Path(home_path).resolve())
if home_key in _APPLIED_HOMES:
@@ -515,16 +463,14 @@ def _apply_external_secret_sources(home_path: Path) -> None:
# disable secret loading for this process even after the user fixes the file.
return
if not cfg:
- # No secrets section (or everything disabled at parse level). Not marked applied either —
- # the re-parse is a cheap fast_safe_load, and leaving the home unmarked lets a process
- # pick up a config change on its next load_hermes_dotenv() call instead of never.
+ # No secrets section. Not marked applied either — the re-parse is a cheap fast_safe_load and
+ # an unmarked home picks up a config change on the next load_hermes_dotenv() instead of never.
return
# Defer the registry import until a source is enabled — agent.secret_sources.bitwarden eagerly
# loads cryptography._rust.pyd, which makes the Windows updater self-lock before its preflight.
- # Enabled-ness is detected by *shape* (source dict with enabled flag) rather than hardcoded
- # names, so plugin/test sources pass through unknown keys and a generic dict entry never
- # forces the crypto load on every launch.
+ # Detect by *shape* (dict with enabled flag), not hardcoded names, so plugin/test sources pass
+ # and a generic dict entry never forces the crypto load on every launch.
any_enabled = any(isinstance(v, dict) and v.get("enabled") is True for v in cfg.values())
if not any_enabled:
return
@@ -540,22 +486,18 @@ def _apply_external_secret_sources(home_path: Path) -> None:
return
if not report.sources:
- # Config parsed but no source is enabled: keep retrying cheaply (no fetch happens for
- # disabled sources) so flipping a source on mid-process takes effect on the next call.
+ # No source enabled: keep retrying cheaply so flipping one on mid-process takes effect.
return
# A real fetch attempt happened (success OR error). Mark the home now so the 3-5 import-time
- # load_hermes_dotenv() calls per startup don't re-fetch / re-print — error retries within one
- # process are opt-in via reset_secret_source_cache(). Marking AFTER the attempt (not before)
- # is what keeps the earlier failure paths retryable.
+ # calls per startup don't re-fetch / re-print — error retries are opt-in via
+ # reset_secret_source_cache(). Marking AFTER the attempt keeps the earlier failure paths retryable.
_APPLIED_HOMES.add(home_key)
if report.applied_any:
- # Vault values are user-supplied and may carry the same copy-paste corruption as a
- # manually edited .env — re-run the ASCII sanitization pass.
+ # Vault values are user-supplied and may carry the same copy-paste corruption as .env.
_sanitize_loaded_credentials()
- # Remember where each var came from so setup / `hermes model` can label detected
- # credentials "(from Bitwarden)" / "(from 1Password)" instead of a bare "credentials ✓".
+ # Provenance lets setup / `hermes model` label credentials "(from Bitwarden)" etc.
values: dict[str, str] = {}
for name, applied in report.provenance.items():
_SECRET_SOURCES[name] = applied.source
@@ -582,11 +524,8 @@ def _apply_external_secret_sources(home_path: Path) -> None:
def _remediation_hint(source_name: str, error_kind, secrets_cfg: dict, *, scope: str | None = None) -> str:
- """Ask the failed source for its one-line fix-it hint.
-
- remediation() is a pure mapping and shouldn't raise, but a plugin source could — and startup
- must never break on a status line.
- """
+ """The failed source's one-line fix-it hint. remediation() is a pure mapping and shouldn't raise,
+ but a plugin source could — and startup must never break on a status line."""
try:
from agent.secret_sources.registry import get_source
@@ -601,15 +540,15 @@ def _remediation_hint(source_name: str, error_kind, secrets_cfg: dict, *, scope:
def _load_secrets_config(home_path: Path) -> dict:
- """Read just the ``secrets:`` section out of config.yaml, isolated from the main config loader
- so a malformed config can't take down dotenv loading entirely."""
+ """Read just the ``secrets:`` section of config.yaml, isolated from the main config loader so a
+ malformed config can't take down dotenv loading entirely."""
config_path = home_path / "config.yaml"
if not config_path.exists():
return {}
- # Prefer the shared (mtime, size)-keyed raw-config cache — this is the first config.yaml read
- # in a normal `hermes` startup, so populating it here lets main.py's early bridge and
- # hermes_logging reuse the same parse (one per process instead of 3-4). Falls back to a direct
- # isolated parse if the shared reader is unavailable (it also swallows parse errors -> {}).
+ # Prefer the shared (mtime, size)-keyed raw-config cache: this is the first config.yaml read in
+ # a normal startup, so populating it lets main.py's early bridge and hermes_logging reuse one
+ # parse instead of 3-4. Falls back to a direct isolated parse (the shared reader also swallows
+ # parse errors -> {}).
if home_path == _process_hermes_home():
try:
from hermes_cli.config import read_raw_config
diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.py
index 1e2ac6461bf..d1d24b1aba5 100644
--- a/hermes_cli/kanban.py
+++ b/hermes_cli/kanban.py
@@ -1,9 +1,7 @@
-"""CLI for the Hermes Kanban board — ``hermes kanban …`` subcommand.
-
-All DB work is delegated to ``kanban_db``. This module holds dispatch (``kanban_command``), the
-task-verb handlers, and ``run_slash`` for ``/kanban …`` from the CLI and gateway. Siblings:
-``kanban_parser`` (argparse tree, re-exported as ``build_parser``), ``kanban_output`` (text/--json
-helpers), ``kanban_boards`` (``boards …``), ``kanban_ops`` (dispatch/daemon/tail/watch/gc/repair).
+"""``hermes kanban …`` — dispatch (``kanban_command``), task-verb handlers, ``run_slash`` for ``/kanban``.
+DB work lives in ``kanban_db``; siblings: ``kanban_parser`` (argparse, re-exported ``build_parser``),
+``kanban_output`` (text/--json), ``kanban_boards`` (``boards …``), ``kanban_ops`` (dispatch/daemon/
+tail/watch/gc/repair).
"""
from __future__ import annotations
@@ -32,9 +30,7 @@ from hermes_cli.kanban_ops import (
from hermes_cli.kanban_parser import build_parser # noqa: F401 (re-exported: hermes_cli.main, run_slash)
-# ---------------------------------------------------------------------------
-# Flag parsing helpers
-# ---------------------------------------------------------------------------
+# --- Flag parsing helpers ---
def _none_profile(value: str) -> Optional[str]:
"""``none`` / ``-`` / ``null`` mean "unassign"."""
@@ -77,10 +73,8 @@ def _parse_workspace_flag(value: str) -> tuple[str, Optional[str]]:
if not path:
raise argparse.ArgumentTypeError(f"--workspace {prefix} requires a path after the colon")
return (kind, os.path.expanduser(path))
- raise argparse.ArgumentTypeError(
- f"unknown --workspace value {value!r}: use scratch, worktree, "
- "worktree:<path>, or dir:<path>"
- )
+ raise argparse.ArgumentTypeError(f"unknown --workspace value {value!r}: use scratch, worktree, "
+ "worktree:<path>, or dir:<path>")
def _parse_branch_flag(value: Optional[str]) -> Optional[str]:
@@ -98,51 +92,38 @@ def _parse_branch_flag(value: Optional[str]) -> Optional[str]:
def _check_dispatcher_presence(hermes_home: Optional[Path] = None) -> tuple[bool, str]:
- """``(running, message)`` for the "will anything dispatch this?" warning.
-
- ``running=True`` when a gateway is alive for this HERMES_HOME with ``kanban.dispatch_in_gateway``
- on; otherwise ``False`` plus human guidance. Fails OPEN — import/probe/config errors return
- ``(True, "")`` — since a missed warning beats crying wolf. ``hermes_home`` scopes the probe to a
- profile dir (the dashboard backend may run under a different HERMES_HOME); CLI callers pass None.
+ """``(running, message)`` for the "will anything dispatch this?" warning: True when a gateway is
+ alive for this HERMES_HOME with ``kanban.dispatch_in_gateway`` on, else False + human guidance.
+ Fails OPEN (probe/config errors -> ``(True, "")``) — a missed warning beats crying wolf.
+ ``hermes_home`` scopes the probe to a profile dir (dashboard backend); CLI callers pass None.
"""
try:
from gateway.status import resolve_gateway_liveness # type: ignore
- # Same ladder as the dashboard status endpoints so PID-file-less or cross-container
- # gateways aren't misreported; use_cache=False because this one-shot probe must see now.
+ # Same ladder as the dashboard status endpoints so PID-file-less / cross-container gateways
+ # aren't misreported; use_cache=False because this one-shot probe must see the state now.
liveness = resolve_gateway_liveness(profile_dir=hermes_home, use_cache=False)
except Exception:
return (True, "") # can't probe — silent
- if liveness.probe_error:
- # The resolver swallows per-rung failures; "can't tell" != "no gateway".
+ if liveness.probe_error: # resolver swallows per-rung failures; "can't tell" != "no gateway"
return (True, "")
pid = liveness.pid
# Even if the gateway is up, dispatch_in_gateway may be off (can't tell -> assume default).
- dispatch_on = bool(_kanban_config().get("dispatch_in_gateway", True))
- if pid and dispatch_on:
+ if pid and bool(_kanban_config().get("dispatch_in_gateway", True)):
return (True, f"gateway pid={pid}, dispatch enabled")
if pid:
- return (
- False,
- "Gateway is running but kanban.dispatch_in_gateway=false in "
- "config.yaml — the task will sit in 'ready' until you flip it "
- "back on and restart the gateway, OR run the legacy "
- "standalone daemon (`hermes kanban daemon --force`).",
- )
- return (
- False,
- "No gateway is running — the task will sit in 'ready' until you "
- "start it. Run:\n"
- " hermes gateway start\n"
- "The gateway hosts an embedded dispatcher (tick interval 60s by "
- "default); your task will be picked up on the next tick after "
- "the gateway comes up.",
- )
+ return (False, "Gateway is running but kanban.dispatch_in_gateway=false in "
+ "config.yaml — the task will sit in 'ready' until you flip it "
+ "back on and restart the gateway, OR run the legacy "
+ "standalone daemon (`hermes kanban daemon --force`).")
+ return (False, "No gateway is running — the task will sit in 'ready' until you "
+ "start it. Run:\n hermes gateway start\n"
+ "The gateway hosts an embedded dispatcher (tick interval 60s by "
+ "default); your task will be picked up on the next tick after "
+ "the gateway comes up.")
-# ---------------------------------------------------------------------------
-# Command dispatch
-# ---------------------------------------------------------------------------
+# --- Command dispatch ---
def kanban_command(args: argparse.Namespace) -> int:
"""Entry point from ``hermes kanban …``; returns a shell-style exit code."""
@@ -152,11 +133,8 @@ def kanban_command(args: argparse.Namespace) -> int:
if parser is not None:
parser.print_help()
else:
- print(
- "usage: hermes kanban <action> [options]\n"
- "Run 'hermes kanban --help' for the full list of actions.",
- file=sys.stderr,
- )
+ print("usage: hermes kanban <action> [options]\n"
+ "Run 'hermes kanban --help' for the full list of actions.", file=sys.stderr)
return 0
# Fast-fail for UX only; the durable trust boundary is in kanban_db, since children can
@@ -183,10 +161,8 @@ def kanban_command(args: argparse.Namespace) -> int:
# Boards other than 'default' must already exist — typoed slugs would otherwise silently
# create an empty board.
if normed != kb.DEFAULT_BOARD and not kb.board_exists(normed):
- return _err(
- f"kanban: board {normed!r} does not exist. "
- f"Create it with `hermes kanban boards create {normed}`."
- )
+ return _err(f"kanban: board {normed!r} does not exist. "
+ f"Create it with `hermes kanban boards create {normed}`.")
board_scope = kb.scoped_current_board(normed)
with board_scope:
@@ -210,9 +186,7 @@ def kanban_command(args: argparse.Namespace) -> int:
return _err(f"kanban: {exc}")
-# ---------------------------------------------------------------------------
-# Handlers
-# ---------------------------------------------------------------------------
+# --- Handlers ---
def _profile_author() -> str:
"""Best-effort author name for an interactive CLI call."""
@@ -335,10 +309,8 @@ def _cmd_init(args: argparse.Namespace) -> int:
def _cmd_heartbeat(args: argparse.Namespace) -> int:
with kb.connect_closing() as conn:
- ok = kb.heartbeat_worker(
- conn, args.task_id, note=getattr(args, "note", None),
- expected_run_id=_worker_run_id_for(args.task_id),
- )
+ ok = kb.heartbeat_worker(conn, args.task_id, note=getattr(args, "note", None),
+ expected_run_id=_worker_run_id_for(args.task_id))
return _ok_or_err(ok, f"cannot heartbeat {args.task_id} (not running?)",
f"Heartbeat recorded for {args.task_id}")
@@ -372,11 +344,8 @@ def _cmd_create(args: argparse.Namespace) -> int:
return _err(f"kanban: --max-runtime: {exc}", 2)
max_retries = getattr(args, "max_retries", None)
if max_retries is not None and max_retries < 1:
- return _err(
- f"kanban: --max-retries must be >= 1 (got {max_retries}); "
- "use 1 to trip on the first failure.",
- 2,
- )
+ return _err(f"kanban: --max-retries must be >= 1 (got {max_retries}); "
+ "use 1 to trip on the first failure.", 2)
with kb.connect_closing() as conn:
task_id = kb.create_task(
conn, title=args.title, body=args.body, assignee=args.assignee,
@@ -451,11 +420,8 @@ def _cmd_list(args: argparse.Namespace) -> int:
all_boards = []
if len(all_boards) > 1:
other_count = len(all_boards) - 1
- print(
- f"Board: {kb.get_current_board()} "
- f"({other_count} other board{'s' if other_count != 1 else ''} — "
- f"`hermes kanban boards list`)\n"
- )
+ print(f"Board: {kb.get_current_board()} ({other_count} other board{'s' if other_count != 1 else ''} — "
+ f"`hermes kanban boards list`)\n")
if not tasks:
print("(no matching tasks)")
return 0
@@ -471,10 +437,8 @@ def _print_diagnostics(diags, indent: str, *, with_kind: bool) -> None:
head = f"{d.kind}: {d.title}" if with_kind else d.title
print(f"{indent}{sev_marker.get(d.severity, '?')} [{d.severity}] {head}")
if d.data:
- bits = [
- f"{k}={','.join(str(x) for x in v)}" if isinstance(v, list) else f"{k}={v}"
- for k, v in d.data.items()
- ]
+ bits = [f"{k}={','.join(str(x) for x in v)}" if isinstance(v, list) else f"{k}={v}"
+ for k, v in d.data.items()]
if bits:
print(f"{indent} data: {' | '.join(bits)}")
for a in d.actions:
@@ -512,10 +476,7 @@ def _cmd_show(args: argparse.Namespace) -> int:
if want_json:
_print_json({
- "task": _task_to_dict(task),
- "latest_summary": latest_summary,
- "parents": parents,
- "children": children,
+ "task": _task_to_dict(task), "latest_summary": latest_summary, "parents": parents, "children": children,
"comments": [_obj_dict(c, ("author", "body", "created_at")) for c in comments],
"events": [_obj_dict(e, ("kind", "payload", "created_at", "run_id")) for e in events],
"runs": [_obj_dict(r, _SHOW_RUN_FIELDS) for r in runs],
@@ -575,9 +536,7 @@ def _cmd_show(args: argparse.Namespace) -> int:
if events:
_print_section(f"Events ({len(events)}):", (
f" [{_fmt_ts(e.created_at)}]{f' [run {e.run_id}]' if e.run_id else ''} {e.kind}"
- f"{f' {e.payload}' if e.payload else ''}"
- for e in events[-20:]
- ))
+ f"{f' {e.payload}' if e.payload else ''}" for e in events[-20:]))
if runs:
print()
print(f"Runs ({len(runs)}):")
@@ -633,9 +592,7 @@ def _cmd_reassign(args: argparse.Namespace) -> int:
profile = _none_profile(args.profile)
reclaim = bool(getattr(args, "reclaim", False))
with kb.connect_closing() as conn:
- ok = kb.reassign_task(
- conn, args.task_id, profile, reclaim_first=reclaim, reason=getattr(args, "reason", None),
- )
+ ok = kb.reassign_task(conn, args.task_id, profile, reclaim_first=reclaim, reason=getattr(args, "reason", None))
return _ok_or_err(
ok,
f"cannot reassign {args.task_id} (unknown id, or still running — pass --reclaim to release first)",
@@ -647,9 +604,7 @@ def _rows_by_task(conn, table: str, ids: list[str]) -> dict[str, list]:
"""``{task_id: [rows ordered by id]}`` for every id (empty list when none)."""
by = {i: [] for i in ids}
placeholders = ",".join(["?"] * len(ids))
- for row in conn.execute(
- f"SELECT * FROM {table} WHERE task_id IN ({placeholders}) ORDER BY id", tuple(ids),
- ):
+ for row in conn.execute(f"SELECT * FROM {table} WHERE task_id IN ({placeholders}) ORDER BY id", tuple(ids)):
by.setdefault(row["task_id"], []).append(row)
return by
@@ -667,12 +622,9 @@ def _cmd_diagnostics(args: argparse.Namespace) -> int:
task = kb.get_task(conn, args.task)
if task is None:
return _err(f"no such task: {args.task}")
- diags_by_task = {
- args.task: kd.compute_task_diagnostics(
- task, kb.list_events(conn, args.task), kb.list_runs(conn, args.task),
- graph=kb.task_graph_context(conn, args.task), config=diag_config,
- )
- }
+ diags_by_task = {args.task: kd.compute_task_diagnostics(
+ task, kb.list_events(conn, args.task), kb.list_runs(conn, args.task),
+ graph=kb.task_graph_context(conn, args.task), config=diag_config)}
else:
# Fleet mode: pull all non-archived tasks + their events/runs.
rows = list(conn.execute("SELECT * FROM tasks WHERE status != 'archived'").fetchall())
@@ -684,37 +636,28 @@ def _cmd_diagnostics(args: argparse.Namespace) -> int:
graph_by = kb.task_graph_contexts(conn, ids)
for r in rows:
tid = r["id"]
- dl = kd.compute_task_diagnostics(
- r, ev_by.get(tid, []), run_by.get(tid, []),
- graph=graph_by.get(tid), config=diag_config,
- )
+ dl = kd.compute_task_diagnostics(r, ev_by.get(tid, []), run_by.get(tid, []),
+ graph=graph_by.get(tid), config=diag_config)
if dl:
diags_by_task[tid] = dl
sev = getattr(args, "severity", None)
if sev:
floor = kd.SEVERITY_ORDER.index(sev)
- diags_by_task = {
- tid: kept
- for tid, dl in diags_by_task.items()
- if (kept := [d for d in dl if kd.SEVERITY_ORDER.index(d.severity) >= floor])
- }
+ diags_by_task = {tid: kept for tid, dl in diags_by_task.items()
+ if (kept := [d for d in dl if kd.SEVERITY_ORDER.index(d.severity) >= floor])}
# Map task_id → title/status/assignee for the table output.
meta: dict[str, dict] = {}
if diags_by_task:
placeholders = ",".join(["?"] * len(diags_by_task))
- for r in conn.execute(
- f"SELECT id, title, status, assignee FROM tasks WHERE id IN ({placeholders})",
- tuple(diags_by_task.keys()),
- ):
+ for r in conn.execute(f"SELECT id, title, status, assignee FROM tasks WHERE id IN ({placeholders})",
+ tuple(diags_by_task.keys())):
meta[r["id"]] = {k: r[k] for k in ("title", "status", "assignee")}
if getattr(args, "json", False):
- _print_json([
- {"task_id": tid, **meta.get(tid, {}), "diagnostics": [d.to_dict() for d in dl]}
- for tid, dl in diags_by_task.items()
- ])
+ _print_json([{"task_id": tid, **meta.get(tid, {}), "diagnostics": [d.to_dict() for d in dl]}
+ for tid, dl in diags_by_task.items()])
return 0
if not diags_by_task:
@@ -725,10 +668,8 @@ def _cmd_diagnostics(args: argparse.Namespace) -> int:
print(f"{total} active diagnostic(s) across {len(diags_by_task)} task(s):\n")
for tid, dl in diags_by_task.items():
m = meta.get(tid, {})
- title = m.get("title") or "(untitled)"
- status = m.get("status") or "?"
- assignee = m.get("assignee") or "(unassigned)"
- print(f" {tid} {status:8s} @{assignee:18s} {title}")
+ print(f" {tid} {m.get('status') or '?':8s} @{m.get('assignee') or '(unassigned)':18s} "
+ f"{m.get('title') or '(untitled)'}")
_print_diagnostics(dl, " ", with_kind=True)
print()
return 0
@@ -755,10 +696,8 @@ def _cmd_claim(args: argparse.Namespace) -> int:
existing = kb.get_task(conn, args.task_id)
if existing is None:
return _err(f"no such task: {args.task_id}")
- return _err(
- f"cannot claim {args.task_id}: status={existing.status} "
- f"lock={existing.claim_lock or '(none)'}"
- )
+ return _err(f"cannot claim {args.task_id}: status={existing.status} "
+ f"lock={existing.claim_lock or '(none)'}")
workspace = kb.resolve_workspace(task)
kb.set_workspace_path(conn, task.id, str(workspace))
print(f"Claimed {task.id}\nWorkspace: {workspace}")
@@ -794,9 +733,8 @@ def _cmd_attach(args: argparse.Namespace) -> int:
uploaded_by = args.author or _profile_author()
try:
with kb.connect_closing() as conn:
- att_id = kb.store_attachment_bytes(
- conn, args.task_id, name, data, content_type=content_type, uploaded_by=uploaded_by,
- )
+ att_id = kb.store_attachment_bytes(conn, args.task_id, name, data, content_type=content_type,
+ uploaded_by=uploaded_by)
except kb.AttachmentTooLarge as exc:
return _err(f"kanban: {exc}")
print(f"Attached {name} to {args.task_id} (attachment {att_id}, {len(data)} bytes)")
@@ -862,15 +800,13 @@ def _goal_mode_handoff_rejection(task: Optional[kb.Task], evidence: str):
verdict, reason = "done", ""
try:
- verdict, reason, _, _, _ = judge_goal(
- goal=f"{task.title}\n\n{task.body or ''}".strip(), last_response=evidence.strip(),
- )
+ verdict, reason, _, _, _ = judge_goal(goal=f"{task.title}\n\n{task.body or ''}".strip(),
+ last_response=evidence.strip())
except Exception as judge_exc:
import logging as _logging
- _logging.getLogger(__name__).warning(
- "goal judge check failed, allowing lifecycle handoff: %s", judge_exc, exc_info=True,
- )
+ _logging.getLogger(__name__).warning("goal judge check failed, allowing lifecycle handoff: %s",
+ judge_exc, exc_info=True)
return (verdict, None if verdict == "done" else reason)
@@ -897,12 +833,9 @@ def _cmd_complete(args: argparse.Namespace) -> int:
raw_meta = getattr(args, "metadata", None)
# Handoff fields are per-run; refuse to copy them across N runs.
if len(ids) > 1 and (summary or raw_meta):
- return _err(
- "kanban: --summary / --metadata are per-task and can't be used "
- "with multiple ids (would apply the same handoff to every task). "
- "Complete tasks one at a time, or drop the flags for the bulk close.",
- 2,
- )
+ return _err("kanban: --summary / --metadata are per-task and can't be used "
+ "with multiple ids (would apply the same handoff to every task). "
+ "Complete tasks one at a time, or drop the flags for the bulk close.", 2)
metadata, rc = _parse_metadata_flag(raw_meta)
if rc:
return rc
@@ -911,18 +844,14 @@ def _cmd_complete(args: argparse.Namespace) -> int:
def op(tid):
gate_err = _goal_gate_error(
conn, tid, (summary or args.result or "").strip(), "completion",
- "Re-scope with kanban edit, or record the block with kanban block "
- "instead of completing.",
- "Provide evidence matching the task's acceptance criteria.",
- )
+ "Re-scope with kanban edit, or record the block with kanban block instead of completing.",
+ "Provide evidence matching the task's acceptance criteria.")
if gate_err:
fail_msg[tid] = gate_err
return False
fail_msg[tid] = f"cannot complete {tid} (unknown id or terminal state)"
- return kb.complete_task(
- conn, tid, result=args.result, summary=summary, metadata=metadata,
- expected_run_id=_worker_run_id_for(tid),
- )
+ return kb.complete_task(conn, tid, result=args.result, summary=summary, metadata=metadata,
+ expected_run_id=_worker_run_id_for(tid))
return _bulk_apply(ids, op, lambda tid: f"Completed {tid}", fail_msg.__getitem__)
@@ -932,13 +861,9 @@ def _cmd_edit(args: argparse.Namespace) -> int:
if rc:
return rc
with kb.connect_closing() as conn:
- if not kb.edit_completed_task_result(
- conn, args.task_id, result=args.result, summary=getattr(args, "summary", None),
- metadata=metadata,
- ):
- return _err(f"cannot edit {args.task_id} (unknown id or task is not done)")
- print(f"Edited {args.task_id}")
- return 0
+ ok = kb.edit_completed_task_result(conn, args.task_id, result=args.result,
+ summary=getattr(args, "summary", None), metadata=metadata)
+ return _ok_or_err(ok, f"cannot edit {args.task_id} (unknown id or task is not done)", f"Edited {args.task_id}")
def _commented(conn, reason: Optional[str], author, prefix: str, op):
@@ -968,8 +893,7 @@ def _cmd_block(args: argparse.Namespace) -> int:
return f"Blocked {tid}{suffix}"
op = _commented(conn, reason, author, "BLOCKED", lambda tid: kb.block_task(
- conn, tid, reason=reason, kind=kind, expected_run_id=_worker_run_id_for(tid),
- ))
+ conn, tid, reason=reason, kind=kind, expected_run_id=_worker_run_id_for(tid)))
return _bulk_apply(ids, op, ok_msg, lambda tid: f"cannot block {tid}")
@@ -980,11 +904,8 @@ def _cmd_schedule(args: argparse.Namespace) -> int:
suffix = f": {reason}" if reason else ""
with kb.connect_closing() as conn:
op = _commented(conn, reason, author, "SCHEDULED", lambda tid: kb.schedule_task(
- conn, tid, reason=reason, expected_run_id=_worker_run_id_for(tid),
- ))
- return _bulk_apply(
- ids, op, lambda tid: f"Scheduled {tid}{suffix}", lambda tid: f"cannot schedule {tid}",
- )
+ conn, tid, reason=reason, expected_run_id=_worker_run_id_for(tid)))
+ return _bulk_apply(ids, op, lambda tid: f"Scheduled {tid}{suffix}", lambda tid: f"cannot schedule {tid}")
def _cmd_unblock(args: argparse.Namespace) -> int:
@@ -996,10 +917,8 @@ def _cmd_unblock(args: argparse.Namespace) -> int:
suffix = f": {reason}" if reason else ""
with kb.connect_closing() as conn:
op = _commented(conn, reason, author, "UNBLOCK", lambda tid: kb.unblock_task(conn, tid))
- return _bulk_apply(
- ids, op, lambda tid: f"Unblocked {tid}{suffix}",
- lambda tid: f"cannot unblock {tid} (not blocked/scheduled?)",
- )
+ return _bulk_apply(ids, op, lambda tid: f"Unblocked {tid}{suffix}",
+ lambda tid: f"cannot unblock {tid} (not blocked/scheduled?)")
def _cmd_request_review(args: argparse.Namespace) -> int:
@@ -1012,15 +931,12 @@ def _cmd_request_review(args: argparse.Namespace) -> int:
gate_err = _goal_gate_error(
conn, tid, summary or "", "review handoff",
"Record the block with kanban block instead of requesting review.",
- "Provide acceptance evidence matching the task.",
- )
+ "Provide acceptance evidence matching the task.")
if gate_err:
return _err(gate_err)
ok, reason = kb.request_review(
conn, tid, summary=summary, metadata=metadata, reviewer=getattr(args, "reviewer", None),
- expected_run_id=_worker_run_id_for(tid), force=bool(getattr(args, "force", False)),
- with_reason=True,
- )
+ expected_run_id=_worker_run_id_for(tid), force=bool(getattr(args, "force", False)), with_reason=True)
if not ok:
return _err(f"cannot request review for {tid}: {reason or 'not running/ready?'}")
persisted_run = kb.latest_run(conn, tid)
@@ -1057,9 +973,8 @@ def _cmd_reopen_review(args: argparse.Namespace) -> int:
kb.add_comment(conn, tid, author or "operator", f"CHANGES REQUESTED: {reason}")
return True
- return _bulk_apply(
- ids, op, lambda tid: f"Reopened {tid}{suffix}", lambda tid: f"cannot reopen {tid} (not in review?)",
- )
+ return _bulk_apply(ids, op, lambda tid: f"Reopened {tid}{suffix}",
+ lambda tid: f"cannot reopen {tid} (not in review?)")
def _cmd_promote(args: argparse.Namespace) -> int:
@@ -1073,10 +988,8 @@ def _cmd_promote(args: argparse.Namespace) -> int:
with kb.connect_closing() as conn:
for tid in ids:
ok, err = kb.promote_task(conn, tid, actor=author, reason=reason, force=force, dry_run=dry_run)
- results.append({
- "task_id": tid, "promoted": ok, "dry_run": dry_run, "forced": force,
- "reason": reason, "error": err,
- })
+ results.append({"task_id": tid, "promoted": ok, "dry_run": dry_run, "forced": force,
+ "reason": reason, "error": err})
failed = [r for r in results if not r["promoted"]]
if getattr(args, "json", False):
@@ -1104,14 +1017,10 @@ def _cmd_archive(args: argparse.Namespace) -> int:
return _err("at least one task_id is required")
with kb.connect_closing() as conn:
if purge_ids:
- return _bulk_apply(
- purge_ids, lambda tid: kb.delete_archived_task(conn, tid),
- lambda tid: f"Deleted {tid}", lambda tid: f"cannot delete {tid} (must already be archived)",
- )
- return _bulk_apply(
- ids, lambda tid: kb.archive_task(conn, tid),
- lambda tid: f"Archived {tid}", lambda tid: f"cannot archive {tid}",
- )
+ return _bulk_apply(purge_ids, lambda tid: kb.delete_archived_task(conn, tid), lambda tid: f"Deleted {tid}",
+ lambda tid: f"cannot delete {tid} (must already be archived)")
+ return _bulk_apply(ids, lambda tid: kb.archive_task(conn, tid),
+ lambda tid: f"Archived {tid}", lambda tid: f"cannot archive {tid}")
def _cmd_stats(args: argparse.Namespace) -> int:
@@ -1143,8 +1052,7 @@ def _cmd_notify_subscribe(args: argparse.Namespace) -> int:
notifier_profile=args.notifier_profile or _profile_author(),
delivery_mode=getattr(args, "delivery_mode", None),
)
- print(f"Subscribed {args.platform}:{args.chat_id}"
- + (f":{args.thread_id}" if args.thread_id else "")
+ print(f"Subscribed {args.platform}:{args.chat_id}" + (f":{args.thread_id}" if args.thread_id else "")
+ f" to {args.task_id}")
return 0
@@ -1172,10 +1080,8 @@ def _cmd_notify_list(args: argparse.Namespace) -> int:
def _cmd_notify_unsubscribe(args: argparse.Namespace) -> int:
with kb.connect_closing() as conn:
- ok = kb.remove_notify_sub(
- conn, task_id=args.task_id, platform=args.platform, chat_id=args.chat_id,
- thread_id=args.thread_id,
- )
+ ok = kb.remove_notify_sub(conn, task_id=args.task_id, platform=args.platform, chat_id=args.chat_id,
+ thread_id=args.thread_id)
return _ok_or_err(ok, "(no such subscription)", f"Unsubscribed from {args.task_id}")
@@ -1206,8 +1112,7 @@ def _cmd_runs(args: argparse.Namespace) -> int:
end = r.ended_at or int(time.time())
# Clamp to 0 so NTP backward-jumps don't print negative durations.
elapsed = max(0, end - r.started_at)
- el = (f"{elapsed}s" if elapsed < 60 else f"{elapsed // 60}m" if elapsed < 3600
- else f"{elapsed / 3600:.1f}h")
+ el = f"{elapsed}s" if elapsed < 60 else f"{elapsed // 60}m" if elapsed < 3600 else f"{elapsed / 3600:.1f}h"
outcome = r.outcome or ("(running)" if not r.ended_at else r.status)
print(f"{i:3d} {outcome:12s} {(r.profile or '-'):16s} {el:>8s} {_fmt_ts(r.started_at)}")
if r.summary:
@@ -1272,10 +1177,9 @@ def _cmd_specify(args: argparse.Namespace) -> int:
"""Spec a triage task (or all) via the auxiliary LLM, promote to todo."""
from hermes_cli import kanban_specify as spec
- return _run_triage_sweep(
- args, "specify", spec, spec.specify_task, "specified", ("task_id", "ok", "reason", "new_title"),
- lambda o: f"Specified {o.task_id} → todo{_retitled_suffix(o)}",
- )
+ return _run_triage_sweep(args, "specify", spec, spec.specify_task, "specified",
+ ("task_id", "ok", "reason", "new_title"),
+ lambda o: f"Specified {o.task_id} → todo{_retitled_suffix(o)}")
def _decompose_ok_line(o) -> str:
@@ -1289,10 +1193,8 @@ def _cmd_decompose(args: argparse.Namespace) -> int:
"""Fan a triage task (or all) out into child tasks via the auxiliary LLM."""
from hermes_cli import kanban_decompose as decomp
- return _run_triage_sweep(
- args, "decompose", decomp, decomp.decompose_task, "decomposed",
- ("task_id", "ok", "reason", "fanout", "child_ids", "new_title"), _decompose_ok_line,
- )
+ return _run_triage_sweep(args, "decompose", decomp, decomp.decompose_task, "decomposed",
+ ("task_id", "ok", "reason", "fanout", "child_ids", "new_title"), _decompose_ok_line)
_HANDLERS = {
@@ -1318,9 +1220,7 @@ _HANDLERS = {
}
-# ---------------------------------------------------------------------------
-# Slash-command entry point (used by /kanban from CLI and gateway)
-# ---------------------------------------------------------------------------
+# --- Slash-command entry point (used by /kanban from CLI and gateway) ---
_SLASH_KANBAN_HELP = """\
**/kanban** — manage the shared task board.
@@ -1353,12 +1253,10 @@ def run_slash(rest: str) -> str:
import io
tokens = shlex.split(rest) if rest and rest.strip() else []
-
# Bare ``/kanban`` / ``help`` / ``-h``: curated short block, not argparse's full tree (garbage
# in a chat bubble). ``/kanban foo -h`` still works.
if not tokens or tokens[0] in {"help", "--help", "-h", "?"}:
return _SLASH_KANBAN_HELP
-
# build_parser() needs a subparsers action to attach to: build a throwaway one and drive
# kanban_parser directly so usage/error text reads ``/kanban``.
_wrap = argparse.ArgumentParser(prog="/kanban-wrap", add_help=False)
@@ -1380,14 +1278,12 @@ def run_slash(rest: str) -> str:
return subparser.format_usage().rstrip()
return kanban_parser.format_usage().rstrip()
- buf_out = io.StringIO()
- buf_err = io.StringIO()
+ buf_out, buf_err = io.StringIO(), io.StringIO()
try:
with contextlib.redirect_stdout(buf_out), contextlib.redirect_stderr(buf_err):
args = kanban_parser.parse_args(tokens)
except SystemExit as exc:
- out = buf_out.getvalue().rstrip()
- err = buf_err.getvalue().rstrip()
+ out, err = buf_out.getvalue().rstrip(), buf_err.getvalue().rstrip()
if exc.code in {0, None} and out: # ``-h`` help dump
return out
body = err or out
@@ -1403,8 +1299,7 @@ def run_slash(rest: str) -> str:
except Exception as exc:
print(f"error: {exc}", file=sys.stderr)
- out = buf_out.getvalue().rstrip()
- err = buf_err.getvalue().rstrip()
+ out, err = buf_out.getvalue().rstrip(), buf_err.getvalue().rstrip()
if err and out:
return f"{out}\n{err}"
return err if err else (out or "(no output)")