Commit Graph

7381 Commits

Author SHA1 Message Date
kshitijk4poor
57644ec000 fix(process): a family's stop path releases its group only once the group is empty
Same class as the router fix: nine stop paths released their group from the owner-death supervisor
as soon as the leader exited, but members that ignore TERM or outlive the leader keep the group
alive. Releasing it let those members survive a later kill -9 of this process.

Lightpanda, real-profile Chrome, embedded cua-driver, the TTS command provider, dashboard WhatsApp
pairing, the raft and WhatsApp bridges, verify's app server, agent-browser session groups, and
Browser Use harness daemons stopped by --reload now go through release_process_group_once_empty.

New test stops a raft bridge whose TERM-ignoring helper survives. It fails when raft releases
unconditionally, and the group stays covered with the fix. Test seams moved from the per-module
release_process_groups name to the shared helper.

Reported by Greptile on #137057 (thread on the router).
2026-10-29 16:58:09 +05:30
kshitijk4poor
c2b1e4391c refactor(process): one release-once-empty helper; the kernel and slash-worker tests stop racing a loaded host
LSP, the code kernel and the slash worker each had their own "release the group once nothing in
it is left" (a killpg(pgid, 0) probe; the kernel's version also waited for reaps). They are now
one helper, process_identity.release_process_group_once_empty(pgid, proc=, timeout=). It polls
the leader so a zombie leader does not keep the group alive, waits up to `timeout` for killed
members to be reaped by init, and keeps covering a group that still has a member. LSP's async
close path probes once (timeout=0), as before.

The slash worker used to probe exactly once right after SIGKILL. On a loaded macOS host (load
25+) init had not reaped the killed members yet, so a group that was about to be empty stayed
registered (test_close_stops_the_whole_group_then_releases_it, flaky). It now waits up to 1 s,
like the kernel did.

The kernel survivor test raced too: under load the cell child's `trap '' TERM` could land after
the teardown's SIGTERM, and the 5 s escalation could SIGKILL it. The child now signals once its
trap is installed, and the test turns escalation off (the escalation is not what it pins).

New tests/hermes_cli/test_process_identity_release_once_empty.py: an unreaped empty group is
released, a live member keeps it covered, a late exit is waited for, and Windows never releases.
Teeth: forcing the helper to always release, or to never release, turns 5 tests red in the 4
touched files. macOS: the 9 owned-child files, 78 tests, 3 runs in a row, 0 flaky.
2026-10-29 16:58:09 +05:30
kshitijk4poor
6ff702ec0d chore(process): mark the agent/plugin detached spawns that are not owned children, with the reason
The detached-spawn check (scripts/check_detached_spawns.py, from the owned-child API) flags every
start_new_session outside spawn_owned. Five sites in this family are deliberately not owned. Each
now carries a `detached-spawn: ok — <why>` marker, so the check passes without a baseline entry:

- iron-proxy daemon: meant to outlive the CLI that started it; `hermes egress stop` ends it
  through the pidfile + nonce.
- google_meet bot: reached through files across turns and stopped by meet_leave (pid in
  .active.json).
- photon sidecar: exits on stdin EOF (PHOTON_SIDECAR_WATCH_STDIN). kill -9 probe with that exact
  watch block: 0 of 1 survived; the same probe with the watch off: 1 of 1 survived.
- ddgs search worker: awaited under a 30 s cap that kills its group. Blocked reading its request
  on a stdin pipe, it exits when the owner dies (kill -9 probe: 0 of 1 survived).
- secret_sources command helper: awaited under a hard timeout (default 3 s) that kills its group.

Comments only; no behaviour change.
2026-10-29 16:58:09 +05:30
kshitijk4poor
b4031c37c8 fix(verify): a verify run's app server dies with the Hermes process running it (orphans after kill -9: 3 -> 0)
`hermes verify`'s start phase launches the project's dev server (recipe.start, a shell string) in
its own session and polls readiness for up to 60 s. Killing the Hermes process mid-poll (SIGKILL,
OOM, a closed terminal) skipped the finally that killpg()s it, and the detached group (shell + server
+ its workers) kept running on the port forever.

_run_start_phase now starts it through process_identity.spawn_owned: still a group leader for the
existing group teardown, and the group goes to the owner-death supervisor. It is released once the
teardown has stopped it (a group that survived the teardown stays covered).

