Commit Graph

972 Commits

Author SHA1 Message Date
Teknium
3035c0c0ec fix(cron): grace_minutes=0 skips real misses instead of every run
The ticker fires seconds after the slot, so a 0 s catch-up window classified every on-time run as missed: with cron.catch_up_missed=false the job never fired at all, and with the default it still ran late misses and stamped every normal run catch_up. Floor the override at the existing 120 s tick tolerance, and let an explicit per-job grace skip a miss past its window regardless of the global catch-up default (that is what the user asked for on that job).
2026-10-28 19:40:40 -07:00
yliu325
b81e71addd feat(cron): optional per-job grace_minutes override
The catch-up window (how late a missed cron occurrence may run instead of being skipped) was
half the job's period, clamped to 120s-2h, for every job. A job can now override it outright:
0-1440 minutes, `0` meaning never catch up.

`grace_minutes` is a real 0, not "unset" — and the obvious write pattern would eat it:
`v in {None, "", False}` (the `workdir` update lambda) and `if value:` both treat `0` as
False in Python. Both doors therefore share `jobs_time.normalize_grace_minutes`, reads test
`is None`, and the renderer formats before testing truthiness.

The override moves the dispatch stamp too: `_classify_dispatch_lateness` and the dispatch
health metric read the same window, so a job the scheduler calls "late" is never reported
overdue by the dashboard.

Refused on `once`/`interval` schedules: the window describes a missed wall clock, and a
duration has none.

Split from the timezone commit so it can be reverted alone.
2026-10-28 19:40:40 -07:00
yliu325
bfa67878cd fix(cron): per-job timezone drives schedule compute and due-scan
A job may pin its own IANA timezone; its cron expression is then that zone's wall clock,
independent of the profile's configured timezone. Absent/None inherits the profile, so an
existing jobs.json keeps byte-identical behaviour and needs no migration.

The dispatch path needs the pin as much as the compute does. `compute_next_run()` resolves
the zone as job pin -> profile zone -> base offset, and every site that writes `next_run_at`
now passes it (advance, claim, resume, re-arm, recovery, and the quota/unreachable
planners); one missed site re-fires or skips a slot because the stored instant and the
expression would be read in different zones.

`_evaluate_due_job()` normalizes the stored instant into the JOB's zone, which hands every
downstream cron predicate the job's clock, and a pinned job skips
`_repair_timezone_shifted_cron` outright. That repair exists for jobs that FOLLOW the profile
zone across a zone change: on a pinned job its wall-clock comparison reads a due occurrence
as still-in-the-future and re-anchors past it.

Failing shape this fixes (profile America/Los_Angeles, job 0 9 * * 1-5 pinned to
America/New_York, scanned at 09:00 New York): `get_due_jobs()` returned [] and the job was
re-anchored to the next day, i.e. job zones east of the profile zone silently never fired.
The regression test drives the public store API and asserts both the fire and the absence of
the repair, and is proven red on main ([] and a rewritten instant).

Knobs live in the new sibling `cron/jobs_time.py`; `cron/jobs.py` stays over the file-lines
ratchet and only gained the call-site plumbing.
2026-10-28 19:40:40 -07:00
Teknium
f101b0f7b7 fix(cron): a quota hold on a manual run delays a queued run-now instead of desyncing it
When a manual run hit a provider quota window while another run-now was
queued, plan_hold moved next_run_at to the hold boundary but left
manual_run_at behind. The claim at the boundary no longer recognised the
queued extra fire, so it ran as a scheduled fire: it spent a repeat run and
dropped the scheduled slot saved in manual_run_restore_at.

extra_fire.reschedule moves the queued marker together with next_run_at, so
the run-now is delayed to the boundary and keeps its saved slot. A queued
run-now on a cron job waits for the boundary itself, not the next lattice
occurrence after it.
2026-10-28 13:08:26 -07:00
Teknium
af0d245b3a fix(cron): a run-now queued during a manual run survives its completion
A trigger_job that landed while a manual (extra) run was in flight had its
manual_run_at/manual_run_restore_at cleared by that run's mark_job_run, and
settle moved next_run_at off the queued "now", so the queued run fired as a
normal fire and completed the one-shot. The claim pops manual_run_restore_at
in its own save, so a job holding it again at completion was triggered
mid-run: keep its markers and leave it queued for its own claim.
fire_claim.at cannot order the two: the run heartbeat refreshes it.

settle's docstring said a recurring slot that passes mid-run is kept; it is
dropped (as on main). Corrected the docstring.
2026-10-28 13:08:26 -07:00
Teknium
481b6fe144 fix(cron): queued run-now intent survives a second trigger and the tick advance
Two review findings on the extra-fire change:
- A second trigger_job before the ticker claimed saved the first trigger's "now" as the slot
  to restore, so the original scheduled time was lost and the manual run consumed the one-shot.
  trigger_job now keeps the saved slot while a run-now is still queued.
