Skip to content

The agent that grows with you

refactor(cron): rewrap long comment/docstring lines to 100 cols

Tekniumb385c0198f81
diff --git a/cron/blueprint_catalog.py b/cron/blueprint_catalog.py
index bd9a8a448c8..4a938e4a3a8 100644
--- a/cron/blueprint_catalog.py
+++ b/cron/blueprint_catalog.py
@@ -1,8 +1,8 @@
"""Automation Blueprints — one slot-schema definition per automation that every surface renders
natively: dashboard form (``blueprint_form_schema``), pre-filled ``/blueprint`` slash command
-(``blueprint_slash_command``), agent seed prompt, docs deep-link. ``fill_blueprint`` validates values
-into ``cron.jobs.create_job`` kwargs — there is no second job engine. Users never type raw cron:
-``schedule_template`` fixes the recurrence and only human-friendly parts (time, weekdays) are slots.
+(``blueprint_slash_command``), agent seed prompt, docs deep-link. ``fill_blueprint`` validates
+values into ``cron.jobs.create_job`` kwargs — there is no second job engine. Users never type raw
+cron: ``schedule_template`` fixes the recurrence; only human parts (time, weekdays) are slots.
"""
from __future__ import annotations
@@ -553,7 +553,9 @@ def get_blueprint(key: str) -> Optional[AutomationBlueprint]:
return _CATALOG_BY_KEY.get(key)
-def _slot(blueprint: AutomationBlueprint, *names: str, type: Optional[str] = None) -> Optional[BlueprintSlot]:
+def _slot(
+ blueprint: AutomationBlueprint, *names: str, type: Optional[str] = None
+) -> Optional[BlueprintSlot]:
"""First slot matching any of *names* (or *type*), else None."""
return next((s for s in blueprint.slots if s.name in names or (type and s.type == type)), None)
@@ -644,8 +646,8 @@ def _humanize_schedule(blueprint: AutomationBlueprint) -> str:
def blueprint_catalog_entry(blueprint: AutomationBlueprint) -> Dict[str, Any]:
- """Unified serializable shape (docs generator + dashboard API): form schema + ready-to-paste slash
- command + deep-link URL + human-readable schedule."""
+ """Unified serializable shape (docs generator + dashboard API): form schema + ready-to-paste
+ slash command + deep-link URL + human-readable schedule."""
return {
**blueprint_form_schema(blueprint),
"schedule": blueprint.schedule_template,
diff --git a/cron/executions.py b/cron/executions.py
index e0798bbb97c..8c9fa24f0fc 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -1,8 +1,8 @@
"""Profile-local durable audit ledger for cron execution attempts.
The ledger records what is known about each attempt; it is not a retry queue. Interrupted attempts
-become ``unknown`` only after their exact owner process is proved gone. Terminal states are immutable.
-Also hosts the SQLite connection/transaction helpers shared with ``cron.incidents`` / ``cron.notepad``.
+become ``unknown`` only after their exact owner process is proved gone. Terminal states are
+immutable. Also hosts the SQLite ledger helpers shared with ``cron.incidents`` / ``cron.notepad``.
"""
from __future__ import annotations
@@ -19,7 +19,8 @@ from hermes_constants import get_hermes_home
from hermes_time import now as _hermes_now
# Optional test override. Production resolves the path at transaction time so dashboard operations
-# that temporarily enter another profile cannot leak that profile's records into the import-time home.
+# that temporarily enter another profile cannot leak that profile's records into the import-time
+# home.
EXECUTIONS_FILE: Optional[Path] = None
MAX_TERMINAL_EXECUTIONS = 1000
_TERMINAL_STATES = ("completed", "failed", "unknown")
@@ -37,7 +38,9 @@ def open_ledger(path: Path) -> sqlite3.Connection:
return sqlite3.connect(path, timeout=5)
-def prepare_ledger(conn: sqlite3.Connection, *, db_label: str, synchronous_full: bool = True) -> None:
+def prepare_ledger(
+ conn: sqlite3.Connection, *, db_label: str, synchronous_full: bool = True
+) -> None:
"""Row factory + busy timeout + WAL (with fallback) + optional ``synchronous=FULL``."""
from hermes_state import apply_wal_with_fallback
@@ -50,12 +53,13 @@ def prepare_ledger(conn: sqlite3.Connection, *, db_label: str, synchronous_full:
@contextmanager
def ledger_transaction(
- lock: threading.RLock, connect: Callable[[], sqlite3.Connection],
+ lock: threading.RLock,
+ connect: Callable[[], sqlite3.Connection],
initialize_schema: Callable[[sqlite3.Connection], None],
) -> Iterator[sqlite3.Connection]:
- """Open a connection, commit/rollback on exit, always close. ``sqlite3.Connection``'s own context
- manager does NOT close (leaks WAL/SHM fds until GC); schema init runs inside the ``try`` so a
- PRAGMA/DDL failure after ``connect()`` still closes."""
+ """Open a connection, commit/rollback on exit, always close. ``sqlite3.Connection``'s own
+ context manager does NOT close (leaks WAL/SHM fds until GC); schema init runs inside the
+ ``try`` so a PRAGMA/DDL failure after ``connect()`` still closes."""
with lock:
conn = connect()
try:
diff --git a/cron/incidents.py b/cron/incidents.py
index e8ea8be4c0a..51999fa3983 100644
--- a/cron/incidents.py
+++ b/cron/incidents.py
@@ -3,9 +3,9 @@
The executions ledger records every attempt; this module groups the *failures* into incidents keyed
by ``(job_id, error signature)`` so the same job failing with the same error does not re-ping the
operator every run once acknowledged. Lifecycle: ``detected`` → ``alerted`` → ``closed``. The same
-job + same normalized error resolves to the SAME incident id, so a closed incident stays closed until
-the error text changes and mints a new one. ``alerted`` means a failure ping actually reached the
-operator. Incidents share ``cron/executions.db`` with ``cron.executions`` (one ledger file).
+job + same normalized error resolves to the SAME incident id, so a closed incident stays closed
+until the error text changes and mints a new one. ``alerted`` means a failure ping actually reached
+the operator. Incidents share ``cron/executions.db`` with ``cron.executions`` (one ledger file).
"""
from __future__ import annotations
@@ -140,9 +140,10 @@ def upsert_incident(
job_id: str, error: str, *, job_name: Optional[str] = None, failure_type: Optional[str] = None,
output_file: Optional[str] = None,
) -> tuple[str, bool]:
- """Record (or refresh) the incident for ``job_id`` + ``error``; returns ``(incident_id, is_new)``.
- An existing row for the signature refreshes ``last_seen_at``/``error``/``output_file`` and keeps
- its state — a ``closed`` incident stays closed. A changed error text mints a new incident."""
+ """Record (or refresh) the incident for ``job_id`` + ``error``; returns ``(incident_id,
+ is_new)``. An existing row for the signature refreshes
+ ``last_seen_at``/``error``/``output_file`` and keeps its state — a ``closed`` incident stays
+ closed. A changed error text mints a new incident."""
job_id = str(job_id or "")
sig = _error_signature(job_id, error)
stored_error = _redact_error(error)
@@ -175,9 +176,9 @@ def upsert_incident(
def set_incident_state(incident_id: str, state: str) -> bool:
- """Transition an incident's lifecycle state; return whether it changed. ``closed`` is terminal for
- that signature (re-open happens by a changed error minting a NEW incident). Unknown states are
- rejected (no-op, ``False``)."""
+ """Transition an incident's lifecycle state; return whether it changed. ``closed`` is terminal
+ for that signature (re-open happens by a changed error minting a NEW incident). Unknown states
+ are rejected (no-op, ``False``)."""
if state not in INCIDENT_STATES:
return False
now = _hermes_now().isoformat()
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.py
index 3b9add8b484..a27e24e15a6 100644
--- a/cron/lifecycle_guard.py
+++ b/cron/lifecycle_guard.py
@@ -2,9 +2,9 @@
A cron job that restarts/stops the gateway from inside the gateway (``hermes gateway restart``,
``launchctl kickstart ai.hermes.gateway``, ``systemctl restart hermes-gateway``) kills the process,
-the supervisor revives it, auto-resume re-runs the turn: a SIGTERM-respawn loop. ``cron.jobs.create_job``
-rejects such specs on every creation path. Patterns are command-shaped — anchored on concrete command
-identifiers — so they cannot fire on prose. Defence-in-depth layer.
+the supervisor revives it, auto-resume re-runs the turn: a SIGTERM-respawn loop.
+``cron.jobs.create_job`` rejects such specs on every creation path. Patterns are command-shaped —
+anchored on concrete command identifiers — so they cannot fire on prose. Defence-in-depth layer.
"""
from __future__ import annotations
@@ -28,15 +28,17 @@ class GatewayLifecycleBlocked(ValueError):
# concrete command identifier so it fires only on command-shaped strings, never prose.
_GATEWAY_LIFECYCLE_PATTERN = re.compile(
r"(?i)"
- # Branch A: destructive `hermes gateway` ops. `start` is excluded: starting from inside a gateway
- # is benign and a job may legitimately start a sibling profile. The lookbehind keeps `hermes` from
- # being a path component or word tail (`/docs/hermes gateway restart-notes.md`) while every real
- # command position (text start, whitespace, `;`/`&`/`|`, `$(`, backtick, U+FFFD) still matches.
+ # Branch A: destructive `hermes gateway` ops. `start` is excluded: starting from inside a
+ # gateway is benign and a job may legitimately start a sibling profile. The lookbehind keeps
+ # `hermes` from being a path component or word tail (`/docs/hermes gateway restart-notes.md`)
+ # while every real command position (text start, whitespace, `;`/`&`/`|`, `$(`, backtick,
+ # U+FFFD) still matches.
r"(?:(?<![/\w.\-])hermes\s+gateway\s+(?:restart|stop|uninstall)\b)"
# Branch B: launchctl ops anchored on a hermes-gateway label so unrelated hermes services stay
# unblocked. `submit`/`bootstrap` register a NEW keepalive job wrapping an arbitrary helper (a
- # laundered restart); neutral-label submissions are caught by `contains_launchctl_submit_command`.
- # `bootout`/`remove`/`disable` are the modern/legacy/durable forms of `unload`.
+ # laundered restart); neutral-label submissions are caught by
+ # `contains_launchctl_submit_command`. `bootout`/`remove`/`disable` are the
+ # modern/legacy/durable forms of `unload`.
r"|(?:launchctl\s+(?:kickstart|unload|load|stop|restart|submit|bootstrap|bootout|remove|disable)\b[^\n]*\bhermes[.\-]?gateway)"
# Branch C: systemctl ops on a hermes-gateway unit.
r"|(?:systemctl\s+(?:-\S+\s+)*(?:restart|stop|start)\b[^\n]*\bhermes[.\-]?gateway)"
@@ -47,18 +49,18 @@ _GATEWAY_LIFECYCLE_PATTERN = re.compile(
)
# Every branch uses `[^\n]*` between verb and label so matches cannot span unrelated lines. A POSIX
-# backslash-newline continuation is therefore collapsed to a space before matching (as the shell does)
-# rather than loosening `[^\n]*`.
+# backslash-newline continuation is therefore collapsed to a space before matching (as the shell
+# does) rather than loosening `[^\n]*`.
_SHELL_LINE_CONTINUATION = re.compile(r"\\\r?\n[ \t]*")
-# Python argv-list punctuation (`subprocess.run(["launchctl", "bootout", ...])`) separates exec'd words
-# with brackets/commas. Stripped only for the token-join re-scan, never from raw text.
+# Python argv-list punctuation (`subprocess.run(["launchctl", "bootout", ...])`) separates exec'd
+# words with brackets/commas. Stripped only for the token-join re-scan, never from raw text.
_ARGV_LIST_PUNCTUATION = re.compile(r"[\[\],]+")
-# Branch A2: `hermes -p <profile> gateway restart|stop` (also `--profile <name>` / `--profile=<name>`).
-# The selector breaks Branch A's adjacency. A sibling-profile restart is a legitimate fleet operation,
-# so the profile name is captured and blocked only when it equals the profile running the guard.
-# `start` stays excluded as in Branch A.
+# Branch A2: `hermes -p <profile> gateway restart|stop` (also `--profile <name>` /
+# `--profile=<name>`). The selector breaks Branch A's adjacency. A sibling-profile restart is a
+# legitimate fleet operation, so the profile name is captured and blocked only when it equals the
+# profile running the guard. `start` stays excluded as in Branch A.
_PROFILE_FLAG_LIFECYCLE_PATTERN = re.compile(
r"(?i)"
r"hermes\s+"
@@ -72,9 +74,9 @@ _PROFILE_FLAG_LIFECYCLE_PATTERN = re.compile(
)
# Branch B needs the label AFTER the verb in one `[^\n]*` span; a loop that builds the label in an
-# EARLIER `;`-segment (`label=${item%%:*}; launchctl bootout "gui/$uid/$label"`) leaves only `$label`
-# next to the verb. These verbs act on an EXISTING job, so the hermes-gateway label anchor stays
-# correct, but the check is "verb anywhere AND label anywhere".
+# EARLIER `;`-segment (`label=${item%%:*}; launchctl bootout "gui/$uid/$label"`) leaves only
+# `$label` next to the verb. These verbs act on an EXISTING job, so the hermes-gateway label anchor
+# stays correct, but the check is "verb anywhere AND label anywhere".
_LAUNCHCTL_LIFECYCLE_VERBS_RE = re.compile(
r"(?i)\blaunchctl\s+(?:kickstart|unload|load|stop|restart|bootout|kill|disable|remove)\b"
)
@@ -87,13 +89,14 @@ _MAX_REFERENCED_SCRIPT_BYTES = 1024 * 1024
_MAX_REFERENCED_SCRIPT_DEPTH = 8
_CONTROL_CHARS = frozenset(";&|()")
-# Directory names directly under `Library` that mark a FileProvider-backed subtree: `Mobile Documents`
-# is iCloud Drive; `CloudStorage` hosts third-party providers (Dropbox, OneDrive, Google Drive, ...).
+# Directory names directly under `Library` that mark a FileProvider-backed subtree: `Mobile
+# Documents` is iCloud Drive; `CloudStorage` hosts third-party providers (Dropbox, OneDrive, Google
+# Drive, ...).
_CLOUD_PLACEHOLDER_MARKERS = frozenset({"Mobile Documents", "CloudStorage"})
# Executables whose arguments are DATA (search patterns, SQL, log filters) and cannot execute their
-# argument text. Deliberately conservative: no `awk` (system()), no `sed` (`s///e`), no `echo`/`printf`
-# (routinely piped into a shell), no `mysql` (`\\!` and `system` escapes).
+# argument text. Deliberately conservative: no `awk` (system()), no `sed` (`s///e`), no
+# `echo`/`printf` (routinely piped into a shell), no `mysql` (`\\!` and `system` escapes).
_DATA_SINK_EXECUTABLES = frozenset(
{"grep", "egrep", "fgrep", "rg", "ag", "ack", "journalctl", "sqlite3", "psql"}
)
@@ -103,7 +106,7 @@ _UNSAFE_DATA_ARG_MARKERS = ("`", "$(", "<(", ">(", "\\!")
# sqlite3 dot-commands (`.shell`, `.system`) also disable masking. Dot must be followed by a NAME
# character so relative paths (`.`, `./x`) stay paths.
_DOT_COMMAND_ARGUMENT = re.compile(r"^\.[A-Za-z]")
-# A data sink piped into a shell/interpreter can feed matched lines to execution; never mask such a line.
+# A data sink piped into a shell/interpreter can feed matched lines to execution; never mask it.
_PIPE_TO_INTERPRETER = re.compile(
r"\|\s*&?\s*(?:sudo\s+)?(?:sh|bash|dash|ksh|zsh|xargs|eval|source)\b"
)
@@ -114,7 +117,7 @@ _BINARY_SNIFF_BYTES = 4096
_ReadRemoteScriptFn = Callable[[str], Optional[str]]
# Wrappers that hand execution to their argument tail: the real command sits further right, so a
-# first-token-only guard would let `sudo bash ~/restart.sh` or `sudo launchctl submit ...` walk past.
+# first-token-only guard would let `sudo bash ~/restart.sh` / `sudo launchctl submit ...` walk past.
_TRANSPARENT_COMMAND_PREFIXES = frozenset({
"sudo", "doas", "env", "nohup", "setsid", "nice", "ionice", "stdbuf",
"timeout", "exec", "command", "builtin", "eatmydata",
@@ -136,8 +139,8 @@ _TRANSPARENT_PREFIX_VALUE_OPTIONS = {
"runuser": {"-u", "--user", "-s", "--shell", "-g", "--group", "-G", "--supp-group"},
"setpriv": {"--reuid", "--regid", "--groups", "--inh-caps", "--ambient-caps", "--bounding-set",
"--selinux-label", "--apparmor-profile"},
- "systemd-run": {"-u", "--unit", "-p", "--property", "-E", "--setenv", "--slice", "--description",
- "--uid", "--gid", "--on-calendar", "--service-type"},
+ "systemd-run": {"-u", "--unit", "-p", "--property", "-E", "--setenv", "--slice",
+ "--description", "--uid", "--gid", "--on-calendar", "--service-type"},
"nsenter": {"-t", "--target", "-S", "--setuid", "-G", "--setgid", "-r", "--root", "-w", "--wd"},
"unshare": {"--map-user", "--map-group", "--setgroups", "-R", "--root", "-w", "--wd"},
}
@@ -190,8 +193,8 @@ def _current_profile_name() -> Optional[str]:
def _named_profile_is_current(named: str) -> bool:
- """True when *named* is the profile executing the guard. Without a profile identity self-targeting
- cannot be proven, so nothing is blocked (sibling restarts stay allowed)."""
+ """True when *named* is the profile executing the guard. Without a profile identity
+ self-targeting cannot be proven, so nothing is blocked (sibling restarts stay allowed)."""
current = _current_profile_name()
return bool(current) and named.strip().casefold() == current.strip().casefold()
@@ -210,14 +213,15 @@ def contains_gateway_lifecycle_command(text: str) -> bool:
Passes, in order: raw-text regex (the only pass that fires on inputs shlex cannot tokenize, e.g.
Python source); profile-flag form; the same regex on each shell-tokenized segment with quotes/
- escapes resolved (closes splice bypasses like ``kick"start"`` / ``kick\\start``); order-independent
- launchctl pass. Single choke point for every recursion level of ``_contains_unsafe_gateway_action``.
+ escapes resolved (closes splice bypasses like ``kick"start"`` / ``kick\\start``);
+ order-independent launchctl pass. Single choke point for every recursion level of
+ ``_contains_unsafe_gateway_action``.
"""
if not text:
return False
- # Provably inert heredoc bodies (quoted delimiter, data-sink consumer like `cat > f <<'EOF'`) are
- # documentation, not commands. The stripper fails open on ANY ambiguity (unquoted delimiter, shell
- # consumer, unterminated body), so executable heredocs are still scanned.
+ # Provably inert heredoc bodies (quoted delimiter, data-sink consumer like `cat > f <<'EOF'`)
+ # are documentation, not commands. The stripper fails open on ANY ambiguity (unquoted delimiter,
+ # shell consumer, unterminated body), so executable heredocs are still scanned.
from tools.shell_heredoc import strip_inert_heredoc_bodies
text = strip_inert_heredoc_bodies(text)
@@ -241,14 +245,15 @@ def contains_gateway_lifecycle_command(text: str) -> bool:
stripped = _ARGV_LIST_PUNCTUATION.sub(" ", joined)
if stripped != joined and _GATEWAY_LIFECYCLE_PATTERN.search(stripped):
return True
- # The label may be built in an earlier `;`-segment, so neither pass above sees verb and label together.
+ # The label may be built in an earlier `;`-segment, so no pass above sees verb + label together.
return _contains_launchctl_gateway_lifecycle(normalized)
# --- shell tokenization -----------------------------------------------------------------------
def _split_logical_lines(text: str) -> list[str]:
- """Split on newlines outside quotes (a quoted newline is data, not a separator); honors escapes."""
+ """Split on newlines outside quotes (a quoted newline is data, not a separator); honors
+ escapes."""
lines: list[str] = []
current: list[str] = []
in_single = in_double = escape = False
@@ -313,9 +318,9 @@ def _iter_command_segments(command: str) -> Iterator[list[str]]:
def _executable_name(token: str) -> str:
- """Command name of an executable token. ``Path(token).name`` is "" for ``.``, ``..`` and ``/``; the
- POSIX dot-source builtin is spelled ``.``, so fall back to the raw token or ``. ./helper.sh`` would
- escape the sourced-script scan."""
+ """Command name of an executable token. ``Path(token).name`` is "" for ``.``, ``..`` and ``/``;
+ the POSIX dot-source builtin is spelled ``.``, so fall back to the raw token or ``.
+ ./helper.sh`` would escape the sourced-script scan."""
return Path(token).name or token
@@ -367,7 +372,7 @@ def contains_launchctl_submit_command(command: str) -> bool:
"""Detect an executed ``launchctl submit``/``bootstrap``, not quoted text.
Label-independent by design: a NEW job's label is attacker-chosen, so a neutral name defeats any
- label-anchored regex. Both verbs register a persistent launchd job, never safe inside the gateway.
+ label-anchored regex. Both verbs register a persistent launchd job — never safe in the gateway.
"""
for segment in _iter_command_segments(command):
index = _executed_command_index(segment)
@@ -384,8 +389,8 @@ def _mask_data_sink_arguments(text: str) -> str:
The regex cannot tell an EXECUTED lifecycle command from the same characters as *data* (a grep
pattern, a SQL literal): every argument of a ``_DATA_SINK_EXECUTABLES`` segment becomes ``arg``
and a match that survives is a real command. Strictly fail-closed: masking is skipped when the
- line pipes into a shell/interpreter, any argument carries an execution marker, or the line cannot
- be tokenized. Masking can only ALLOW what the plain regex would block, never block more.
+ line pipes into a shell/interpreter, any argument carries an execution marker, or the line
+ cannot be tokenized. Masking can only ALLOW what the plain regex would block, never block more.
"""
lines_out: list[str] = []
changed = False
@@ -429,7 +434,10 @@ def _lifecycle_command_scan_with_data_exemption(text: str) -> bool:
def _direct_lifecycle_scan(command: str) -> bool:
"""Pure-string direct scans: lifecycle regex (data-exempted) + submit."""
- return _lifecycle_command_scan_with_data_exemption(command) or contains_launchctl_submit_command(command)
+ return (
+ _lifecycle_command_scan_with_data_exemption(command)
+ or contains_launchctl_submit_command(command)
+ )
# --- path handling ----------------------------------------------------------------------------
@@ -500,8 +508,8 @@ def _resolve_script_path(script_path: str) -> Optional[Path]:
try:
return get_hermes_home() / "scripts" / raw
except (RuntimeError, OSError):
- # get_hermes_home() falls back to Path.home(), which raises when neither HERMES_HOME nor HOME
- # is resolvable (launchd/systemd) — same ingestion contract: nothing to scan.
+ # get_hermes_home() falls back to Path.home(), which raises when neither HERMES_HOME nor
+ # HOME is resolvable (launchd/systemd) — same ingestion contract: nothing to scan.
return None
@@ -562,16 +570,16 @@ def _references_at(segment: list[str], index: int, cwd: Optional[str]) -> Iterat
yield from _resolved_or_nothing(arguments[arg_index], cwd)
return
- # A bare "/" is pathlib's division operator in Python sources, not an executable; resolving it hits
- # the filesystem root and fails the regular-file check, hard-blocking innocent .py scripts.
+ # A bare "/" is pathlib's division operator in Python sources, not an executable; resolving it
+ # hits the filesystem root and fails the regular-file check, hard-blocking innocent .py scripts.
if executable.strip("/") and ("/" in executable or executable.endswith((".sh", ".bash", ".zsh"))):
yield from _resolved_or_nothing(executable, cwd)
def _iter_referenced_shell_scripts(command: str, *, cwd: Optional[str] = None) -> Iterator[Path]:
- """Yield scripts executed directly or through a POSIX shell. Each segment is read at the original
- token AND at the peeled wrapper target — additive on purpose: peeling must never REMOVE a reference
- (a local ``./timeout`` is a script, not the coreutils wrapper)."""
+ """Yield scripts executed directly or through a POSIX shell. Each segment is read at the
+ original token AND at the peeled wrapper target — additive on purpose: peeling must never REMOVE
+ a reference (a local ``./timeout`` is a script, not the coreutils wrapper)."""
for segment in _iter_command_segments(command):
index = _command_token_index(segment)
if index is None:
@@ -583,12 +591,13 @@ def _iter_referenced_shell_scripts(command: str, *, cwd: Optional[str] = None) -
def _iter_shell_command_payloads(command: str) -> Iterator[str]:
- """Yield code passed through ``sh|bash|... -c`` (and ``su -c`` / ``env -S``) for recursive scanning."""
+ """Yield code passed through ``sh|bash|... -c`` (and ``su -c`` / ``env -S``) for recursive
+ scanning."""
for segment in _iter_command_segments(command):
index = _command_token_index(segment)
if index is None:
continue
- # Read at the ORIGINAL token: peeling past `su`/`env` would discard the option carrying the command.
+ # Read at the ORIGINAL token: peeling past `su`/`env` would discard the command option.
for option in _STRING_COMMAND_OPTIONS.get(_executable_name(segment[index]), ()):
yield from _iter_option_values(segment, index, option)
index = _executed_command_index(segment)
@@ -605,9 +614,9 @@ def _iter_shell_command_payloads(command: str) -> Iterator[str]:
def _has_binary_magic(data: bytes) -> bool:
"""True when *data* starts with a known compiled-binary signature. Deliberately narrower than
- "contains a NUL": ``bash`` still executes a NUL-bearing script, so a padded script must not bypass
- the scan. A shebang always wins (interpreted, never binary). Extensions are not consulted: a
- suffixless script must still be scanned and fail closed if oversized."""
+ "contains a NUL": ``bash`` still executes a NUL-bearing script, so a padded script must not
+ bypass the scan. A shebang always wins (interpreted, never binary). Extensions are not
+ consulted: a suffixless script must still be scanned and fail closed if oversized."""
if data.startswith(b"#!"):
return False
return data.startswith(_BINARY_MAGICS)
@@ -617,8 +626,8 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:
"""Return ``(text, unsafe)`` using bounded, regular-file-only reads.
Shared choke point for every local script read, so the cloud-placeholder refusal lives here: a
- FileProvider path is never opened — not even to check hydration — because an evicted placeholder's
- ``open()`` can hang preflight. Lexical check covers direct paths; resolved check covers symlinks.
+ FileProvider path is never opened — not even to check hydration — because an evicted
+ placeholder's ``open()`` can hang preflight. Lexical check: direct paths; resolved: symlinks.
"""
if _on_cloud_path(path):
return None, True
@@ -635,8 +644,8 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:
# Directories are not scripts (`fpath=(~/.docker/completions …)` in ~/.zshrc must not
# block `source ~/.zshrc`). Devices/sockets stay fail-closed.
return None, not stat.S_ISDIR(metadata.st_mode)
- # Sniff a small prefix first: compiled binaries are never shell scripts, so skip them WITHOUT
- # reading the rest or feeding decoded garbage into the recursion.
+ # Sniff a small prefix first: compiled binaries are never shell scripts, so skip them
+ # WITHOUT reading the rest or feeding decoded garbage into the recursion.
data = os.read(descriptor, _BINARY_SNIFF_BYTES)
if _has_binary_magic(data):
return None, False
@@ -675,7 +684,8 @@ def _sanitize_remote_script_text(text: Optional[str]) -> tuple[Optional[str], bo
def _read_script_for_scanning(script_path: str) -> str:
"""Read a cron script with the bounded scanner. Non-regular/oversized inputs fail closed via a
- lifecycle-shaped sentinel; missing/unreadable paths stay empty so scheduler validation reports them."""
+ lifecycle-shaped sentinel; missing/unreadable paths stay empty so scheduler validation reports
+ them."""
resolved = _resolve_script_path(script_path)
if resolved is None:
return ""
@@ -736,8 +746,8 @@ def contains_gateway_lifecycle_command_or_referenced_script(
) -> bool:
"""Detect lifecycle/submit commands, including bounded nested scripts.
- Total by construction: never raises. Direct scans are pure string ops; the referenced-script walk
- (filesystem, remote backends, shlex on decoded bytes) is best-effort defense-in-depth — an
+ Total by construction: never raises. Direct scans are pure string ops; the referenced-script
+ walk (filesystem, remote backends, shlex on decoded bytes) is best-effort defense-in-depth — an
unexpected failure is logged and treated as "walk found nothing".
"""
try:
@@ -753,19 +763,20 @@ def contains_gateway_lifecycle_command_or_referenced_script(
try:
return _direct_lifecycle_scan(command)
except Exception:
- # If even the data-argument masker fails, fall to raw regex + submit scan so the guard stays total.
+ # If even the data-argument masker fails, fall to raw regex + submit scan: stay total.
return contains_gateway_lifecycle_command(command) or contains_launchctl_submit_command(command)
def check_gateway_lifecycle(prompt: Optional[str], script: Optional[str] = None) -> None:
- """Raise ``GatewayLifecycleBlocked`` if *prompt* or *script* contains a gateway-lifecycle command.
- The script is read from disk and concatenated with the prompt so a command cannot slip through by
- being split across the two. Callers let the ``ValueError``-shaped exception propagate."""
+ """Raise ``GatewayLifecycleBlocked`` if *prompt* or *script* contains a gateway-lifecycle
+ command. The script is read from disk and concatenated with the prompt so a command cannot slip
+ through by being split across the two. Callers let the ``ValueError``-shaped exception
+ propagate."""
combined = prompt or ""
python_script = False
if script:
resolved_script = _resolve_script_path(script)
- # Attribute the refusal correctly: not a lifecycle command, but a cloud path the guard refuses to open.
+ # Attribute the refusal correctly: not a lifecycle command, but a cloud path never opened.
if resolved_script is not None and _on_cloud_path(resolved_script):
raise GatewayLifecycleBlocked(
"Blocked: the cron script lives on a cloud-synced path "
@@ -783,7 +794,7 @@ def check_gateway_lifecycle(prompt: Optional[str], script: Optional[str] = None)
if python_script:
# Python runs via the interpreter, never a POSIX shell, and the shell reference walk is a
# false-positive generator on Python sources (pathlib "/" resolves to the filesystem root).
- # The regex still scans the full text; non-regular/oversized files still fail closed via the sentinel.
+ # The regex still scans the full text; non-regular/oversized files fail closed (sentinel).
unsafe = _lifecycle_command_scan_with_data_exemption(combined)
else:
unsafe = contains_gateway_lifecycle_command_or_referenced_script(
diff --git a/cron/monitor.py b/cron/monitor.py
index 7d63cd3bcb1..3a419084d7c 100644
--- a/cron/monitor.py
+++ b/cron/monitor.py
@@ -1,12 +1,13 @@
"""Monitor-mode cron support — hash-suppressed change detection.
-A monitor job attaches a cheap source (``monitor_script`` / ``monitor_url``) to an LLM cron job. Each
-tick runs the source FIRST and hashes its EXACT output bytes (no timestamp/whitespace normalization —
-scripts must emit stable output) against the hash from the last agent-triggering tick: unchanged →
-agent run suppressed (silent ``no_change`` run); changed/first run → a "MONITOR CHANGE DETECTED"
-block (capped unified diff + new output) is injected into the prompt; source failure → an ERROR,
-never a change, and the stored hash is left untouched. State: ``job["monitor_state"]`` in jobs.json
-(hash + last_changed_at) and ``OUTPUT_DIR/<job_id>/monitor_last_output.txt`` (for the diff).
+A monitor job attaches a cheap source (``monitor_script`` / ``monitor_url``) to an LLM cron job.
+Each tick runs the source FIRST and hashes its EXACT output bytes (no timestamp/whitespace
+normalization — scripts must emit stable output) against the hash from the last agent-triggering
+tick: unchanged → agent run suppressed (silent ``no_change`` run); changed/first run → a "MONITOR
+CHANGE DETECTED" block (capped unified diff + new output) is injected into the prompt; source
+failure → an ERROR, never a change, and the stored hash is left untouched. State:
+``job["monitor_state"]`` in jobs.json (hash + last_changed_at) and
+``OUTPUT_DIR/<job_id>/monitor_last_output.txt`` (for the diff).
"""
from __future__ import annotations
diff --git a/cron/notepad.py b/cron/notepad.py
index 6c5a91ea3b8..6f0768fd2ba 100644
--- a/cron/notepad.py
+++ b/cron/notepad.py
@@ -126,8 +126,8 @@ def list_notes(job_id: str) -> List[Dict[str, Any]]:
def clear_notepad(job_id: str) -> int:
- """Delete every key for one job (called from ``cron.jobs.remove_job``). Returns row count; no-ops
- without creating the DB when no notepad file exists yet."""
+ """Delete every key for one job (called from ``cron.jobs.remove_job``). Returns row count;
+ no-ops without creating the DB when no notepad file exists yet."""
if not _current_notepad_file().exists():
return 0
with _transaction() as conn:
@@ -138,8 +138,8 @@ def clear_notepad(job_id: str) -> int:
def render_notepad_section(job_id: str) -> str:
- """Render a job's notepad as a prompt section. An empty notepad MUST return '' so jobs that never
- use the feature get a byte-identical prompt (prompt-cache + drift safety)."""
+ """Render a job's notepad as a prompt section. An empty notepad MUST return '' so jobs that
+ never use the feature get a byte-identical prompt (prompt-cache + drift safety)."""
try:
notes = list_notes(job_id)
except Exception:
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py
index 6363c1d340d..5bb39c7e1b3 100644
--- a/cron/scheduler_provider.py
+++ b/cron/scheduler_provider.py
@@ -39,7 +39,8 @@ def _note_tick_failure(exc: BaseException, consecutive_failures: int) -> int:
def _profile_entry(entry) -> tuple:
- """Normalize a ``profile_homes`` entry (``(name, home)`` tuple or bare home) to ``(name, home)``."""
+ """Normalize a ``profile_homes`` entry (``(name, home)`` tuple or bare home) to ``(name,
+ home)``."""
return entry if isinstance(entry, tuple) else (None, entry)
@@ -198,8 +199,9 @@ def _misfire_grace_minutes() -> float:
try:
from hermes_cli.config import cfg_get, load_config
+ config = load_config()
return float(
- cfg_get(load_config(), "cron", "misfire_grace_minutes", default=DEFAULT_MISFIRE_GRACE_MINUTES)
+ cfg_get(config, "cron", "misfire_grace_minutes", default=DEFAULT_MISFIRE_GRACE_MINUTES)
)
except Exception:
return float(DEFAULT_MISFIRE_GRACE_MINUTES)
@@ -223,7 +225,9 @@ def fire_overdue_jobs(
if grace_minutes <= 0:
return 0
- from cron.jobs import ONESHOT_GRACE_SECONDS, _ensure_aware, _hermes_now, is_job_runnable, load_jobs
+ from cron.jobs import (
+ ONESHOT_GRACE_SECONDS, _ensure_aware, _hermes_now, is_job_runnable, load_jobs,
+ )
if now is None:
now = _hermes_now()
@@ -356,7 +360,9 @@ class InProcessCronScheduler(CronScheduler):
recovered = self.recover_interrupted()
if recovered:
- logger.warning("Marked %d interrupted cron execution(s) unknown after restart", recovered)
+ logger.warning(
+ "Marked %d interrupted cron execution(s) unknown after restart", recovered
+ )
# Heartbeat before the first sleep so `hermes cron status` sees a live ticker immediately.
record_ticker_heartbeat()
# EMFILE backoff: don't hammer the store while fds are exhausted; a clean tick resets it.
@@ -367,7 +373,10 @@ class InProcessCronScheduler(CronScheduler):
if can_dispatch is not None and not can_dispatch():
logger.debug("Cron dispatch paused while gateway drains existing work")
else:
- cron_tick(verbose=False, adapters=adapters, loop=loop, sync=False, can_dispatch=can_dispatch)
+ cron_tick(
+ verbose=False, adapters=adapters, loop=loop, sync=False,
+ can_dispatch=can_dispatch,
+ )
ok = True
except BaseException as e:
# BaseException, not Exception: a SystemExit must not silently kill the ticker;
@@ -408,9 +417,9 @@ class InProcessCronScheduler(CronScheduler):
)
def tick_adapters_for(profile_name):
- # Deliver via the profile's OWN adapters; NEVER fall back to the default profile's (wrong
- # bot). A credentialless satellite may ride the PRIMARY adapter only for targets an exact
- # enabled route maps here; else fail closed (delivery skipped this tick).
+ # Deliver via the profile's OWN adapters; NEVER fall back to the default profile's
+ # (wrong bot). A credentialless satellite may ride the PRIMARY adapter only for targets
+ # an exact enabled route maps here; else fail closed (delivery skipped this tick).
if profile_name is None or profile_name == default_profile:
return adapters
tick_adapters = (profile_adapters or {}).get(profile_name) or {}
@@ -426,11 +435,14 @@ class InProcessCronScheduler(CronScheduler):
recovered = self.recover_interrupted()
if recovered:
logger.warning(
- "Marked %d interrupted cron execution(s) for profile at %s", recovered, home
+ "Marked %d interrupted cron execution(s) for profile at %s",
+ recovered, home,
)
record_ticker_heartbeat()
except BaseException as e:
- logger.error("Cron startup recovery error for profile at %s: %s", home, e, exc_info=True)
+ logger.error(
+ "Cron startup recovery error for profile at %s: %s", home, e, exc_info=True
+ )
consecutive_failures = 0
while not stop_event.is_set():
@@ -441,7 +453,9 @@ class InProcessCronScheduler(CronScheduler):
_cycle_exc: BaseException | None = None
cycle_homes = [_profile_entry(e) for e in _existing_profile_homes(profile_homes)]
if profile_gate is not None:
- cycle_homes = [(name, home) for name, home in cycle_homes if profile_gate(name, home)]
+ cycle_homes = [
+ (name, home) for name, home in cycle_homes if profile_gate(name, home)
+ ]
try:
if can_dispatch is not None and not can_dispatch():
logger.debug("Cron dispatch paused while gateway drains existing work")
@@ -459,7 +473,9 @@ class InProcessCronScheduler(CronScheduler):
_profile_errors[str(home)] = f"{type(e).__name__}: {e}"
except BaseException as e:
# THIS profile only; BaseException as in the single-profile loop.
- logger.error("Cron tick error for profile at %s: %s", home, e, exc_info=True)
+ logger.error(
+ "Cron tick error for profile at %s: %s", home, e, exc_info=True
+ )
_profile_errors[str(home)] = f"{type(e).__name__}: {e}"
if _cycle_exc is None or _is_fd_exhaustion(e):
_cycle_exc = e
diff --git a/cron/scripts/classify_items.py b/cron/scripts/classify_items.py
index 101cd128cca..63bb11bf59b 100644
--- a/cron/scripts/classify_items.py
+++ b/cron/scripts/classify_items.py
@@ -4,9 +4,9 @@
The proactive-monitor pattern: a fetch step (watcher script, inbox dump, feed) produces a JSON list
of candidate items (stdin or --input-file); one call to the auxiliary ``monitor`` model scores the
whole batch and ONLY items at/above --threshold are printed. Empty stdout -> the cron job's
-[SILENT]/empty-stdout path suppresses delivery, so quiet intervals never spam. A classifier
-failure exits non-zero (never silently swallowed). Items are opaque objects; a
-title/subject/summary/text field helps, and id/guid/message_id/url is echoed back for upstream dedup.
+[SILENT]/empty-stdout path suppresses delivery, so quiet intervals never spam. A classifier failure
+exits non-zero (never silently swallowed). Items are opaque objects; a title/subject/summary/text
+field helps, and id/guid/message_id/url is echoed back for upstream dedup.
Usage: cat items.json | python classify_items.py --threshold 7 --criteria "Urgent if ..."
"""
@@ -91,7 +91,9 @@ def _parse_scores(content: str, n_items: int) -> Dict[int, Dict[str, Any]]:
return {
obj["index"]: obj
for obj in arr
- if isinstance(obj, dict) and isinstance(obj.get("index"), int) and 0 <= obj["index"] < n_items
+ if isinstance(obj, dict)
+ and isinstance(obj.get("index"), int)
+ and 0 <= obj["index"] < n_items
}
@@ -154,7 +156,10 @@ def main() -> int:
if args.format == "json":
out = [
- {"id": _item_id(item, i), "score": s.get("score"), "reason": s.get("reason", ""), "item": item}
+ {
+ "id": _item_id(item, i), "score": s.get("score"),
+ "reason": s.get("reason", ""), "item": item,
+ }
for (i, item, s) in surfaced
]
print(json.dumps(out, ensure_ascii=False, indent=2))
diff --git a/cron/suggestions.py b/cron/suggestions.py
index a7e84b32bcc..9ca896127e7 100644
--- a/cron/suggestions.py
+++ b/cron/suggestions.py
@@ -4,8 +4,8 @@ A suggestion is a ready-to-run cron job spec the user accepts (creates the real
(latched by ``dedup_key`` so it is never re-offered). Every proposal flows through here regardless
of source: ``catalog`` (curated starters), ``blueprint`` (skill ``blueprint:`` blocks, see
``tools/blueprints.py``), ``usage`` (self-improvement review), ``integration`` (connected account).
-Accepting calls ``cron.jobs.create_job`` with the stored ``job_spec`` — no second job engine; nothing
-auto-creates (consent-first). Storage mirrors ``cron/jobs.py``: ``suggestions.json``, atomic replace, 0600.
+Accepting calls ``cron.jobs.create_job`` with the stored ``job_spec`` — no second job engine;
+nothing auto-creates (consent-first). Storage mirrors ``cron/jobs.py`` (atomic replace, 0600).
"""
from __future__ import annotations
@@ -83,7 +83,8 @@ def _save_raw(suggestions: List[Dict[str, Any]]) -> None:
fd, tmp_path = tempfile.mkstemp(dir=str(suggestions_file.parent), suffix=".tmp", prefix=".sugg_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump({"suggestions": suggestions, "updated_at": _hermes_now().isoformat()}, f, indent=2)
+ payload = {"suggestions": suggestions, "updated_at": _hermes_now().isoformat()}
+ json.dump(payload, f, indent=2)
f.flush()
os.fsync(f.fileno())
atomic_replace(tmp_path, suggestions_file)
@@ -113,9 +114,10 @@ def list_pending() -> List[Dict[str, Any]]:
def add_suggestion(
*, title: str, description: str, source: str, job_spec: Dict[str, Any], dedup_key: str,
) -> Optional[Dict[str, Any]]:
- """Register a pending suggestion. Returns the record, or None when skipped: the same ``dedup_key``
- was already decided on or is still pending (never re-offer, never duplicate), or the pending list
- is full (``MAX_PENDING``). ``job_spec`` is passed straight to ``cron.jobs.create_job`` on accept."""
+ """Register a pending suggestion. Returns the record, or None when skipped: the same
+ ``dedup_key`` was already decided on or is still pending (never re-offer, never duplicate), or
+ the pending list is full (``MAX_PENDING``). ``job_spec`` is passed straight to
+ ``cron.jobs.create_job`` on accept."""
if source not in VALID_SOURCES:
raise ValueError(f"unknown suggestion source: {source!r}")
if not title.strip() or not dedup_key.strip():
@@ -185,8 +187,8 @@ def dismiss_suggestion(ref: str) -> bool:
def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""Accept a suggestion: create the real cron job from its ``job_spec``. Returns the job dict, or
- None if not found / not pending. ``origin`` (platform/chat) is merged so "origin" delivery routes
- back to the chat where the user accepted."""
+ None if not found / not pending. ``origin`` (platform/chat) is merged so "origin" delivery
+ routes back to the chat where the user accepted."""
s = get_suggestion(ref)
if not s or s.get("status") != _STATUS_PENDING:
return None
@@ -202,7 +204,7 @@ def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> O
try:
job = create_job_with_scheduler_registration(**spec)
except CronSchedulerRegistrationError:
- # The job is already durable: resolve the suggestion so a retry cannot create another local copy.
+ # The job is already durable: resolve the suggestion so a retry cannot create a second copy.
_set_status(s["id"], _STATUS_ACCEPTED)
raise
_set_status(s["id"], _STATUS_ACCEPTED)