Measured on Linux, owner killed mid-readiness-poll, 6 s settle: origin/main 3 of 3 (sh +
two workers) survived; this commit 0 of 4 descendants. New kill -9 / live-owner case and an
own-then-release test; reverting spawn_owned to the main-era Popen turns the kill -9 case red.
2026-10-29 16:58:09 +05:30
kshitijk4poor
3d24fce471 fix(lsp): a language server's whole process tree dies with its Hermes owner (orphans_after_30s 1 -> 0)
Symptom: LSPClient starts every language server in its own session (start_new_session=True) so a
killpg aimed at the server can never reach Hermes. That also took the server's descendants out of
Hermes's kill domain. The server itself exits on stdin EOF when Hermes dies, but a descendant that
neither holds nor watches that pipe (a wrapper's background child, a SIGTERM-ignoring worker)
outlived a SIGKILLed / OOM-killed Hermes forever. The atexit hook and the idle reaper both live
inside the owner, so neither runs on that path.

Change: _spawn hands the server's process group to the per-process owner-death supervisor
(own_process_groups) and records it in the spawn ledger (register_child "lsp-server").
_cleanup_process hands the group back only once nothing in it is left, so a member that survived
teardown stays covered and still dies with Hermes. No new process: the supervisor is shared with
every other owned child. The atexit hook stays: it runs the LSP shutdown/exit handshake on a
clean exit, which the supervisor's TERM/KILL does not replace. Windows path unchanged.

Measured on Linux (Linux), kill -9 of a real owner running LSPClient, survivors of the server
tree after 30 s:
  mock server with a SIGTERM-ignoring child (slow_tree), 3 trials: main 1/2 alive every trial,
  branch 0/2 every trial (gone by +5 s).
  basedpyright, pylsp, typescript-language-server (4 procs), gopls, rust-analyzer: 0 on main and
  branch (they exit on stdin EOF, and their helpers die with them).

Tests (tests/agent/lsp/test_lsp_owned_server.py): owned on spawn + released on shutdown, a
surviving member keeps coverage, a real kill -9-the-owner end to end, and a live-owner control.
Removing the own_process_groups call turns 3 of them red; making the release unconditional turns
the coverage test red.
2026-10-29 16:58:09 +05:30
Teknium
183b5ddd5f chore(skills): move niche built-in skills to optional
These stop loading by default and become one
`hermes skills install official/<category>/<name>` away:
notion, airtable, box (hosted connectors cover them for Portal users),
opencode, design-md, gif-search, songsee, llm-wiki,
hermes-agent-skill-authoring, inspecting-hermes-desktop-dom,
node-inspect-debugger and python-debugpy.

Existing installs keep their copies: the skills sync already re-labels
a byte-identical copy of a moved built-in as an official optional
install. Onboarding first tasks drop the two skills that are no longer
bundled (llm-wiki, design-md), claude-design and popular-web-designs
point at design-md as an optional install, and doc examples use
skills that still ship.
2026-10-28 21:24:43 -07:00
Teknium
15df08e6c1 fix(auxiliary): a rate-limited auxiliary call backs off before its same-key retry
Review finding: an auxiliary Bedrock ThrottlingException skipped every backoff and reached a
single immediate retry in the credential rung, so a throttle lasting ~300ms failed the task once
botocore stopped retrying (2nd request ~5-18ms after the first; main waited ~400ms).

The credential rung's same-key retry for a rate limit (every provider: aux SDK clients make one
attempt) now waits first: the provider's Retry-After (including the header botocore keeps in
ResponseMetadata.HTTPHeaders) up to 5s, else a jittered 1-1.5s backoff; a longer declared
cooldown goes straight to rotation/fallback. The ladder yields a `wait` step that both the sync
and async ladder drivers sleep. The single-attempt botocore policy is unchanged.
2026-10-28 21:22:10 -07:00
Teknium
f891fbe737 fix(bedrock): auxiliary calls retry a Bedrock 503 and see throttles as rate limits
Greptile "Auxiliary calls lose retries": with botocore's retries off, the aux
recovery ladder only read HTTP status from exception attributes, so a botocore
ClientError (status in response["ResponseMetadata"], code in response["Error"])
skipped the same-provider retry on a 503 and missed rate-limit handling on a
ThrottlingException. _exc_http_status now reads botocore response metadata and
_is_rate_limit_error matches ThrottlingException, matching how the ladder already
owns retries for OpenAI-SDK clients (max_retries=0).