- The tick's advance_next_runs rewrote next_run_at before the worker claimed, erasing the
  manual_run_at == next_run_at pair, so a gateway-forwarded recurring run spent repeat budget
  (and could retire the job). The advance now leaves a queued run-now alone; its claim restores
  the slot and owns the at-most-once advance.
2026-10-28 13:08:26 -07:00
Teknium
f799cf71d9 fix(cron): extra fires key on explicit run-now intent only
An unforced provider claim ahead of the slot keeps advancing next_run_at
(test_claim_succeeds_once_then_blocks); the dashboard Run already passes
manual=True. Diagnostics catch-all logs its traceback; user docs say a
manual run keeps the scheduled one.
2026-10-28 13:08:26 -07:00
Teknium
f656543e03 fix(cron): a manual run is an extra fire, never the scheduled one
`cronjob run` / `hermes cron run` / dashboard Run on an `in 30m` one-shot
completed the job (repeat 1/1, next_run_at null), so the real reminder
never fired; a recurring repeat.times=N job lost one of its N runs.

The fire claim now decides, under the jobs lock, whether the fire is
off-schedule (a run-now while the stored slot is still in the future)
and stamps the pending slot on fire_claim. claim_dispatch and
mark_job_run read that stamp: repeat.completed is untouched and
next_run_at stays on the slot. trigger_job (the gateway-forwarded run)
remembers the slot it overwrites and the claim restores it in the same
save, so a crash between claim and completion cannot lose it. A run at
or after the due slot is still the scheduled fire (no double fire).

