Commit Graph

59 Commits

Author SHA1 Message Date
Maciej Lisiewski
ab72642d8b fix(cron): scrub secrets from error text persisted to jobs.json and executions.db (#155355)
* fix(cron): redact secrets before persisting errors to jobs.json/executions.db

cron/jobs.py::_mark_job_run_locked wrote raw error/delivery_error text
straight into jobs.json's last_error/last_delivery_error fields. When a
provider error embeds a key-management link (e.g. OpenRouter's
'.../workspaces/default/keys/<KEY_ID>' 403 body), the key identifier
was persisted verbatim and survived indefinitely across restarts, job
edits, and profile backups.

cron/incidents.py::_redact_error and cron/delivery_queue.py::_finish
already sanitize before persisting; jobs.json was the one cron
persistence chokepoint left raw. Fix the whole class, not just the
reported field:

- agent/redact.py: new _KEY_MANAGEMENT_URL_PATH_RE, applied
  unconditionally in redact_sensitive_text — masks /keys/<id> and
  /api-keys/<id> path segments (not caught by the existing sk-/ghp_-
  style prefix patterns).
- cron/jobs.py: new _sanitize_persisted_error() (redact + bound to
  2000 chars, mirroring incidents.py's MAX_ERROR_CHARS convention).
  Applied at every raw-error write site: _mark_job_run_locked
  (last_error, last_delivery_error) and note_fire_forward_failure
  (last_fire_error.detail).
- cron/scheduler.py: the post-interrupt update_job({last_delivery_error})
  path bypasses mark_job_run — sanitized there too.
- cron/executions.py: finish_execution() writes to the durable
  executions.db SQLite ledger, same exposure class as jobs.json
  (survives restarts) — sanitized there too.

Closes #102700.

Tests: tests/cron/test_cron_jobs_error_redaction.py (new, 10 cases)
covers the OpenRouter key-URL example from the issue, None/empty
passthrough, length bounding, redactor-failure fail-closed behavior,
and each of the four write sites. Full tests/cron/ suite: 1164/1175
passing (the 11 failures are pre-existing on unmodified main — Windows
HOME/path env issues and one process-timing flake, confirmed
unrelated by running the same files against main before this change).
tests/agent/test_redact.py (116) and tests/test_redaction_registry.py
(19) pass unchanged, confirming no regression to the shared redactor.

* fix(cron): fail closed and cover last_failure/receipt recovery when scrubbing persisted errors

Follow-up to the salvaged commit: a redactor failure now stores a
placeholder instead of the unscanned text, the sticky last_failure
detail and recover_receipted_execution's ledger write go through the
same scrub, and the unconditional /keys/<id> regex is dropped (key IDs
are not credentials and it rewrote unrelated URLs).

Fixes #102700

* fix(cron): scrub the unverified-admission reason before persisting it

The CronExecutionUnknown path wrote str(e) raw to jobs.json paused_reason and
executions.db error. Sanitize once and pass the same string to both, so the
receipt that later proves the run terminal still matches the pause it lifts.

Refs #102700

* refactor(cron): move persisted-error scrubber to cron/jobs_error_text.py

cron/jobs.py is over its size cap and only grew through an unrelated file-level
waiver; the helper now lives in a sibling with a public name, so executions.py,
scheduler.py and scheduler_bookkeeping.py stop importing a private name from
cron.jobs. jobs.py reads it through the module attribute, so one monkeypatch on
cron.jobs_error_text covers every caller. jobs.py is net 0 lines vs main.

Also pins the receipt-recovery and interrupted-run scrub sites and the
redact_url_credentials flag: each mutant now fails exactly its own test.

Refs #102700

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(cron): cap the queued-delivery error settled onto jobs.json

delivery_queue._finish redacts the row's error but does not bound it, and
_settle_job_record copied it straight into last_delivery_error - the one writer
of that field that skipped the 2,000-char cap. Run it through
sanitize_persisted_error and compare the stored form in the no-op check.

Refs #102700

---------

Co-authored-by: joaomarcos <joaomarcosdias444@gmail.com>
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-14 12:44:27 +01:00
Teknium
4e3a6a2265 fix(cron): Desktop shows Stop for a live run behind a refused Run-now
A Run-now refused while a run is live books a newer failed row, and the job
list only carried that newest row, so the Stop button vanished while the run
kept going. The list now also carries live_execution (the newest
claimed/running attempt under a live owner, one batched query shared with
cancellable_execution); Desktop offers Stop off it and settles a Stop whose
target is hidden behind a newer row as cancelled.
2026-10-30 05:54:35 -07:00
Teknium
249a90c037 fix(cron): a stopped run stays stopped in every ledger reader
Review round on cron cancel / missed-run policy:

- Receipt recovery, the external-worker waiter and finish_completed_run
  read only completed/failed as "the firer booked this attempt". A
  cancelled agent run was replayed (job marked failed, repeat spent,
  failure notice sent) and a cancelled detached worker was reported as a
  worker that died without terminalizing. One FIRER_FINISHED_STATES set
  now drives all four readers.
- live_inflight_execution skips the due scan's `missed` rows, so a
  missed note booked while a long run is live no longer hides that run
  from the dashboard.
- Stopping a ladder re-run passes ladder_rung, like every other terminal
  path, so it does not spend a second repeat slot.
- A run whose claim vanished because the job was removed (marker
  written, claim dropped) books `cancelled` with the reason at the
  first claim check and on the post-run claim-loss path, not
  "Fire claim ownership lost".
- request_cancel publishes a private temp file with link(), so
  overlapping requests never share a temp path or overwrite the first
  reason.
- Monitoring: cron_health knows `cancelled`/`missed` as terminal
  statuses, and the shared cron-run metric reports `cancelled` instead
  of `failed`.
- Dashboard history: a cancelled agent run's session row carries
  "CANCELLED · <reason>".
- A capped missed count keeps its "counting stopped at 1000" note after
  the catch-up branch books one fewer than it counted.
2026-10-30 05:54:35 -07:00
Teknium
7de83afa76 fix(cron): a cancel reaches a run hidden behind a refused Run-now, and a stopped agent run reports why
A Run-now refused while a run is live books its own newer `failed · Fire claim was not acquired`
row. The cancel lookup read only the newest row, so `hermes cron cancel` answered "nothing in
flight" for a job that was still running. `cancellable_execution` takes the newest claimed/running
row under a live owner instead.

Agent runs execute in the gateway's session authority, which got the forwarded cancel as a bare
event and logged "was stopped: cron fire ownership was lost". It now reads the execution's cancel
marker first, so the owner reports the operator's reason. The REST endpoint records
"cancelled on request (Stop)" so the run row names the surface that asked.
2026-10-30 05:54:35 -07:00
Teknium
ee394bd921 feat(cron): a stopped or removed run books 'cancelled'; each job picks its missed-run policy
Stopping a live run:
- Removing a job while it runs now cancels that run (cancel marker on its execution)
  instead of letting it burn tokens until a lost fire claim discards the result (#123045).
- An operator-cancelled run (hermes cron cancel, the new POST
  /api/cron/jobs/{id}/cancel, cronjob action=cancel, remove) records a terminal
  'cancelled' ledger row with its reason; the job's last_status is 'cancelled', with no
  failure alert and no failure-streak bump. The cancel check runs before claim-loss
  handling, so a removed job books the cancel, not "fire claim ownership lost".

Missed runs:
- New optional per-job `catch_up` (true = one catch-up run, false = skip). Unset,
  recurring jobs keep following cron.catch_up_missed and one-shots keep the 120s grace
  rule (#93526); a one-shot that opts in fires once late.
- Every skipped or collapsed slot is booked as ONE 'missed xN' ledger row, shown by
  `hermes cron runs` and the dashboard/Desktop run history.
- The execution ledger's status CHECK is widened in place (one-time table rebuild under
  BEGIN IMMEDIATE) to admit 'cancelled' and 'missed'.

The fast-forward and one-shot retire gates move from cron/jobs.py into
cron/missed_runs.py; the cancel-event types move next to the marker in
cron/cancellation.py, keeping both facades at or under their size baseline.

Prior art: #44617 (@LeonSGP43) first proposed stopping in-flight runs on pause/shutdown;
its in-process agent registry no longer applies now that runs execute in the
restart-safe worker, so the cancel rides #133169's per-execution marker instead.
name.

Co-authored-by: LeonSGP43 <LeonSGP43@users.noreply.github.com>
Co-authored-by: fangliquanflq <fangliquanflq@users.noreply.github.com>
2026-10-30 05:54:35 -07:00
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
a50325417d chore(cron): drop finish_execution's uncalled departed_owner branch
finish_execution(departed_owner=True) let receipt recovery settle a running
attempt whose firer had exited, but no caller passes it: receipt recovery
settles through recover_receipted_execution (which also covers the unknown
audit row). The branch was a second, untested path to the same write.

Removed the parameter, its docstring paragraph and the branch; behaviour of
every existing caller is unchanged (dead-code removal, no new test).

Review: kshitijk4poor kshitijk4poor-P3-cron-departed-owner
(cherry picked from commit 8ec10553dc5fb6ee9a3c99ed325cc8db1113c2e2)
2026-10-10 22:49:17 -07: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
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
David Dudok de Wit
a65200e3aa fix(cron): reconcile durable receipts through terminal bookkeeping
Recover a canonical result through the same delivery classification and execution bookkeeping as an ordinary fire. Keep a definite owner refusal until that bookkeeping survives a firing-process crash, preserve a direct retry's generated identity, and mark an unresolved journal's pause once so an explicit resume sticks.

Distinguish a received GatewayRPCError from an ambiguous transport failure. This commit carries only that transport distinction and applies directly to the source base without worker, mutation or Bot changes. The small scheduler sibling extraction keeps the existing facade size ratchet satisfied.

Validation: scripts/run_tests.sh -j 3 tests/cron/test_canonical_receipt_bookkeeping.py tests/cron/test_cron_recovery.py tests/cron/test_execution_ledger.py: 34 passed, no failures or retries on native Windows. Log: split-C-tests.log.

Review-source: greptile-apps, https://github.com/NousResearch/hermes-agent/pull/106742#discussion_r4209145065
Review-source: greptile-apps, https://github.com/NousResearch/hermes-agent/pull/106742#discussion_r4213739467
Review-source: itsflownium, https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6050777316
Source-base: NousResearch/hermes-agent#106742 at 0b815190b2
(cherry picked from commit 92422a124fec93288cc8a478c66491445884adff)
2026-10-08 09:10:27 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
770b5924a6 fix(cron): recovered cron runs settle their execution history instead of staying running
When the firing scheduler exits after the owner finished a canonical cron run
but before its own bookkeeping, reconcile_pending recovered the job status and
delivery from the owner's receipt and then deleted the admission journal --
the only link from the firer's executions row to that receipt. The row stayed
`running`, and the dead-owner sweep later rewrote it as `unknown`, so run
history contradicted the job's `ok`. Ordinary finish_execution could not repair
it because the row is ownership-fenced to the departed pid/process.

finish_execution gains a receipt-backed recovery fence (departed_owner=True):
the same terminal write, allowed only when the row's owner is provably gone
(never this process, never a live owner). reconcile_pending settles the row
with the receipt's verdict and delivery outcome before unlinking the journal.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#discussion_r4209145065
2026-10-07 23:44:54 -07:00
Teknium
b178d9098c Merge origin/main (#18: 76 commits to 3569fba6a6) into feat/unified-gateway-runtime
No conflicts. Overlapping auto-merges: agent/conversation_loop.py, agent/credential_pool.py,
cron/{executions,jobs,scheduler}.py, hermes_cli/{main,update_cmd}.py, Desktop i18n en/types,
locales/_keys.desktop.json, tests/fixtures/resolution_allowlist.json, cron docs.
2026-10-07 07:33:34 -07:00
Teknium
ca38632fc0 Merge origin/main (#17: 454 commits to e6757f2029) into feat/unified-gateway-runtime
12 conflicted files, resolved in three lanes:
- gateway/run.py: take the branch split; main's tirith removal and spool-replay
  ordering ported into run_runtime_init.py / run_bootstrap.py.
- config migrations: main keeps v50 (tirith); the branch's bot-chat timeout removal
  becomes v51 (_config_version 51, template + test updated).
- hermes_state_usage.py: main's voice_chat task route threaded through the branch's
  owner transaction; worker.persist usage allowlist accepts task.
- tui_gateway/server.py: branch side; main's edits applied where the code now lives
  (agent_factory, session_registry). Desktop sessions get the catalog toolset on the
  authority path; daemon-run finite CLI turns are not watched turns; lazy session info
  reports nous/welcome on the free tier.
- Desktop/Ink: one branch-child spinner fix (main's route-token check); main's
  uninstall i18n keys kept, pool keys stay removed; voice_turn forwarded and accepted
  by the authority submit (surface_v1.voice_turn).
- chat_ws / PTY keepalive test: main's stricter test kept.
2026-10-07 06:48:09 -07:00
Teknium
ed2dd0b35c fix(cron): live-owner stale-claim reclaim measures silence, not run length
The #115692 reclaim released any running attempt whose claim was older than
max(3 x HERMES_CRON_TIMEOUT, script timeout, 2 h), even when the owner was
healthy and busy. Every cron job that legitimately ran longer than that was
marked `unknown` mid-run, its fire claim yanked from under it and the run
aborted with "lost its durable fire claim ownership" (two weekly jobs on one
install in a single day).

The run monitor now stamps `progress_at` on the execution row every 60 s
while the agent reports recent activity, and the sweep measures the stale
bound from that stamp (claim age for legacy rows). A wedged worker stops
stamping and is still reclaimed once the bound passes.

Shape: the stamper and the inactivity watchdog loop (which reads the same
idle signal) live in a new topical sibling cron/scheduler_liveness.py, so
cron/scheduler.py shrinks (4457 -> 4436 lines) instead of growing.
2026-10-07 06:29:09 -07:00
Teknium
e1de0c2665 fix(cron): write a drained delivery's outcome back onto the run that queued it
Agent cron runs hand their send to the durable delivery queue and book
last_status=delivery_queued / ledger delivery_outcome=queued. Nothing ever
wrote the drain's result back, so after a gateway sent (or refused) the
message the job stayed "delivery still in progress" forever and a refused
send never surfaced as delivery_failed + last_delivery_error (review M1;
main records ok/delivered and delivery_failed/failed + error).

cron/delivery_outcome.py settles a terminal queue row onto:
- the execution ledger: only a terminal attempt whose delivery_outcome is
  still 'queued' (new executions.settle_delivery_outcome), and
- the job record: only while the execution is both the ledger's latest
  attempt for the job and the job's latest canonical completion, so a later
  run's status is never rewritten.

It runs after the drain's _finish, after the run's own bookkeeping (a drain
can win the race before mark_job_run lands; _finish_completed_run also
books the settled outcome instead of 'queued'), and after receipt
recovery. Write-back failures are logged, never undo the at-most-once send.

Restores main's assertions in the rewritten W1 tests, checked after an
explicit drain: test_warning_execution_outcome (ok/delivered|suppressed),
test_cron_failure_deliver (delivered / failed outcome after drain),
test_fire_claim_lost_after_delivery (last_status ok),
test_script_claim_heartbeat self-removal (delivery_outcome delivered).
New invariant test: test_delivery_outcome_writeback (sent/refused x drain
after run / drain before bookkeeping).

(cherry picked from commit 0402eff3d91050bbfa68b83ba6f3d7169700da3f)
2026-10-06 21:58:20 -07:00
kshitijk4poor
5fff7380ab fix(cron): settle the execution receipt when dispatch fails after creating it
_submit_with_guard persists a `claimed` receipt before the worker runs, and
run_one_job only owns the terminal writes once it starts. Two exits in
between left the row `claimed` forever (a permanently in-flight attempt
for a run that never happened): a fire claim raising anything other than
OSError in _process_due_job, and a failure in _submit_with_guard after
create_execution returned (note_cron_execution, context copy). Both now
close the receipt through a best-effort settle_unstarted_execution in
cron/executions.py (the ledger owner; scheduler.py is a capped facade); the
claim failure still re-raises so the real error surfaces.

Co-authored-by: PRELVAS94 <86016656+PRELVAS94@users.noreply.github.com>
2026-10-07 10:20:18 +05:30
Austin Pickett
46370fd2a2 fix(desktop): gate cron-run writes on scheduler ownership, re-evaluated per send
The view-only decision for a never-closed cron run keyed on `is_active`,
a 300s activity window. A live run inside a long tool call writes no
heartbeat, reads inactive exactly like a zombie, and was latched
read-only for the rest of the app session.

- Backend: run rows (and the session detail of a cron run) carry
  `scheduler_owned` — the job's in-flight execution is held by a live
  process (pid + start-time fingerprint) and the session started under
  that claim. An older never-closed run of the same job stays a zombie.
- Desktop: the latch becomes a per-run verdict that is re-evaluated on
  every Cron surface poll and, authoritatively, right before any send
  (primary chat and tiles). A run that ticks, is owned, or closes becomes
  writable again; one whose process dies becomes view-only.
- Restored route/tab after a restart: the pre-send refresh recognises a
  cron run by its session id and gates it even though no surface ever
  evaluated it; an unreadable unknown run fails closed.

Refs #88443
2026-10-01 09:44:06 -04:00
unsupportedpastels
96982d6284 fix(cron): retain bounded history after targeted worker recovery 2026-09-30 20:57:21 -04:00
Finn763
ef64034005 fix(cron): record a lost manual run instead of reporting a restart that never happened (#128509)
A restart-safe cron worker that dies AFTER adopting its attempt was reported as
"Scheduler restarted after this execution's owner exited" and treated as success.

recover_interrupted_executions() only knows that an owner is gone, so that is all it
can write -- but the waiter holding the worker's Popen knows the owner was that
worker and knows its exit status. Worse, the sweep leaves the row terminal, so the
waiter returned True, run_one_job short-circuited, and mark_job_run never ran: the
job's fire claim outlived its lost execution and refused the next manual fire with
"Job is already being fired" for the whole 300s lease, with an empty last_error.

- executions.terminalize_dead_owner(): terminalize ONE attempt with an observed
  cause. Refuses a live owner, this process, and a handoff inside the adoption
  grace, so it can never steal a running worker's attempt; returns False so the
  caller keeps the generic sweep.
- The waiter records that cause and RAISES, routing the existing post-handoff
  bookkeeping: mark_job_run records the run and retires the claim, no dispatch
  incident and no false crash notice. Also folds the worker's captured stderr into
  the error, which the pre-ack path already did (#112729) and this path dropped.

(cherry picked from commit d3f3571f8c6f4d2f188e90151d8f8393f049a573)
2026-09-30 20:57:21 -04:00
teknium1
f4075a20d6 feat(telemetry): gateway platform health, delivery, first-reply latency and cron run metrics
The gateway and cron ticker were blind spots in shared metrics: we could not
tell which messaging platforms fail to connect or drop, how often replies fail
to reach users, how long users wait for a first reply, or whether scheduled
jobs run, fail, get skipped or get missed while Hermes was down.

New opt-in counters (all through the existing enabled() / record_process_mark
gate, recorded fire-and-forget on one background worker that runs in a copy of
the caller's context so the owning profile gets the row):

- hermes.platform.health: platform, event (connect_ok/connect_failed/
  reconnect/disconnect), error_class. One seam in the runner
  (_connect_adapter_with_timeout, used by cold start, multiplex secondaries and
  the reconnect watcher) plus the fatal-error handler; classified from
  exception types, HTTP statuses and Hermes's own fatal codes, never text.
- hermes.platform.delivery: platform, outcome, failure_class. One row per
  logical BasePlatformAdapter._send_with_retry call (retries and plain-text
  fallback included), from SendResult's typed fields or the exception type.
- hermes.gateway.reply_latency: platform, first_response_bucket. Clock starts
  when _handle_message accepts a non-internal turn; stops on the stream
  consumer's first delivered text or send_final_ledgered. Busy acks and
  command replies never stop it.
- hermes.cron.run: outcome (success/failed/missed/skipped), delivery_kind,
  duration_bucket. Recorded at the write-once terminal execution row
  (finish_execution) and where the due scan drops an occurrence (catch-up
  disabled, expired one-shot). Job names, prompts and targets never leave.

Platform names: platforms Hermes ships under plugins/platforms/ now report by
name, and a plugin-catalog platform reports its catalog entry name only when
the installer-owned .install-metadata.json record proves a catalog install of
the plugin dir that defines the registered adapter factory (a URL install
cannot claim a catalog name via its tree or manifest). Everything else stays
"plugin". GATEWAY_PLATFORMS becomes catalog-backed (_CatalogValues), and the
v3 schema's platform fields accept published catalog identifiers.
2026-09-28 12:43:03 -07:00
alt-glitch
318f6ac63f fix(cron): order execution, delivery and incident history by instant, not by text
The cron SQLite stores write hermes_time.now().isoformat(), an ISO string
that carries the local UTC offset. That offset changes at a DST transition
and after a timezone config change, so the text order of these columns is
not their time order. Across a fall-back, 01:10-05:00 is 20 minutes after
01:50-04:00 but sorts before it. latest_execution(), latest_executions()
(which fills job["latest_execution"] for `hermes cron list` and the
dashboard), list_executions() and its before_claimed_at cursor, the
delivery queue's pending-claim order, delivery and execution pruning, and
list_incidents() all returned the older row first.

Every ORDER BY and the cursor comparison on these columns now use
julianday(col), which SQLite resolves to the same instant for any offset.
The raw text stays as the next sort key, so rows within the same
millisecond (julianday's resolution) keep their microsecond order, and the
cursor compares the same (instant, text) key on both sides. Stored values
and the schema are unchanged, so existing rows with mixed offsets order
correctly without a migration.

latest_executions() moves from a correlated per-row subquery to one
ROW_NUMBER() window. With julianday() in the ORDER BY the index on
claimed_at no longer serves the per-row LIMIT 1, and the correlated form
took about 90 ms at 1000 rows; the window form takes about 1 ms.

Refs #86520
Thanks to #86889 (zhao0112) for the executions-ledger diagnosis.
2026-09-28 19:07:43 +05:30
teknium1
36ede56a66 fix(gateway): share the drift-tolerant start-time comparator across every owner-liveness check
Review follow-up for #117505: delivery_ledger, api_server_runs and
async_delegation reconciled a live owner to dead/unknown on the same 1 s
same-host fingerprint drift that cron/executions had just stopped doing.
One comparator (gateway.status.start_time_fingerprints_match) replaces the
private cron tolerance and the three exact-equality sites.
2026-09-20 16:33:19 -07:00
liuhao1024
52abb64c8f fix(cron): treat a drifted start-time fingerprint as a live owner in recovery
_owner_is_live() required the recomputed start-time fingerprint to be exactly
equal to the one recorded at claim time. On hosts where same-host readings
drift by ~1s (macOS kern.boottime adjustment), every long-running execution
was reconciled to unknown while its owner process was still alive and healthy.
A mismatch is now treated as inconclusive within a small tolerance (both
platform fingerprint scales are x100, so 200 means 2s), and an unreadable
reading is fail-safe, matching the function's existing posture that inability
to prove death must not rewrite durable state.
2026-09-20 16:33:19 -07:00
kshitijk4poor
2d0867695d refactor(cron): one claim-TTL headroom constant shared by the job store and the ledger 2026-09-20 17:59:57 +05:30
kshitijk4poor
2eb40f71d8 fix(cron): derive the live-owner stale bound only when a live-owned row is seen
The bound reads the script timeout, which falls through to load_config() when
HERMES_CRON_SCRIPT_TIMEOUT is unset. Computing it eagerly on every reap put a
config load back on the idle gateway tick (CI: tests/cron/test_idle_tick_config_skip.py).
Resolve it on the first live-owned claimed/running row instead; an idle tick with no
such rows stays config-free.
2026-09-20 17:59:57 +05:30
kshitijk4poor
77592f4ec2 refactor(cron): claim age from the aware timestamp only 2026-09-20 17:59:57 +05:30
kshitijk4poor
f4b4032211 docs(cron): reap docstrings describe the live-owner stale bound 2026-09-20 17:59:57 +05:30
kshitijk4poor
b552dc9a8c fix(cron): derive the live-owner stale-claim bound from the configured timeouts
The carrier used a hardcoded 7200 s wall-clock ceiling. HERMES_CRON_TIMEOUT is
an *inactivity* limit (cron/jobs.py, _run_agent_with_watchdog), so a healthy
agent job in the external-worker topology can legitimately run past any fixed
wall clock; marking its row `unknown` releases the gateway's running guard and
the next tick double-dispatches while the first worker is still running (its
later finish_execution is fenced out). The constant also ignored
HERMES_CRON_TIMEOUT=0 (unlimited) and HERMES_CRON_SCRIPT_TIMEOUT > 7200.

Mirror cron/jobs.py::_oneshot_run_claim_ttl_seconds instead:
stale_after = max(3 × HERMES_CRON_TIMEOUT, script timeout, 7200), reusing the
existing accessors (_cron_inactivity_seconds, _get_script_timeout). When the
inactivity timeout is 0/unlimited or not a finite positive number there is no
bound to derive, so live owners are skipped entirely (fail closed — today's
behaviour). Drop the `except (ValueError, TypeError): pass` swallow (rows are
always aware ISO from hermes_time.now), fix the stray whitespace in the
SELECT, record a distinct `error` reason for the wedged-owner case, and keep
the comment honest: the deadlocked worker process is not terminated, and
in-process rows (process_id == _PROCESS_ID) remain out of scope.
2026-09-20 17:59:57 +05:30
holny
086da1e072 fix(cron): wall-clock stale-claim guard for live-but-deadlocked workers (#115692)
A claimed/running execution whose owner process is alive but permanently
deadlocked (e.g. futex_wait after a route/proxy flip) passes _owner_is_live()
and is never reclaimed — the execution row stays 'running' forever and the
job rejects every subsequent fire with 'Job is already running'.

recover_interrupted_executions() now also checks the wall clock: a
claimed/running row older than STALE_RUNNING_CLAIM_TIMEOUT_SECONDS (7200 s,
covering the 3600 s script timeout + 600 s inactivity watchdog + margin)
is marked unknown even though the owner PID is alive.

Tests: stale claim recovered, recent claim NOT recovered.
2026-09-20 17:59:57 +05:30
kshitijk4poor
55b254a2c7 refactor(cron): keep the suppressed disposition, drop the delivery-manifest ledger rework
The suppression feature needs one cron cell: a failure notice whose target hides warning
notifications is recorded as `suppressed` (bot_chat_pending record, deliveries queue row,
execution delivery_outcome) instead of being sent. That is kept.

Everything else the PR added to cron/ is an independent ledger rework and is removed here:
execution delivery manifests + filesystem manifest journal, `schema_meta` fence and the
"legacy intent adoption" layer, incident occurrence generations + trigger, jobs projection
CAS (`bind_delivery_execution`/`update_delivery_projection`), the per-tick projection
reconciler, and the `_deliver_targets`/`_settle_manifest` split. origin/main has none of
the state that layer migrates from (zero occurrences of delivery_manifest / manifest_journal
/ schema_meta); the "pre-flag old writer" the r5-r9 tests simulate is a vendored snapshot of
this PR's own earlier revision (tests/cron/_r5_prior_executions.py). Those fixes may have
merit on their own and should land as separate PRs with a main-reproducing test each.

Also restores main's `_classify_delivery_outcome` precedence (`failed` before `queued`)
and drops the SHA-pinned `git show <PR commit>` test, which would go red the moment a
rebase-merge rewrote that commit.
2026-09-18 01:43:35 +05:30
Victor Kyriazakos
cd3de040ab feat(notifications): opt-in suppression of user-channel warning notifications
Squash of the 54 commits on victor-kyriazakos:feat/user-channel-warning-suppression
(PR #112302, head f45c640e55) so the contributor's authorship survives a rebase-merge;
the commits interleave with a cron delivery-ledger rework that the salvage removes in
follow-up commits, so per-commit cherry-picks were not practical.

Adds display.suppress_warning_notifications (global + per-platform, default false):
one resolver (gateway/warning_notifications.py), BasePlatformAdapter.emit_warning /
emit_media_warning / warning_text, a notification_category classification carried
through wakes, queues and persistence, and render/present boundaries for CLI/TUI.
2026-09-18 01:43:35 +05:30
teknium1
579dbe0c71 fix(cron): sqlite_util imports are late so a running scheduler survives an on-disk upgrade
cron/ledger.py (e24c8499) existed so a long-running scheduler that lazily imports
notepad/incidents AFTER `hermes update` never needs new names from a module it already has
cached. The dedup deleted it and imported open_db/transaction from hermes_cli.sqlite_util at
module level; a pre-upgrade daemon has the OLD sqlite_util cached (executions imported
add_column_if_missing from it), so the first job tick after an upgrade would ImportError in
scheduler_prompt._build_job_prompt until restart.

- cron/{notepad,incidents,executions,delivery_queue}: import open_db/transaction/
  add_column_if_missing and cron.jobs._ensure_cron_dir inside _connect/_transaction/
  _initialize_schema. This also stops the 3.8k-line cron.jobs being pulled eagerly by
  importing a store (it was lazy in cron/ledger.open_ledger).
- gateway/hosted_rooms_common, hosted_room_policy_checkpoint: same treatment; the gateway
  imports hosted_rooms lazily from request handlers, so it has the same skew exposure.
- tests/cron/test_upgrade_module_skew.py: simulate the real skew (delete open_db/transaction
  from the cached sqlite_util, then import each store). The previous repoint deleted names
  from cron.executions, which notepad/incidents do not import from, so it passed regardless.
  Sabotage: a module-level `from hermes_cli.sqlite_util import open_db` in notepad fails it
  with "cannot import name 'open_db'".
2026-09-13 05:08:29 -07:00
teknium1
576accd92b refactor(sqlite): one open_db/transaction layer for every small store; plugin DBs use the WAL fallback
Twelve modules each carried their own sqlite3.connect + PRAGMA + `with conn:`
stack. The #69567 fd-leak fix (a `with conn:` commits but never closes, so each
call leaked a connection and its WAL/SHM fds until GC) was pasted as code plus
docstring into six of them and hosted_room_policy_checkpoint never received
it; plugins/plugin_storage.plugin_db was the only production caller issuing a
raw `PRAGMA journal_mode=WAL`, bypassing the network-FS fallback, the
WAL-reset-bug gate and the never-live-downgrade invariant that
hermes_state_wal.apply_wal_with_fallback carries.

hermes_cli/sqlite_util.py (already home to add_column_if_missing/write_txn,
imported by cron, gateway and hermes_cli alike) gains `open_db(path, *,
db_label, busy_timeout_ms, wal, foreign_keys, synchronous_full, row_factory,
check_same_thread, wal_lock_retries, initialize)` and `transaction(conn,
immediate=)`; cron/ledger.py is deleted and hosted_rooms_common's
open_sqlite/connect/transaction become 1-3 line forwarders. Migrated:
agent/verification_evidence, cron/{executions,incidents,notepad,
delivery_queue}, gateway/{delivery_ledger,hosted_room_policy_checkpoint,
hosted_rooms_common (-> hosted_rooms, hosted_room_driver)}, hermes_cli/
projects_db, tools/async_delegation, plugins/plugin_storage.

Behavior changes (each module keeps its effective PRAGMA set otherwise):
- hosted_room_policy_checkpoint: connection now closed after every use and
  on init failure (was leaked per call), busy_timeout PRAGMA set explicitly.
- projects_db: gains busy_timeout=5000 (was the sqlite3 default 5 s connect
  timeout with no PRAGMA); explicit and observable.
- delivery_ledger / async_delegation: busy_timeout PRAGMA now mirrors the
  10 s connect timeout they already had.
- plugin_storage.plugin_db: WAL through apply_wal_with_fallback (DELETE on
  network filesystems / WAL-reset-vulnerable builds instead of raw WAL);
  busy_timeout=5000.
- cron/incidents._redact_error: redact_sensitive_text(force=True) — the
  error text is persisted to disk.
- delivery_ledger's private duplicate-column guard and the unguarded
  `ALTER TABLE ADD COLUMN` sites (shared_metrics, api_server_run_idempotency,
  holographic store, kanban model_override) go through add_column_if_missing.
- hermes_state.py::_scrub_surrogates: dead byte-copy of
  hermes_state_messages._scrub_surrogates (0 callers) deleted.
2026-09-13 05:08:29 -07:00
Teknium
5280fe9987 fix: cron and local DMs reach an open Desktop Bot Chat
Route local producers to durable owner ingress before attempting the unowned
CLI lane. Preserve per-run/per-message IDs and receipt-first retry handling;
never fall back after ambiguous admission. Report cron admission as queued,
not completed or failed, in job status, the execution ledger and CLI/tool UX.

Native isolated Electron validation reproduces SESSION_NOT_OWNED on main for
both idle and busy owners. Fixed owner consumes idle cron, busy cron, local
DM and mounted-chat cron exactly once, keeps its lease, yields to queued
human input, and preserves the prior model-request prefix and tool schema.
Inference alone used a deterministic loopback wire stub; no paid model call.
2026-09-07 16:48:29 -07:00
fangliquanflq
e24c8499f2 fix(cron): isolate ledger helpers from stale execution modules 2026-09-07 06:01:31 -07:00
Teknium
7d6d0709cd fix(cron): skip completed scheduled occurrences after snapshot rollback
Capture the exact UTC scheduled instant before either due scanning or the
external fire claim advances jobs.json. Bind it to the durable attempt
before worker handoff; manual and unclassified direct attempts stay null.
Consult any retained completed matching row, independently of stale stamps,
claim-time windows, and newer failed attempts. Preserve unknown and legacy
attempt eligibility rather than guessing that a side effect completed.

Real isolated restart probes reproduce duplicate script writes on base and
suppress them on the fix for builtin tick and provider fire. Distinct and
manual occurrences still execute. The campaign-serialized cron suite is
queued; this progressive commit preserves the verified integration step.

Credit holny's issue #104790 and guard proposal #104323; exact identity
replaces the approximation rather than importing its legacy heuristic.

Co-authored-by: holny <holny@foxmail.com>
2026-09-07 05:57:26 -07:00
Teknium
53db597201 simplify(compat): hermes_state — drop 81 re-exports + 3 registry aliases + 3 shims, repoint 45 callers + 60 test files
hermes_state.py: delete every '# noqa: F401 (re-exported...)' import block (hermes_state_common/errors/guard/
readpool/sessions/fts/dbfile/wal/repair/registry + agent.context_compressor _DB_PERSISTED_MARKER_KEY); keep
only the names hermes_state.py itself uses, without noqa.
hermes_state_registry.py: drop get_shared_session_db/release_shared_session_db/close_shared_session_dbs
aliases; every caller (gateway/, tools/, tui_gateway/, cron/, mcp_serve, run_agent, tests) now imports
acquire/release/close_all/release_or_close from hermes_state_registry.
hermes_state_titles.py: drop set_auto_title_if_empty shim (title_generator keeps its getattr fallback).
Re-remove shim-only names restored by 34abf954bd: latest_user_message_row_id (tests call
latest_message_row_id(key, role='user'); role-targeting assertions kept) and get_session_activity (tests
build the snapshot via agent.session_activity.build_activity_snapshot over db.get_session(sid)).
hermes_state_wal._log_once resolves its dedupe sets as module globals instead of via hermes_state;
hermes_state_repair helpers call module globals directly (tests patch hermes_state_repair.<name>).
Frozen updater surface untouched (update_cmd_maint imports only SessionDB from hermes_state).
2026-09-03 13:46:50 -07:00
Teknium
0071ba9965 Merge origin/main (561b053f79) into simp/forwardport: forward-port 220 main commits into the simplified tree 2026-09-03 03:31:03 -07:00
kshitijk4poor
b440a492b3 fix(cron): keep unsent worker deliveries queued, cheapen handoff polling
Follow-up to the salvaged restart-safe worker (#101877):

- delivery_queue: a row still `pending` at the worker's wait timeout was
  marked `failed` and never drained, so any gateway outage longer than the
  300s budget (e.g. a restart that runs `hermes update`) silently lost the
  delivery. Unclaimed rows are certainly unsent, not uncertain — leave them
  queued for the next gateway; only mid-send rows are fenced `unknown`.
- delivery_queue: stop running the full-table prune UPDATE+COUNT inside
  every transaction (each `get_status` poll paid for it; terminalizing
  paths already prune explicitly); poll at 1s instead of 250ms.
- delivery_queue/executions: use `hermes_state.apply_wal_with_fallback`
  (bare `journal_mode=WAL` raises on NFS/SMB homes) and the race-safe
  `hermes_cli.sqlite_util.add_column_if_missing`; drop the copied
  owner-liveness helpers in favour of the ones in cron.executions.
- scheduler: the parent waited on the worker by re-opening the executions
  ledger every 50ms for the whole run (~20 opens/s, hours). Wait on the
  process with a 1s timeout instead — the worker commits its terminal row
  before exiting — and reap stranded payload/ack files once terminal.
- scheduler: skip the housekeeping drain until a worker has actually
  created deliveries.db, so non-systemd gateways never open it.
- scheduler: set up hermes logging in the detached worker entrypoint; it
  runs with stdout/stderr on DEVNULL and previously logged nowhere.
- tests: test_lost_fire_claim_stops_stale_delivery still mocked
  `mark_execution_running -> None`, which now means "ownership lost, return
  before run_job" — the test passed without ever reaching the path it
  names. Mocking `{}` restores it (mutation-checked).
2026-09-03 12:40:26 +05:30
Brooklyn Nicholson
83efdf5e5e [verified] fix(cron): close restart handoff races 2026-09-03 12:40:26 +05:30
Brooklyn Nicholson
29e5172487 [verified] fix(cron): harden gateway restart handoff 2026-09-03 12:40:26 +05:30
Brooklyn Nicholson
3373e97693 [verified] fix(cron): preserve active runs across gateway restart 2026-09-03 12:40:26 +05:30
Teknium
b385c0198f refactor(cron): rewrap long comment/docstring lines to 100 cols 2026-09-02 19:37:58 -07:00
Teknium
baf31733e9 refactor(cron): AST-neutral bracket packing 2026-09-02 19:32:42 -07:00
Teknium
b3d9b20a3b refactor(cron): share ledger connect/prepare/transaction across executions, incidents, notepad; compact suggestions 2026-09-02 19:18:21 -07:00
Teknium
064bcaf3c1 refactor(cron): compact scheduler_provider and small cron modules
- scheduler_provider.py: _profile_entry/_profile_cron_scope replace four hand-rolled
  home-override+store blocks in the multiplex ticker; comments compacted to the WHY.
- incidents/executions/notepad/monitor/suggestions/blueprint_catalog/__init__: docstrings
  and comments compacted; no code change (AST-identical).
2026-09-02 13:29:30 -07:00
Gille
000d22b9db fix(cron): keep deleted profiles from returning 2026-08-28 13:39:19 +05:30
Evgenii
acaafcc6bb fix(cron): make immediate execution race-safe
- claim_job_for_fire returns the atomically claimed snapshot with a unique
  fire owner; heartbeat_fire_claim renews the lease; mark_job_run fences
  terminal writes by expected_fire_owner so a stale worker cannot record
  over a replacement claim.
- run_one_job heartbeats the fire claim and forwards a combined cancel
  event (ownership loss OR external cancel) into run_job; the agent path
  is interrupted cooperatively and script-based jobs (no_agent + pre-run
  scripts) are hard-stopped with a process-tree kill (POSIX killpg
  SIGTERM then SIGKILL for surviving group members; Windows
  taskkill /T /F), with a bounded pipe drain so a SIGTERM-ignoring
  descendant cannot wedge the worker on communicate() EOF.
- Shutdown interruption is scoped to the exact execution token instead of
  the bare job ID, so a replacement run of the same job never consumes a
  stale interrupted flag.
- fire_claim_fence serializes save/deliver side effects per profile+job
  with a cross-process flock; remove_job prunes the fence-lock entry.
- Preserves upstream BaseException terminal recording (#73973),
  completed one-shot retention (#80624), blocked_config preflight
  (T1-26), and the advance_next_runs batch on top of current main.
2026-08-14 20:46:50 -07:00