The status-shape helpers move to agent/auxiliary_error_shapes.py to keep the
auxiliary_client facade under its line cap.
2026-10-28 21:22:10 -07:00
Teknium
e286e63e0e fix(bedrock): a hung Bedrock call fails after one read timeout, not five
botocore's default retry policy (legacy mode, 5 total attempts) re-sent a
Converse/ConverseStream read timeout, so a hung call surfaced after ~5x the
configured request timeout (5x botocore's 60s default when unset), and
throttles were retried under Hermes's own adaptive rate-limit backoff.

The bedrock-runtime client now makes one attempt per call
(retries.total_max_attempts=1; botocore's max_attempts counts retries, not
attempts). Hermes's retry loop already classifies ReadTimeoutError as a
retryable timeout and ThrottlingException as rate_limit with backoff; the
AnthropicBedrock client already runs with max_retries=0.
2026-10-28 21:22:10 -07:00
Teknium
882482b58a fix(compression): the active-request bridge obeys the post-handoff progress floor
When the first post-handoff tool group ends right before the active user
request, the progress floor lands on that request, and _compress_window's
assistant/tool bridge then pulled the cut back onto the group's assistant:
the window held only the handoff and compress() no-oped with
empty_post_handoff_window. The bridge now moves the cut back only down to
tail_cut_progress_floor (one rule); when the floor sits on the active request
the summary merges into that row through the existing merge path.
2026-10-28 20:39:24 -07:00
Teknium
f6a84fd6d9 fix(compression): a tail cut inside the first post-handoff tool group still compacts
After a compaction the transcript opens with the handoff followed by a tool
group. When the raw tail budget broke inside that group, the cut was aligned
back onto the group's assistant, leaving a window that held only the handoff.
The handoff scan drops standalone handoff rows, so compress() returned the
empty_post_handoff_window no-op and the session stayed over the trigger with
no warning. Since #144824 priced pre-handoff rows at zero, the whole-transcript
re-cut takes this path routinely.

The progress floor now requires one row the scan keeps: when every row before
the cut is a handoff, the cut moves past the next tool group, unless that
would take the newest row or the active user request out of the tail.

Found on the C4 e2e suite: test_good_summarizer_compacts_and_keeps_every_invariant[11]
failed deterministically since 52a01bd2f2.
2026-10-28 20:39:24 -07:00
Victor Kyriazakos
a8b987aaa1 fix(bedrock): apply configured request timeouts to Bedrock clients
providers.bedrock.request_timeout_seconds and
providers.bedrock.models.<model>.timeout_seconds resolved correctly through
hermes_cli.timeouts.get_provider_request_timeout, but no Bedrock client was
built with the result. The cached boto3 bedrock-runtime client (ambient and
profile-scoped) was created with no botocore Config, so it kept botocore's
60s read / 60s connect, and the AnthropicBedrock SDK client was built with
_client_timeout(None), i.e. a fixed 900s read. The resolver (3143d32330)
landed after the cached Converse client (0cb8c51fa5) and was wired only into
the OpenAI-wire and native Anthropic builders; 611657487f documented Bedrock
as not covered instead of wiring it.

- _get_bedrock_runtime_client(region, model) resolves the model's timeout
  (model over provider) and passes Config(read_timeout=..., connect_timeout=60)
  only when one is configured; unset or invalid builds the exact
  no-Config client used before.
- Both client caches (ambient and per-profile-home) key on the effective read
  timeout, so models with different overrides in one region never share a
  client, and the same timeout reuses one client. Stale-connection eviction
  drops every timeout slot of the region.
- converse/converse_stream dispatch picks the client from the request's
  modelId, so a /model switch or a fallback to another Bedrock model uses
  that model's timeout. call_converse and the context probe pass their model.
- AnthropicBedrock: build_anthropic_bedrock_client takes the timeout; the
  bound client and the per-request client key carry the active model's
  value (connect stays 10s, unset stays 900s).
- Docs: replace "not currently wired for AWS Bedrock" with what is wired.

This closes a configuration gap only. A socket read timeout bounds each read,
not the whole call; retry policy and the stale detector are unchanged.
2026-10-28 19:51:15 -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
Victor Kyriazakos
47ec37e427 fix(sessions): a Bot Chat capability rebuild also satisfies a pending prompt refresh
The Bot Chat capability-refresh branch rebuilt and persisted the prompt
without recording the refresh epoch, so a pending `refresh-prompts`
request rebuilt the prompt a second time on the next turn, and a warm
agent restored through that branch never adopted a later request.

Read the requested epoch before that build and stamp it after the
persist, the same read-before-build contract as the first-build path.

Tests: a Bot Chat rebuild with a request pending is the only rebuild,
a warm agent rebuilt through Bot Chat adopts a later request, a warm
agent that restored its prompt from the row adopts a later request, and
a warm agent with no request never rebuilds across turns.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
e240d617e8 feat(sessions): refresh-prompts lets continuing sessions adopt updated prompt sources
A continuing session replays its stored system prompt verbatim on every turn
so the provider prefix cache stays warm. The gateway restores that prompt from
the session row on each fresh agent, and warm cached agents keep it in memory,
so SOUL.md edits, new or edited skills and project-context changes never
reach a long-running conversation until /new, which also drops the history.
Operators who push profile updates and restart the gateway had no way to make
existing conversations pick them up.

`hermes sessions refresh-prompts [--session ID] [--json]` records a refresh
epoch in the profile's state.db (state_meta, one counter orders profile-wide
and per-session requests). At the start of a continuing session's next turn,
_restore_or_build_system_prompt compares that epoch with the one stamped in
the session's model_config when its prompt was built. When the stored prompt
is older it follows the Bot Chat capability-refresh precedent in the same
function: tools[] pin restored first, skills prompt cache and snapshot
cleared, prompt rebuilt through _build_system_prompt (memory reloaded and
plugin sections re-rendered, as at a compaction boundary), cache break
recorded, on_session_start not fired, new bytes and epoch persisted so the
following turns restore them verbatim. One cache break per request.

Warm agents (gateway agent cache, TUI/Desktop) run the same check from
build_turn_context against the epoch they saw when their prompt was set, so
the verb works with the gateway running. A session first built after a
request is stamped with it and does not rebuild again.

With no request recorded, the stored prompt is reused byte-identically. The
only added work per continuing turn is one state_meta point read. No file
scanning, no config key, no watcher, no mid-turn mutation.

The tools[] pin is kept on purpose: the refresh is about instructions, and
tool changes already reach long sessions at the compaction boundary. The
cache break is recorded as the existing system_prompt_rebuild cause rather
than a new one, which would change the shared-metrics contract and schemas.

Related: #141154 (per-turn source hashing, alternative design), #74622.
2026-10-28 19:30:48 -07:00
Victor Kyriazakos
5cba2718c0 fix(agent): preserve completed replies before terminal silence
Reuse an eligible housekeeping reply before output transforms, persistence
and receipt generation when the local host requires a reply. Keep permitted
silence and marker-only warnings unchanged.

Reconcile recovered stream finals with their own delivered segment,
including transformed text and split previews. Treat short recovered
answers as successful replies and sanitize them before persistence.

Cover local gateway composition, output hooks, recovery, receipt identity,
stream transports and the unchanged silence controls.
2026-10-28 19:29:23 -07:00
Victor Kyriazakos
93286ffd87 fix(bedrock): an unresolved application-profile ARN issuer is unknown, not foreign
A Claude configured by application-profile ARN stamps its Converse turns with the ARN. Without
bedrock:GetInferenceProfile the ARN stays unresolved, names no model, and was treated as a non-Claude
issuer, so a switch to a plain Claude id dropped Claude's own signed thinking on both Bedrock wires.
2026-10-28 19:21:51 -07:00
Victor Kyriazakos
e34d84897a fix(bedrock): Claude never gets a GPT turn's sealed reasoning on the Anthropic Messages path
A Bedrock session that switches from a reasoning GPT (Converse) to Claude with /model, or falls back
from one to the other, failed every Claude turn with
`HTTP 400: messages.N.content.M: Invalid `data` in `redacted_thinking` block` and then failed over to
GPT ("Fallback activated: <claude> -> <gpt> (bedrock)"). The only workaround was /new.