The one-shot removal diagnostics move to cron/jobs_oneshot_diagnostics.py
so cron/jobs.py ends shorter than on main.
2026-10-28 13:08:26 -07:00
Ben Barclay
f4c54cd3cc fix(config-remote): a config backend outage ends one request, fire or turn, never the process
andrexibiza P1-B. ConfigBackendUnavailable subclasses SystemExit on purpose: a fail-open reader
must never serve defaults instead of the selected backend's config, and boot fails closed. That
contract stays. But long-lived consumers caught only Exception, so a plane blip after boot killed
the thread (or, inside an asyncio task, stopped the gateway's event loop).

The six named sites, each with its own outcome:
- gateway/readiness._probe_config: the existence check moved inside the guard; the outage reports
  {"status": "degraded", "detail": "config backend unavailable"}.
- cron/scheduler._load_cron_job_config: still refuses defaults (its except Exception lets the
  outage through); run_job, the fire's owner, now catches it and returns that fire's failure
  result; _run_one_job_body records it like an Exception (mark_job_run(False), finish_execution,
  crash notice) instead of re-raising into the ticker.
- cron/jobs._main_model_pin (moved to cron/jobs_model_pin.py to keep jobs.py under its cap):
  raises ValueError, so pinned=True create/update is refused as invalid input instead of silently
  dropping the lock or exiting.
- tui_gateway/server._profile_configured_cwd: None (logged); the cwd is a hint.
- tui_gateway/server._load_cfg_raw: the designed FailedConfigRead; _refuse_failed_read now
  refuses to save it with "could not be read", not "formatting error".
- tui_gateway/prompt_attachments._profile_attachments_storage: "" (logged): attachments stage in
  the profile home the sandbox mounts and the vision allowlist cover.

The owners above every other config read on a long-lived path (sweep in the PR body):
- TUI request owner already answers 4064 (_handle_admitted_request); deferred agent-build and
  resume-hydration threads now report agent_error / the resume failure and release their waiters;
  compute_host turn and frame workers answer turn.error / their error frame.
- gateway platform turn (_process_message_background) notifies the user and ends the turn
  instead of re-raising this SystemExit into the loop; api_server gets an outermost
  config_unavailable_middleware (503) since entering a profile scope reads config; the served-
  profile reconcile watcher and _serve_profile_runtime park the profile for the next rescan.

Tests: tests/plugins/config_backends/test_remote_unavailable_consumers.py (13), each raising the
real ConfigBackendUnavailable from the seam the consumer calls; every production file's fix was
reverted alone and its test(s) went red.
2026-10-27 17:33:48 -07:00
unsupportedpastels
91a4b14f63 test(gateway): keep only the MSG-44 tests that prove a fix
Keep the real-ticker LOCAL-only satellite test (red on main) and the fatal-error ownership test
(test_dropped_bot_is_never_swapped_for_the_primary: the only test that fails when ownership is
recorded after connect instead of before). Drop the reconnecting-satellite tick and housekeeping
tests and the credential-repair test (all pass on main and with ownership recorded late), and the
housekeeping and authz unit tests that only re-test has_credential_platform.

Refs #143547
2026-10-25 19:16:23 -04:00
unsupportedpastels
18e16bdd7d fix(gateway): stable bot ownership for satellite fallback; relay completions survive a restart
Addresses review feedback on #144595.

Refs #143547
2026-10-25 19:16:23 -04:00
unsupportedpastels
f18ef0a15c fix(gateway): keep a reconnecting satellite off the primary bot
When a satellite profile's own bot hits a fatal error, its adapter is
popped from _profile_adapters and parked in _profile_failed_platforms
for reconnect. With a Desktop/CLI LOCAL adapter still in the map,
has_credential_platform() saw no credential platform and the cron tick
and restart-safe drain handed the profile the primary's routed bots, so
its output went out through the wrong bot until the reconnect landed.

has_credential_platform() now also takes the profile's
_profile_failed_platforms entry and counts a parked reconnect as owning
a bot, the same signal _is_shared_bot_satellite already uses for authz.
The drain reads it from the runner; the in-process ticker gets the live
map through a new profile_failed_platforms start kwarg.

Also update the native-ingress guards fixture to the remote-media
contract: an uncached remote URL is dropped with a note and the text
kept, while the trust-upgrade refusals stay.

Refs #143547
2026-10-25 19:16:23 -04:00
unsupportedpastels
01dffd3b47 fix(gateway): keep shared-bot fallback for a satellite that has a local session
Any local session (Desktop chat, CLI run, Kanban worker) adds a LOCAL
adapter to a satellite profile's adapter map. The shared-bot fallback
at three sites tested that map for truthiness, so once it held LOCAL
the satellite stopped borrowing the primary's routed bot and its cron
results, heartbeats and background notices failed as "not
configured/enabled".

has_credential_platform() ignores LOCAL when deciding whether a profile
has a bot of its own; _adapters_for_profile, tick_adapters_for and
_drain_restart_safe_cron_deliveries use it. _adapters_for_profile keeps
the satellite's LOCAL adapter layered over the borrowed primary map.

Refs #143547
Co-authored-by: liuhao1024 <11816344+liuhao1024@users.noreply.github.com>
2026-10-25 19:16:23 -04:00
Teknium
710fa8a073 test(cron): a sweep queued behind a failing one still runs
The serialised worktree prune must queue the sweep behind, not lose it: the
one ahead raises during discovery, and the waiting sweep still takes the slot.
Red when the slot release is removed from run_sweep's finally.
2026-10-25 11:02:27 -07:00
Teknium
1accd1e8cf test(cron): keep the one invariant main lacked from the #143255 salvage
The shared-repo and own-repo cases duplicate tests/cron/test_worktree_maintenance_once_per_repo.py
(#144505); the sweep-slot invariant is the one red on main.
2026-10-25 11:02:27 -07:00
qby
2420c0d599 fix(cron): serialise the tick's worktree prune sweeps
One process ticks every served profile, so the per-profile worktree-prune throttle let each
profile decide it was due and dispatched one cron-worktree-prune thread per due profile. A
338-profile gateway therefore had hundreds of threads forking `git` at the same moment, starved
the event loop past the liveness probes and exited 75; a supervisor restart reached the same first
tick and died again (#143255).

The sweep now runs through `cron/scheduler_worktree_maintenance.run_sweep`: one sweep at a time per
process (semaphore, bounded 120 s wait), so the number of concurrent `git` children no longer
scales with the profile count. Discovery runs inside the slot too.

The per-profile throttle is unchanged: every profile still decides when it is due, and its own
repos are still pruned.

Salvaged onto main: main already carries the per-repo claim half of this fix
(`claim_due_worktree_repos`, #144505), so this keeps that one claim mechanism (now keyed on
`normcase(realpath())`) instead of the original `due_repos` and drops its window test.
2026-10-25 11:02:27 -07:00
Teknium
c1b934a9d0 refactor(cron): the per-repo worktree prune claim lives in its own sibling
scheduler.py is over the 2,000-line ratchet, so the claim added for the
once-per-repo prune moves to cron/scheduler_worktree_maintenance.py and the
facade only calls it. scheduler.py ends one line shorter than main.
2026-10-25 07:53:55 -07:00
Teknium
adc330b185 fix(worktree): prune each repo once per interval, skip the whole-tree du when the count decides
A multiplexed gateway ticks cron once per served profile and every profile resolves the hermes
checkout, so the 6 h worktree maintenance (throttled per profile home) pruned the same repo once
per profile at the same second. Each pass ends in _warn_worktree_footprint, which ran
`du -sm <repo>/.worktrees` over every file of every tree (node_modules included) even when the
tree count alone (>= 10) already decided the warning. Observed: 4-11 concurrent full walks per
burst, on every boot and every 6 h.

- cron/scheduler.py: repo discovery stays throttled per profile home (own registry and jobs);
  the prune itself is claimed per resolved repo root, once per interval across every profile
  the process serves.
- worktrees_summary(size_below_count=...) skips the size probe when the count decides; the
  footprint warning drops the size text in that case instead of printing "unknown size".
- _tree_size_mb runs du through bounded_probe_run: subprocess.run's post-kill wait() never
  returns for a du stuck in uninterruptible disk I/O, hanging the caller (a `hermes -w`
  launch or the cron prune thread).
2026-10-25 07:53:55 -07:00
Teknium
48874dd594 test(cron): keep the #141468 cases out of the over-cap test_scheduler.py
tests/cron/test_scheduler.py is past the 2,000-line ratchet, so the new
mcp-<server> and disabled-server cases move to their own file (two
invariant tests, both red on main).
2026-10-24 15:40:43 -07:00
Sahil Vishnalya
7c8810dc21 fix(cron): a configured but disabled MCP server must not widen the job either
Addresses the two findings from the review on #142172.

The allowlist match ran against the ENABLED servers only, so a job that named a
server which is configured but ``enabled: false`` fell through to the union of
every enabled server: an operator who turned a server off for maintenance
silently widened an unattended job's permissions to all the others. The
interactive resolver refuses exactly that fall-through
(``hermes_cli.tools_config._merge_mcp_servers``: "A listed server that is
configured but disabled is still the user's server selection: it stays off, and
it must not fall through to every enabled server"), so the cron helper now
matches against the configured set as well.

The new tests live next to the helper's other cases (in
``tests/cron/test_scheduler.py::TestPerJobToolsetMcpMerge``) instead of in a
file of their own: the three controls they repeated are already covered there.
2026-10-24 15:40:43 -07:00
Sahil Vishnalya
11cebb30da fix(cron): a per-job MCP allowlist must not widen into every enabled server
A job names an MCP server by its TOOLSET name (`mcp-<server>`) or by the bare
alias the registry registers for it, but the per-job merge helper compared the
job's list against the BARE server names only. The intersection never matched,
so the "a server is already listed -> allowlist, add nothing" branch was
skipped and the fallback unioned EVERY enabled MCP server into the job's
allowlist: a job that asked for one server ran with all of them.

With three servers enabled (filesystem, github, slack), a job whose
`enabled_toolsets` was `["mcp-filesystem"]` resolved to
`["mcp-filesystem", "filesystem", "github", "slack"]`.

The comparison now accepts both spellings, so the two name the same server and
mean the same allowlist. Unchanged: a list that names no MCP server still
merges every enabled one (an operator's native-toolset allowlist must not
silently strip MCP tools), and the `no_mcp` sentinel still means none.

Refs #141468
2026-10-24 15:40:43 -07:00
Teknium
3cf89871bb test(cron): move the voice-flag delivery tests into their own file
tests/cron/test_scheduler.py is over the 2,000-line cap and may only shrink.
2026-10-23 17:40:07 -07:00
liuhao1024
da1453688a fix(cron): forward the voice flag when cron delivery calls send_voice
Cron's _send_media_via_adapter used _is_voice to pick the voice sender
but never passed it on, so the Telegram adapter fell back to extension
routing and a [[audio_as_voice]] .mp3 always arrived as a sendAudio
music file while the run was recorded as delivered. Forward the flag
exactly like the gateway dispatch (BasePlatformAdapter._send_one):
voice-tagged audio transcodes into a voice bubble, plain audio-ext
attachments forward False and stay music files.

Fixes #132120
2026-10-23 17:40:07 -07:00
Teknium
cf4fe4139f test(cron): owner-scope stubs return an empty mapping, not None
cron fires now build their scope through owner_secret_scope, which merges
build_profile_secret_scope into the launch env for the launch home. Eight cron
tests stubbed that builder with return_value=None (a value the real function never
returns: it always returns a dict), so the merge raised TypeError and run_one_job
reported failure. Stub with {} instead; tests/cron passes 1480/1480.
2026-10-20 08:42:13 -07:00
kshitijk4poor
9ca23c6840 fix(cli): run every /cron form on the gateway that owns the cron store
Symptom: in a classic `hermes chat` session on the shared gateway, /cron
add|edit|pause|resume|run|remove still ran main's handler in the CLI
process, which called the cronjob tool there and wrote the profile's
cron/jobs.json from the client. Under strace, every write to jobs.json
came from the `chat --cli` process and none from the gateway.

Root cause: the one-gateway runtime (#106742) made the gateway the
owner of the profile's runtime state and of the ticker that fires cron
jobs. It left CLICommandsMixin._cron_* in the client, and the
gateway's slash.exec refused /cron for every local session except TUI
reads (2efe028116). That left the cron store with two writers.

Change:
- Move main's /cron handler (overview, list and every write) into
  hermes_cli/cli_cron_lines.py as line builders (cron_command_lines),
  with no other behaviour change. The CLI prints them when it has no
  gateway session. The unused CLICommandsMixin._cron_list goes; its
  test and eval read cron_list_lines directly.
- On the gateway, /cron is an owner command
  (gateway/session_cron_commands.py). Bare /cron and `list` are reads
  for every local session; that includes Desktop- and ACP-created
  sessions, which main refused with unsupported_command. Every other
  form is an admission-fenced control. An unclosed quote is refused as
  invalid_params before pre_command fires. `/cron list -a` keeps the
  list-all alias that the TUI read path accepted.
- A /cron write runs only when it arrives on a connection that is not
  attached to the session: the classic CLI's own command socket
  (GatewayConnection.call_until), which waits with no deadline. A
  connection attached to the session keeps main's unsupported_command.
  That is how Ink, Desktop and ACP send /cron: on their main
  connection, which the gateway answers one request at a time and
  which waits with a deadline, while a /cron run lasts as long as its
  job. The gate is on the requesting connection, not on the surface
  that created the session, so a classic CLI that resumed a TUI-made
  session still writes (as on main), and Ink on a CLI-made session is
  still refused.
- The classic CLI sends /cron to slash.exec
  (gateway_setting_commands.GATEWAY_SETTINGS) with no deadline, on a
  socket of its own (gateway_plugin_commands.call_unbounded, now shared
  with plugin commands; its Ctrl+C handle is renamed
  _gateway_command_wait). Ctrl+C prints the stopped line and
  propagates.
- Regenerate the parity table. test_pre_command_in_gateway pinned the
  old refusal of every classic CLI /cron; it now pins that the accepted
  /cron forms fire pre_command once and a refused one (an unclosed
  quote) fires nothing.

Why: the design contract allows one writer per owned store, and
clients only read and submit. The gateway already serves this
profile's cron store to its ticker and to Desktop (cron.manage). Now
the classic CLI's writes go through the same process.

Refs #134889 (T1)
Refs #139158
2026-10-20 13:08:24 +05:30
Maciej Lisiewski
6b0e0a33a9 fix(cron): stale-run reclaim acts only on the snapshot it judged
recover_interrupted_executions read rows outside a write transaction, probed
owner liveness, then marked silent live-owned runs 'unknown' without re-checking;
a worker stamping progress in between was filed wedged and its job could fire
twice. The reclaim UPDATE now also matches the snapshot's claimed_at/progress_at.
2026-10-15 22:12:28 +02:00
Teknium
2cd0ec8686 Merge origin/main into feat/unified-gateway-runtime
215 commits from main (c70332f888). One textual conflict: the generated
apps/shared/src/gateway-contract.generated.ts, regenerated with scripts/gen_gateway_contracts.py
rather than hand-merged. Brings main's fix for the dated shared-metrics install-receipt test
(783637e370).
2026-10-13 05:15:48 -07:00
Teknium
a583989f76 test(cron): a child mid-reap is exited, not a survivor of cancel
test_script_termination_reaps_descendants[stubborn-pipe-cancel] failed in CI
with "descendant <pid> survived cancel" while the product had already killed
it: the failing attempt took 10.09s vs 9.64s for the green retry, so neither
the 5s survivor poll nor the 5s pipe drain ever waited on a live child.

Mechanism: the liveness helper counted every psutil status except "zombie"
as alive. When a parent reaps a zombie, /proc/<pid>/stat reads "X"
(psutil STATUS_DEAD) between wait_task_zombie() claiming it and
release_task() unhashing it. The poll loop read "zombie" (not alive, loop
exits) and the assertion's second read landed in that window and read
"dead" (alive), so a killed child flipped back to "survived". A tight
fork/reap probe sees 27 "dead" reads per 6000 reaps and 2 such flips.

Fix: count STATUS_DEAD as not alive in the helper, and in the two sibling
helpers with the same loop-then-reread shape (test_cron_script's
setsid-grandchild timeout test, test_mcp_stability's pgroup reaping test).

Repro: a scratch pytest plugin makes pytest a child subreaper (the killed
child stays a zombie) and returns STATUS_DEAD on the first read after a
zombie read. Base: 20/20 parametrized runs fail with the CI message (and
both siblings fail); fixed: 0/20 (siblings pass), injection hit every run.
Sabotage (kill only the script root) still fails all four cases.
2026-10-13 04:04:33 -07:00
Teknium
0f2fe9ff5a fix(cron): canonical completion ids retire once nothing can replay them
Mechanism: mark_job_run appended every canonical execution id to the job's
canonical_completions (the idempotency tombstone that makes a recovered
receipt replay a no-op) and never removed one. A recurring one-minute job
grew this list by ~525k ids a year, and every membership check and
jobs.json rewrite grew with it.

Fix: the only path that can replay a completion into mark_job_run is
journal recovery (scheduler_authority.reconcile_pending iterates
cron/admissions/<hash>.json; finish_completed_run unlinks the journal as
its last step). When recording a new completion, keep only the earlier
ids whose admission journal still exists, then append the new id (it stays
last, which delivery_outcome._settle_job_record relies on). An id is
retired exactly when its recovery window has closed - no blind cap.

Test: tests/cron/test_canonical_completion_retention.py fires 65 runs
through mark_job_run with real journals: one whose tail crashed (journal
kept) plus 64 normal ones. The list is ['pending', 'run-63'], and replaying
the still-journaled completion is still a no-op (repeat.completed
unchanged). Fails on r14-base (66 ids retained).

Review: andrexibiza 4243963763
2026-10-11 23:38:03 -07:00
Teknium
eef16d28c8 fix(cron): recovery books a missing admission failed and lifts its own unknown pause
Mechanism (two branches of reconcile_pending):
- 'missing' (the owner holds no admission for the fire) paused the job,
  while the same verdict inside run_canonical_job's submit path books an
  ordinary failed run. A firer that died between journaling and the
  owner's commit therefore stopped a recurring schedule until a manual
  `hermes cron resume`.
- CronExecutionUnknown (any transport drop while polling status) pauses
  the job; when the owner's receipt later proves the run terminal,
  recovery booked output/delivery/mark_job_run but never undid that
  pause, so later fires were skipped. Main had no observer connection
  whose drop could stop a schedule.

Fix: 'missing' becomes the same terminal failed result the submit path
books (no pause); only 'unknown' pauses. Every recovery pause (the
firer's CronExecutionUnknown pause via pause_for_unknown, and
reconcile's own unknown pause) records its exact identity
(paused_at + reason) on the fire's journal; after a verified terminal
receipt is booked, the job is resumed iff it is still held by exactly
that pause, so an operator's own pause or resume is never touched.

Red on r13-base2: tests/cron/test_cron_recover_pause.py (missing ->
paused; terminal receipt -> job stays paused).

Review: dokterdok N98
Review: ahrazzle ahrazzle-B2-08
2026-10-11 19:31:34 -07:00
Teknium
3a41994f45 fix(cron): a firer-booked terminal row retires its admission journal
Mechanism: run_canonical_job journals every canonical fire; only
finish_completed_run unlinked it. The firer's other exits
(_record_fire_ownership_lost, finish_interrupted_run, the generic
exception tail of run_one_job) book the ledger row failed and return with
the journal still on disk. execution_owner_live() is False for a failed
row, so the next tick's reconcile_pending read the owner's terminal
receipt and replayed the whole tail: a second output save, a delivery of
the result the stale firer deliberately discarded, and an unfenced
mark_job_run (last_run_at/repeat/last_status rewritten).

Fix: reconcile_pending treats a journal whose execution row this firer
already finished (completed/failed) as settled: it unlinks it and books
nothing. Only rows still claimed/running/unknown (the firer never
observed the result) remain recoverable. One guard covers every
firer-terminal exit (SWEEP_cron_journal_terminal.md).

Red on r13-base2: tests/cron/test_cron_journal_terminal_exits.py (all
three exits re-save output and re-mark the job).

Review: JoaoMarcos44 JM44-r2-P1-4
Review: ahrazzle ahrazzle-B2-03
2026-10-11 19:31:34 -07:00
Teknium
3e35f5e944 fix(cron): observe a fire whose submit failed after the owner committed it
Mechanism: run_canonical_job's submit raised after the admission row committed
(a lost answer, or an owner error past the commit). It called recover, which
found the run, but only the 'missing' verdict was handled; every other status
re-raised, the outer handler turned it into CronExecutionUnknown, and the
scheduler paused the job and gave up a run the owner then completed.

Fix: recover now returns the admission's receipt (session_id, admission_id)
with its status, and the firer continues its ordinary poll loop through that
receipt when the run is queued, started or terminal. Any other verdict still
re-raises (fail closed: CronExecutionUnknown, pause).

Test: tests/cron/test_cron_recover_after_commit.py drives the real
_run_one_job_body against a real SessionAuthority/SQLite whose submit commits
(and settles) the admission and then raises; red on r12-base with either file
reverted (job paused); green: the execution row completes and the job stays
scheduled.

Review: dokterdok N61
(cherry picked from commit c8f22b60eaf2ef2de0c061c4879544c81c384d15)
2026-10-11 07:34:28 -07:00
Teknium
6ed97629c5 fix(cron): park a Bot Chat delivery whose target owner is not running
_deliver_to_bot_chat returned "... unverified: profile authority is not
ready" when find_canonical_live_owner raised (the target profile's gateway is
down, starting or draining) and wrote no receipt, so _deliver_result appended
it to delivery_errors and the run was booked delivery_failed; through the
restart-safe worker queue, delivery_queue.drain booked the row 'failed' and
claim_next never looks at it again. Nothing retried it, although the
docstring promised "stays unverified for retry". Main parked these through
cron/bot_chat_delivery.defer; this branch retired that lane in 1cc9cb9199
but kept its upgrade drain (cron/bot_chat_legacy.drain_legacy_pending, run
every tick under the tick lock), which already hands each queued record to
the live owner once, idempotently, under its own delivery id.

A not-ready target now parks the output there (bot_chat_legacy.defer, under
the same stable delivery id) and records a 'queued' receipt, which the caller
books as delivery in progress (last_delivery_queued), not as a failure. An
absent store or a delivery error keeps its existing explicit status.

Test: tests/cron/test_bot_chat_delivery_no_owner.py::test_bot_chat_target_without_live_owner_is_parked_and_admitted_later
(tests/cron/test_cron_bot_chat_delivery.py::test_deliver_without_authority_is_parked_not_a_second_writer
updated: it pinned the old unverified string.)

Review: Adolanium Adolanium-reg-2
(cherry picked from commit 963cc681b6b4bd8622b0f1e0739bfda4e954e987)
2026-10-10 22:49:17 -07:00
Teknium
b1ccce898b Merge origin/main (#38: 70 commits to c57331677d) into feat/unified-gateway-runtime
Conflicts: tests/hermes_cli/test_finite_chat_delegation.py and
tests/tools/test_completed_process_results.py, where main's lint sweep (0006a5e229) added
check=False to subprocess.run calls this branch had rewritten. Kept the branch's test bodies
and carried check=False onto their subprocess.run calls.
2026-10-10 17:47:35 -07:00
Maciej Lisiewski
bda3aea496 ci: remove unused variables (linter) 2026-10-10 15:20:14 +02:00
Maciej Lisiewski
0006a5e229 ci: fix PLW1509, PLW1510, PLW2101 linter errors 2026-10-10 15:20:13 +02:00
Teknium
2b3c8aef77 fix(cron): a firer that gives up on a canonical run records its attempt as given up
When an in-gateway firer raised CronExecutionUnknown, _run_one_job_body paused
the job and returned, but its own executions row stayed `running` until a
restart's dead-owner sweep. Receipt recovery deliberately never acts for a
same-process claimed/running row (the in-gateway ticker fires on pool
threads), so the owner's later terminal receipt could not settle it either:
history showed the run in flight for the whole process lifetime.

The give-up path now marks the attempt `unknown` with the firer's reason
through cron.executions.give_up_execution, owner-fenced to this process
(a foreign or terminal row is untouched). An `unknown` same-process row is
exactly what recovery treats as given up, so a terminal canonical receipt
settles it via recover_receipted_execution. The job stays paused (no
re-execution of uncertain work). cron/scheduler.py stays below main's size.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5475590057
2026-10-10 05:53:17 -07:00
Teknium
ee2a175608 refactor(cron): move completed-run bookkeeping to scheduler_bookkeeping
cron/scheduler.py is past 2,000 lines and the branch grew it past main
(4,485 vs 4,437). The completed-run tail (_finish_completed_run) is the
branch's largest growth there and is pure terminal bookkeeping, so it joins
fail_empty_response / finish_interrupted_run / _classify_delivery_outcome in
cron/scheduler_bookkeeping.py as finish_completed_run.

Pure move. The store/ledger writers it calls (mark_job_run, finish_execution,
self_removal_delivery_allowed, _mark_incident_alerted, delivery lane helpers)
are read off the cron.scheduler facade through a late import, the same seam
finish_interrupted_run already uses, so every existing
patch("cron.scheduler.mark_job_run") / setattr(scheduler, "finish_execution")
still intercepts. Callers updated: _run_one_job_body,
scheduler_authority.reconcile_pending, tests/cron/test_unreachable_retry.py.
No alias left in cron.scheduler.

cron/scheduler.py: 4,485 -> 4,411 lines (main 4,437).

Review: https://github.com/NousResearch/hermes-agent/pull/106742#discussion_r4230769970
(cherry picked from commit 4f0fee6e625816e07af33759023f80ede418a1a5)
2026-10-09 17:31:25 -07:00
Teknium
408cc0d12e Merge origin/main (#32: 36 commits to cf23a1a5cc) into feat/unified-gateway-runtime
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
2026-10-09 10:24:04 -07:00
Maciej Lisiewski
9eab688b42 ci: ruff UP017 fixes 2026-10-09 17:34:36 +02:00
Maciej Lisiewski
32b70e9733 ci: FURB188, FURB192 linter fixes 2026-10-09 17:31:52 +02:00
Teknium
607a23e858 Merge origin/main (#30: 54 commits to 1744a19e0d) into feat/unified-gateway-runtime
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 21:38:54 -07:00
Teknium
582ffc3681 fix(cron): an origin-less canonical run is not_configured, not queued then delivered
With deliver='origin' and no resolvable origin/home target, the direct branch of
_save_compose_deliver books delivery_outcome 'not_configured' (nothing is sent,
by design, #43014). The canonical branch skipped that verdict and enqueued the
notice anyway; the drain then found no targets, _deliver_result returned None,
and the row and ledger were terminally 'delivered' for a message that went
nowhere.

Compute unresolved_origin before the branch split and let the canonical branch
return without enqueueing, like 'local'; _finish_completed_run then classifies
the run 'not_configured' exactly as the direct path does.

Red on the previous source: test_origin_with_no_resolvable_target_is_not_configured_never_delivered
finds a pending deliveries.db row. Green after.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040
2026-10-08 19:09:29 -07:00
Teknium
15b4c3467a fix(cron): settle the run a dead drain owner's unknown delivery belongs to
recover_abandoned() fences a 'delivering' row whose gateway died as 'unknown'
(never retried), but nothing wrote that outcome back: the firer's settle_quietly
had already run against a still-'queued' row, and the drain's own write-back only
covers rows it finished itself. The job stayed last_status=delivery_queued with
no error and the ledger stayed delivery_outcome=queued forever, so `hermes cron
list` reported a delivery in progress for a send that may never have happened.

recover_abandoned now collects the job id of every row it fences (before the
same-transaction prune redacts job_json) and, after commit, calls
settle_quietly for each: job -> delivery_failed with the unknown-send error,
ledger -> failed (delivery_outcome maps unknown to failed). Execution-id fencing
in _settle_job_record keeps a later run's status untouched. No resend.

Red on the previous source: test_dead_drain_owner_settles_the_run_it_fenced_unknown
sees last_status 'delivery_queued'. Green after; test_delivery_queue.py and
test_delivery_outcome_writeback.py still pass.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040
2026-10-08 19:09:29 -07:00
Teknium
7e8e321ebd fix(cron): publish the canonical delivery row under the fire-claim fence
_save_compose_deliver sampled fence.lost() once and then enqueued the canonical
notice outside side_effect_fence(); only the direct-send branch was fenced. A
claim taken over between that sample and the insert still queued the stale
fire's notice, and execution-id idempotency cannot dedupe it against the
replacement fire's different id, so a gateway drain sent a ghost notice for a
run whose own bookkeeping then recorded the ownership loss.

claim_job_for_fire mutates the claim under the same per-job fire fence, so
holding side_effect_fence() across enqueue() makes claim-validate-enqueue atomic;
a lost claim raises _FireClaimLostDuringSideEffect exactly like a direct send.
Receipt recovery passes a claim-less fence (owner None -> nullcontext), so it is
unaffected.

Red on the previous source: test_claim_stolen_after_the_ownership_sample_queues_no_ghost_send
finds a pending deliveries.db row for the stale fire. Green after.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040
2026-10-08 19:09:28 -07:00
Teknium
f0f0907a64 fix(cron): receipt recovery books blank and [CRON_FAILURE] answers as failures
The ordinary firing tail turns two "successful" results into failures before
bookkeeping: an agent-declared [CRON_FAILURE] marker (_apply_agent_failure_marker)
and a blank/whitespace answer (empty-response soft failure). reconcile_pending
fed the owner receipt straight into _save_compose_deliver/_finish_completed_run
and skipped both, so a recovered receipt with a blank answer was booked
last_status=ok, and a declared failure was queued as an ordinary report
(delivery_queued, later ok) with failure_streak 0.

The empty-response check moves into cron.scheduler_bookkeeping.fail_empty_response
and both paths call it; recovery also applies the failure marker.

The other halves of the "Cron recovered failures" / "retry/hold recovery" P1s
were already fixed by a65200e3aa (recovery now runs through
_finish_completed_run, which only sets delivery_queued on success and consumes
_model_unreachable/_quota_hold_seconds from the receipt's job_flags). The r6-base
probe shows recovered model failure, unreachable retry (attempt 1 at +5 min) and
quota hold (next run past the window) match the ordinary path.

Red on r6-base: test_recovered_receipt_books_the_same_failure_verdicts_as_the_firer
[blank] and [declared] fail with ('delivery_queued', 0) != ('error', 1). Green after.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5458083694
2026-10-08 19:09:28 -07:00
Maciej Lisiewski
4ee5e8e0f3 ci: RUF007 2026-10-08 21:35:58 +02:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Teknium
5d8dbc5ccf fix(cron): receipt recovery never acts for a live firer, this process included
reconcile_pending replayed a retained admission journal on every tick: it
re-saved the job output and re-marked the job before recover_receipted_execution
refused the finish, so a live firer's journal produced one output file per tick
(pruning could evict real outputs) and a recover RPC per tick. The finish fence
also lost 770b5924a61's "never this process" rule: the in-gateway ticker fires
on pool threads, so a firer still in flight in THIS process had its row
finished as completed underneath it.

reconcile_pending now skips a journal before any side effect while its
execution row is claimed/running and its owner is alive, including this
process (cron.executions.execution_owner_live). recover_receipted_execution
uses the same predicate. The refusal test now gives its row a departed
foreign owner, the way the first bookkeeping test does.

Follow-up to 92422a124fec (#135061)
Follow-up to 8ab45be8730a (#135061)
Review: https://github.com/NousResearch/hermes-agent/pull/135061
2026-10-08 12:07:01 -07:00