#142139 filters reasoning by issuing model on the Converse path only: a turn stamped by a non-Claude
model (CONVERSE_ISSUER_TYPE) replays no reasoning to Claude there. Claude on Bedrock runs on the
AnthropicBedrock (anthropic_messages) path, whose converter copied every thinking/redacted_thinking
block out of reasoning_details, GPT's sealed blob included. The classifier did not help either: the
rejection names none of the signature words, so it landed as format_error (non-retryable, fallback)
and never reached the existing thinking_signature strip-and-retry.

Two layers:

- Root: assistant_replay_carrier's reasoning_details carrier (_extract_preserved_thinking_blocks) yields
  nothing for a turn a non-Claude Converse model stamped, on every route and inside the in-flight tool
  loop. The predicate is #142139's, shared as bedrock_adapter.reasoning_minted_outside_claude (Converse's
  _reasoning_filter now calls the same helper). Claude's own turns (unstamped on AnthropicBedrock, or
  stamped by a Claude model on Converse) replay as before. Unstamped turns keep replaying, as on
  Converse: Claude mints redacted_thinking itself and its AnthropicBedrock turns carry no stamp, so
  "unstamped" cannot mean "foreign".
- Safety net: a 400 naming an invalid `redacted_thinking` block classifies as thinking_signature, so
  turn_recovery's one-shot strip (remember_rejected_thinking on signed-replay routes) removes the blob,
  persists the suppression for the session and retries on Claude. This covers unstamped GPT turns from
  sessions older than the stamp. It runs after the OpenAI Responses thinking_signature_invalid rule, so
  that class and invalid_encrypted_content keep winning.

Refs #142139
2026-10-28 19:21:51 -07:00
Teknium
81985c6bd4 fix(vault): keep the fill's nonce-stamped selector; collect shadow roots once 2026-10-28 19:00:07 -07:00
Teknium
b79946d2ee fix(vault): shadow-root fills reach host listeners and shadow login tabs
The fill events now cross the shadow boundary (composed), so a component tracking its value on the
host sees the password; tab selection finds a form inside an open shadow root; the fill script
collects the stamped controls once instead of walking the page per field.
2026-10-28 19:00:07 -07:00
Teknium
5a4c234a9c fix(vault): shadow-root forms keep their form grouping and shadow-tree labels
document.forms misses a <form> inside a shadow root, so its controls had no formIndex and split OTP
boxes from two such forms counted as one group; aria-labelledby ids inside the shadow tree were not
resolved. Forms are collected in the same walk and labels resolve against the control's root first.
2026-10-28 19:00:07 -07:00
Teknium
0a93a2341f fix(vault): fill saved logins on Camofox pages through a browser page backend seam
browser_vault reached pages only through the task's CDP supervisor. Camofox (now a plugin) has no
CDP endpoint, so every fill on a Camofox tab ended with "Could not determine the current page
origin": the username from browser_vault list worked, the password never filled.

ctx.register_browser_page_backend lets a plugin browser carry the vault's origin read, form
inspection and fill script to its own page. Core keeps the secret contract: the exact-origin
pre-check and in-page re-check, the Bot Desktop takeover check, an in-page try/catch around the
secret script, and fixed failure text on that path. Registration follows the login-backend
provenance rule (bundled, or catalog verified/official at its pin) and is refused under
plugins.isolation: host.

Consolidates the core half of #127179 and #135204 (the Camofox halves already shipped in the
official plugin); the in-page wrapper follows #114414.

Co-authored-by: Jonathan Bruce <jonathan.bruce369@gmail.com>
Co-authored-by: clsferguson <cferguson@live.ca>
Co-authored-by: Benjamin PERRY <benjaminperry6@yahoo.fr>
2026-10-28 19:00:07 -07:00
clsferguson
63b82d209e fix(vault): find login fields inside open shadow roots
Login forms rendered inside a shadow root (Home Assistant, custom-element SPAs) were invisible to
document.querySelectorAll, so the vault found no password field. The inspection and fill scripts now
walk open shadow roots.

Salvaged from #135204.
2026-10-28 19:00:07 -07:00
Teknium
b3c2c35e91 fix(models-dev): an abandoned download keeps its slot until it ends
run_bounded_sync stops waiting at the deadline but cannot stop the
requests download, which runs until the server stops sending. A forced
refresh skips the 5-minute backoff, so repeated attempts on a trickling
link could stack transfers. The one live download (abandoned or not) now
holds a module lock; an attempt that finds it held fails fast through the
normal failure path instead of opening a second transfer.

The deadline test also drops its 0.2 s wall-clock bound (tests/AGENTS.md
asks for >= 2 s) and checks the request count instead.
2026-10-28 07:23:10 -07:00
Teknium
8469e34161 fix(model-metadata): cap every metadata probe's whole exchange too
The same per-op-only timeout sits on the shared model-metadata transport
(agent/model_metadata_http.py), and it is on the same request path: a new
session resolves its context window through fetch_model_metadata (the
OpenRouter catalog) and fetch_endpoint_model_metadata (a custom endpoint's
/models). With DNS for openrouter.ai stalled, the first session.create
blocked for the whole stall even after the models.dev cap.

stream() now sends and, for a 2xx, reads the body under
run_bounded_sync with a 15 s cap. A rejection still returns on its
headers without reading the body, so the auth-failure early close keeps
working; get() rides on stream(). On expiry it raises DeadlineExpired,
which every caller already treats as a failed probe.
2026-10-28 07:23:10 -07:00
Teknium
4df354dba8 fix(models-dev): cap the whole registry download, not just each read
fetch_models_dev downloads models.dev/api.json with timeout=(5, 10). That
bounds each socket operation, so a body that trickles in slower than 10 s
per read (or a DNS lookup that hangs) has no total bound. With no disk
cache, the fetch runs in the foreground of whatever asked for the registry;
in a fresh HERMES_HOME that is the first session.create (tool availability
-> vision check -> provider lookup), which blocked for as long as the
download took.

Run the exchange under agent.deadline.run_bounded_sync with a 15 s cap.
On expiry the fetch raises DeadlineExpired, which the existing failure path
already handles: arm the 5-minute backoff and serve the stale disk cache,
or {} when there is none.
2026-10-28 07:23:10 -07:00
kshitijk4poor
c91bd232c0 fix(kanban): drop the worker.adopt handshake retry from the lost-worker salvage
The salvaged commit raised the managed worker's owner-link open timeout from 5 s to 60 s
(with a HERMES_WORKER_RPC_OPEN_TIMEOUT override) and retried a timed-out handshake three
times. Those retries cannot succeed against a real owner: WorkerRPC._connection mints ONE
worker-adoption ticket and every attempt resent it, while the gateway's bootstrap tickets
are single-use and expire after 30 s (gateway/runtime_bootstrap.py TTL_SECONDS, redeem()
deletes the entry). An attempt past 30 s, or any retry, is refused, and the same path
serves every idle redial during a turn, so a failing redial now took about 3 minutes
instead of 5 s while holding WorkerRPC.lock. The env knob also went against the
repo's no-new-HERMES_*-config rule.

The lost-worker disposition (worker_lost event, settled-admission reclaim) does not depend
on the handshake budget: a worker that dies in worker.adopt is now booked within one tick
either way. Sizing the handshake needs a fresh ticket per attempt and a budget within the
ticket TTL, which is its own change.
2026-10-28 17:06:43 +05:30
SanLuis-AI-Solutions
2432f9c29a fix(kanban): dispose of a lost managed worker within one tick
A managed worker that dies in the worker.adopt handshake writes no
worker_bound/worker_result: the gateway logged "Managed worker lost" and
returned, nothing failed the run, and the card said "running" for 49
minutes on a corpse (2026-10-22, t_f5fad63f, run 730: claim_expires 2067 s
past, last_heartbeat_at NULL, consecutive_failures 0).

D1 detection without disposition: gateway/session_kanban.record_worker_loss
writes a run-scoped worker_lost event on the board (dropped when the card
moved past that run) and session_managed_worker calls it on every loss
except a deliberate stop / stale generation.

D2 an elapsed claim lock read as "still running":
- owner_attempt_provably_over treats a SETTLED owner admission as proof the
  attempt ended, instead of demanding the owner PROCESS be gone (the owner
  is the live gateway, alive by design) - the reason every reclaim path
  declined for 49 minutes;
- the reclaim's kill step reads a bare OSError on an absent pid as Windows
  does (WinError 87), so "already gone" no longer means "termination not
  proven";
- reclaims/reaps name the loss in the run error via owner_attempt_note;
- a loss charges consecutive_failures like any other crash (A3), so the
  failure_limit breaker covers this class.

D3 adopt handshake budget: 60 s default, HERMES_WORKER_RPC_OPEN_TIMEOUT
override, and a TimeoutError is retried with backoff (auth/protocol errors
never are).

Tests: tests/hermes_cli/test_kanban_managed_worker_loss.py (A1-A3, D1
write side, kill-step semantics) and tests/agent/test_worker_rpc_adopt_timeout.py
(A4). 16 passed under the production interpreter.
2026-10-28 17:06:43 +05:30
Teknium
f09d03dfe2 fix(cache): signatures stored and compared later always hash
Review of #145651, item 3: the hook-consent signature, free-tier inventory stamp, onboarding due
stamp and skills manifest are kept and compared on a later tick or by the next process, so they use
always_digest=True like the PR's other stored signatures; a racy digest turning empty no longer
costs one recompute after a fresh write settles.
2026-10-27 12:57:09 -07:00
Teknium
76f2fdb794 fix(cache): a rotated key, token or same-size edit is never served stale from a file cache
Every cache keyed on a file's stat signature had the bug the config caches had: a same-size
in-place rewrite in one coarse timestamp tick keeps mtime, ctime, size and inode, so the older
parse was served for the rest of the process. Move the helper to utils.file_cache_version
(file_signature + content digest while the file is under 2 s old; always_digest for signatures
compared much later, where the racy digest going empty would read as a change) and key every
cache that can hold a secret, token, pairing/allowlist, route or config on it:

- auth.py: global auth-store memo, Nous auth-status memo (was mtime only)
- gateway/pairing.py approved-users cache (a revocation kept access)
- run_profile_reconcile: served-profile signature (always_digest: a false change reconnects
  adapters) and the hook-consent signature
- webhook dynamic routes (route HMAC secrets), Feishu comment pairing/rules cache (mtime only)
- MCP OAuth tokens-file reload check (mtime only; always_digest: a reload tears the session down)
- config parse-failure record (always_digest), named-custom-provider memo, model aliases,
  gateway.standalone memo, profile model read, MoA preset, agent raw config,
  tui_gateway raw config cache, onboarding due stamp, free-tier inventory stamp,
  provider model-list credential fingerprint, git safe.directory key, skills prompt
  manifest

config_cache_version takes its stat through config_version, so its errors and seams are unchanged.
Left alone: the tool-definition cache key and the platform manifest stamp (a safe worker must
never open config.yaml or a plugin file; the MoA preset cache is skipped in one instead) and the
CLI MCP watcher seed (pinned to file_signature by a main test).
2026-10-27 12:57:09 -07:00
Teknium
f29772123f test: pin the stopped mark on the interrupt close and the authority turn's reply stamps
Direct tests for close_interrupted_tool_sequence(stopped=...) and
TurnRunner._stamp_segment through _publish_execution (red on main). The
stopped docstring now says every interrupt gets the mark, as main already
marks interrupted partial replies.
2026-10-27 11:50:16 -07:00
Teknium
674f2d680d fix(desktop): a turn stopped during its tool run keeps its stopped mark once stored
A Stop during a tool run leaves no reply: the finalizer closes the tool tail with
the empty hidden placeholder row and wrote no stopped mark anywhere, so once the
stored copy replaced the live one (the refresh after the stop in a short chat, a
later turn's refresh in a long one, every reload) "Response stopped" was gone.

The user-stop callers of close_interrupted_tool_sequence (the finalizer's
interrupted close and abort_turn_on_interrupt) now record interrupted on the
closing row, as turn_api_call.py does on a partial reply; truncation/overflow
closes stay unmarked. Hydration lends that empty row's mark to the bubble it
closes, the same rule as a reply folded into its tool bubble.
2026-10-27 11:50:16 -07:00
Teknium
2d8d7e2519 chore(state): name the weak claim at both rewind sites; hoist the per-message import; replay through substitute_api_content
Review round (kshitijk4poor) on #144938 (reviewed at b0fad87a; B1-B4 fixed by 7df4b2df):
- The comment at both rewind sites said "a row claimed by identity alone". Since 7df4b2df no
  claim is by identity alone: a weak claim is a rewritten carry naming the row (_row_id, else
  uid). The comment now says that.
- resolve_and_repair_transcript_batch imported _PERSIST_AFTER_ADMISSION_INTERRUPT inside the
  per-message loop. It is now imported once per call, still late because
  agent.session_persistence imports this module at load time.
- The replay helper in test_compaction_carried_tail_not_cloned.py now builds each provider
  message through the turn's own substitute_api_content, so the B1-B3 assertions check the
  bytes the next request sends instead of re-implementing the sidecar rule.
2026-10-27 11:49:40 -07:00
Teknium
3745ea63bb fix(state): a dedupe claim needs the occurrence, its version and its replay bytes
Review round 5 (unsupportedpastels) on #144938, three findings:

- Compaction claims no longer accept matching text: the identity+timestamp and
  bare-identity claims are gone. Only a dict naming the row (_row_id, else
  message_uid) may stand for a tail row, so an identical message another
  surface appended after the watermark keeps its model-visible row (as main).
- A rewritten-carry (containment) claim needs the stored-row digest to equal
  the row's current version; a _row_id without a digest no longer proves it,
  so a row shortened in place after a row-addressed load keeps its new text.
  (A loader-stamped version witness would add an underscore key to
  row-addressed projections, which test_message_reactions pins to _row_id and
  _db_persisted; such carries are cloned as on main instead.)
- Both claim passes and the flush re-insert guard now compare what the next
  request replays: the guard compares _REPLAY_COLUMNS (owned columns +
  api_content + codex_reasoning_items) instead of the CAS ownership columns,
  and claims check api_content and the reasoning carriers through the
  writer's serializer. A newer sidecar or encrypted reasoning item is stored
  / kept instead of being dropped as "the same message".
2026-10-27 11:49:40 -07:00
Teknium
33db60eefe fix(state): the re-insert guard compares through the restore lens; a rewritten carry keeps its uid claim
The durable-uid guard compared a restored dict with the RAW stored row, but restore sanitizes and strips
user/assistant text (context blocks, edge whitespace), drops the compaction-summary flag by default, and a
wire strip loses the underscore identity maps. Those restored copies never matched, so they were
inserted again: the #134799 duplicate survived for ~2% of user rows, summary rows, and every tool-call
assistant row behind a full underscore strip.

_same_as_stored now views the stored content through SessionMessagesMixin._loaded_view_content (the
function restore uses) and takes the row's value for token_count, the summary flag, tool_call_uids and
absorbed_message_uids when the dict carries none. The dict's own content is never normalized, and
content/tool_calls/reasoning are still compared, so an edited restored dict still inserts.

A compaction uid claim with different content (the compressor merged the summary into a carried message or
stripped its images) now claims the tail row when no active row outside the tail carries that uid. It is a
weak claim: the original is archived as compacted history and stays visible. When the dict's original sits
below the watermark, the tail row is another version and is still cloned (B3 unchanged).
2026-10-27 11:49:40 -07:00
Teknium
a995b69417 fix(state,codex): a dedupe claim never drops a different message; a cut codex stream retries
Review H on #144938:

- Codex: the narration recovery for an announced answer item now needs a terminal frame. A stream that
  ends mid-turn (answer announced, partial text, a call announced, no terminal frame) raises "did not
  emit a terminal response" and retries, as on main, instead of completing on the cut-off sentence with
  the call lost. Text deltas follow the phase of the item they name, so commentary that arrives after a
  call announcement is no longer fused into the recovered answer.
- Compaction carry: a dict that names its row by _row_id claims only that row; a message_uid claim needs
  the same identity (a same-uid row with newer content is kept and cloned); an identity+timestamp claim
  is refused when the dict's uid differs from the row's. Rows claimed by identity alone are archived as
  compacted history instead of rewound, so a wrong claim stays visible in display.
- Flush guard: a restored dict whose uid is ACTIVE is skipped only when it serializes to that row's owned
  columns; an edit since the restore inserts, as on main.
2026-10-27 11:49:40 -07:00
Teknium
4186899a6f fix(sessions): skip a re-handed uid only when the agent saw it durable
The salvaged #134799 guard skipped any no-snapshot, no-row-id dict whose
message_uid was ACTIVE, so SessionDB.append_messages_batch dropped a fresh
message carrying a copied uid — the exact case main's contract
test_fresh_identical_message_is_never_adopted_by_payload pins ("even a copied
message_uid is not proof").

Narrow the trigger to provenance: the agent flush records the uids it itself
saw durable in its current session (rows it flushed, history it scanned as
already persisted) and marks a later marker-stripped copy of one of them
RESTORED_FROM_STORE on its batch row. The write transaction skips only those
marked rows whose uid is still ACTIVE. A direct append with a bare copied uid
inserts as on main.
2026-10-27 11:49:40 -07:00
Teknium
7d1c2dc612 fix(codex): recover answer text only from an announced answer message item
The narration fix synthesized a message from any buffered output_text deltas
whenever no answer message item completed. That also promoted bare
output_text beside a commentary item, which main's completion contract
(test_auxiliary_codex_completion_status
[tool-call-like-output-text-beside-commentary]) keeps as narration with
finish_reason=length. Beside calls/commentary, synthesize only when an
assistant answer message (not commentary/analysis) was announced via
output_item.added and its done event never arrived; the no-output plain-text
synthesis is unchanged.
2026-10-27 11:49:40 -07:00
Teknium
5f799922c1 refactor(sessions): let a failed durable-uid probe fail the write it runs in
The probe is one SELECT on the write transaction's own connection. A blind catch that logs and
skips the guard would hide a broken transaction and silently restore the duplicate insert; an error
there now fails the flush like any other statement in it (code-health BLE001). Builtin generics
for the new helper's annotations (ruff UP006).
2026-10-27 11:49:40 -07:00
Teknium
e4347f96b1 fix(codex): keep answer text sent beside a tool call when its message item never completes
_CodexResponseAssembler.result() synthesized a message from buffered output_text deltas only when the
stream carried no tool call. A backend that announces a call, streams narration in a message item and
never sends that item's done event (the relay shapes in #143893) lost the narration whenever a
commentary item was also present, because the normalizer's output_text fallback is skipped once a
commentary phase is seen. The turn then stored an empty assistant row and showed no bubble.

result() now synthesizes the message whenever no answer-phase message item exists, tool calls or
not, and places it before the first call. Commentary and analysis deltas never enter text_deltas, so
they are unaffected.

Live (real tui_gateway.entry + scripted codex_responses stub): base stores '' for the narration
turn and the resumed transcript lacks it; head stores and paints it.
2026-10-27 11:49:40 -07:00
Sharpe
42abc9e2ed fix(sessions): durable-uid dedupe joins the repair transaction — a live rewrite is never dropped
Review (PRATHAMESH75, 134799): the flush-side guard stamped-and-skipped
restored dicts BEFORE resolve_and_repair_transcript_batch could see them,
so a snapshot-carrying dict's live edit never reached its row — reproduced
live (restored[-1]['content']='new answer' -> final active rows read
['q', 'old answer'], the edit silently lost). It also probed the durable
uid set OUTSIDE the write transaction (a concurrent writer could flip the
active set between read and INSERT) and built candidate_uids from the
WHOLE transcript (O(N) per flush, past SQLite's bound-variable limit the
probe throws and the guard fails open silently.

Move the no-snapshot uid dedupe into resolve_and_repair_transcript_batch
(the reviewer's sturdier option, which closes all three):
- _active_uid_dedupe runs inside the caller's BEGIN IMMEDIATE — the same
  transactional guarantee the CAS repair already relies on, no TOCTOU.
- Candidates exclude dicts that still carry DB_ROW_SNAPSHOT or _row_id:
  the CAS path rewrites their active row in place; a live edit must land.
- Candidates are chunked via hermes_state_common._id_chunks (the repair
  code's own pattern), so no bound-variable limit and no whole-transcript
  cost per flush.
- Fail-open stays: a probe error logs and returns an empty set.

The flush-side pre-guard in _db_flush_collect comes out (the marker,
history-identity and scaffolding guards remain untouched there).

Regression: test_restored_snapshot_rewrite_still_lands pins the reviewer's
exact repro — red on this PR's parent head (edit lost), green with the fix.

Validation (this commit): new suite 4/4; red/green confirmed by file-scoped
revert of the two source files (1 failed -> 4 passed); repair-path battery
(test_append_messages_batch, test_restore_alternation_repair,
test_repaired_history_commit_coverage, test_compression_watermark_commit)
35/35; scratch battery (test_scratch_dir, test_scratch_scan_failures)
22 passed + 2 platform skips; -k 'flush or persist or transcript' A/B vs
PR head: fixed 30 failed / 401 passed, baseline 31 failed / 400 passed —
fixed failures a strict subset of baseline (all pre-existing environmental
failures: tests spawning PATH-resolved hermes trip the real-home IO guard);
the single delta is the new regression test, red on base, green here.

Co-Authored-By: Viiy <viiy@mediaplural>
EOF
)
2026-10-27 11:49:40 -07:00
Sharpe
fc6d7edc75 fix(sessions): durable-uid flush guard — restored rows must not be re-inserted
Production receipts (estate state.db, 2026-10-07): 24k+ re-inserted shadow
rows across 47 sessions (Oct 1-7), each preserving the original message_uid
while landing at a later timestamp with display metadata lost. Signature
reproduced end-to-end in test_flush_uid_reinsert_guard.py: a dict rebuilt
from durable rows (crash/failed-turn history restore, resume, repaired
sequence, wire-crossing handoff) carries its durable message_uid but NOT
the _DB_PERSISTED_MARKER (underscore-prefixed, stripped before the wire)
nor _row_id — the flush's identity guards can't see it and INSERT a second
copy of an already-active logical message.

Fix (fail-open, append-only): SessionDB.active_message_uid_exists() probes
the durable uid set in one statement; _db_flush_collect consults it once
per flush and stamps durable candidates _DB_PERSISTED_MARKER + skip.

Validation: new suite 3/3 PASS; red-run confirmed on stashed patch (fails
with the exact defect); A/B mass run (-k flush/persist/transcript/session,
9519 deselected): baseline 30 failed/683 passed vs patched 27/685 — patch
fixes 2, breaks 0; all 30 fail-then-pass-in-isolation (shared-machine
test-ordering pollution, pre-existing).

Co-Authored-By: Viiy <viiy@mediaplural>
2026-10-27 11:49:40 -07:00
Teknium
41e5a82e60 test(agent): keep two invariant tests for the reasoning relay, drop the defensive try
The salvaged relay fix shipped nine tests; keep the two that pin the
invariant (a plain reply is never relayed as reasoning, inline thinking is
relayed without the reply text). Both fail on origin/main. The extractor
call needs no try/except: agent._extract_reasoning does not raise.
2026-10-27 11:49:40 -07:00
webtecnica
4c08c0d407 fix(agent): stop _relay_thinking re-emitting plain reply text as reasoning.available (132477) 2026-10-27 11:49:40 -07:00
kshitijk4poor
fa59cb998a test(deadline): pin review cases for poll_until callers and the sweep
From review: document that poll_until bounds only its sleeps, not time
spent in the predicate; pin that unlink_files_older_than keeps sweeping
after one unlink raises PermissionError; pin that
_wait_for_user_dbus_socket exports the systemd env exactly once when
the socket appears only on the final check, made at the deadline after
a cut last sleep. Both new tests fail against a mutated implementation
(the per-file suppress removed; main's loop shape).
2026-10-27 16:30:14 +05:30
kshitijk4poor
de5f56c92a refactor(deadline): one poll_until for check-until-deadline loops
Twenty loops across 17 files hand-wrote the same thing:

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if condition(): return ...
        time.sleep(interval)

with small drifts between copies: some re-checked once after the loop,
some did not, one slept before its first check, and update_cmd_windows
kept a private _poll_until. A copy without the final check can miss a
condition that becomes true during the last sleep.

agent/deadline.py (already the home of clamp_timeout / run_bounded_*)
gains poll_until(predicate, timeout, interval): checks at once, cuts the
last sleep to the time left, checks again at the deadline, and returns
the predicate's last value so callers that wait for a pid / row /
identity get it back directly. timeout <= 0 is one check.

Converted: outbound_webhooks.flush, cron delivery wait and jobs flock,
host_attach channel wait, browser profile unlock, data-cleanup drain,
gateway dbus/bus waits, launchd fresh-pid and supervision waits,
supervised restart, gateway_migrate live-gateway wait, Windows
drain/absent waits, kanban init lock, local-runtime boot wait,
update_cmd_windows (private helper deleted), bot desktop start/stop
waits, TUI browser connect.

Left as is: loops whose body does more than check (progress callbacks,
interrupt handling, two distinct exits) and one site whose blind except
the health gate would reject once moved.

Behaviour changes, all small:
- loops that stopped at the deadline without re-checking now make one
  more check there;
- loops that already re-checked after a full last sleep now cut that
  sleep to the time left, so the check lands at the deadline (up to one
  interval sooner);
- a timeout <= 0 now means one check (some loops made none);
- the local-runtime boot wait checks before its first sleep instead of
  after it;
- _wait_for_user_dbus_socket also exports the user systemd env when the
  socket appears on that final check (before, that path returned True
  without it).

update_cmd_windows is imported by update_cmd on every OS, so the
fresh-source-install acceptance fixture (which keeps agent/ out of the
update path) now copies the stdlib-only agent/deadline.py too.

Tests: 4 pins for poll_until (two red against the classic
no-final-check variant), plus the existing suites for every touched
module.
2026-10-27 16:30:14 +05:30
Teknium
a382af23f4 feat(models): list gpt-6.1-terra on OpenRouter and Nous Portal
openai/gpt-6.1-terra is served by both OpenRouter's and the Nous Portal's
/v1/models (1.05M context). Adds it to the curated OpenRouter list (the
Nous list derives from it), a 1.05M offline context fallback, and
regenerates the published model-catalog manifest. No older Terra slug was
on either list, so nothing is removed.
2026-10-26 19:05:08 -07:00
Teknium
fbb1b417e2 fix(providers): one guarded api_mode_for_model for resolution, /model and resume
Runtime resolution caught a raising api_mode_for_model hook and kept the
profile's declared api_mode, but /model (model_derived_api_mode, also the
resume re-derivation in the TUI, CLI and gateway), the stale
codex_responses check in resolution, the agent's Responses routing check
and the auxiliary client asked the same hook unguarded: a model could
resolve and then fail building the switch result.

agent.provider_route_hooks.model_api_mode is now the one call: a raise
answers the profile's declared api_mode, logged with its traceback once per
provider. A None answer keeps each caller's existing meaning.
2026-10-26 01:34:59 -07:00
Teknium
51e731f57a fix(agent): a failing credential-refresh hook falls back instead of escaping
refresh_runtime_credentials, is_stale_credential_error and
credential_refresh_notice run inside the API-error handler, outside the
retry loop's try. A raise there (a plugin bug, or a plugin host that
disconnected or timed out) escaped the handler before the fallback walk.

ask_on_error_path is that boundary: a raise answers "not refreshed" (or no
stale verdict / no notice), logged with its traceback once per provider and
hook, and the hook is asked again on the next error since a lost host may
be back. A malformed refresh answer is "not refreshed" too. The original
API error then walks the fallback chain. Same policy as the
missing_credentials_suffix boundary.
2026-10-26 01:30:54 -07:00
Teknium
1c4cbb2222 Merge remote-tracking branch 'origin/main' into copilot-seams/integration 2026-10-26 00:40:32 -07:00