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.
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.
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.
With compression.in_place: false a rotation creates a child whose
model_config did not carry prompt_refresh_epoch, so after any past
profile-wide refresh-prompts request the child looked stale and rebuilt its
prompt (an extra prefix-cache break) on the first restore after eviction or
restart. Carry the key as conversation-wide state.
--session with a compressed conversation's original id wrote the request
for the ended root, which the live tip never reads: the CLI reported
success and nothing refreshed. Resolve to the compression tip first.
Main now keys the skills index manifest on utils.file_cache_version (stat
signature + content digest), so prompt_builder no longer imports
file_signature and the rebased probe raised AttributeError. Freeze the new
key instead; the test still fails when the refresh keeps the cached render.
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.
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.
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.
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.
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
test_inventory.py::test_include_unconfigured_appends_canonical_skeletons
passes alone and fails when it runs in one process after
test_models_dev_provider_capabilities.py (with any earlier file that
already ran provider discovery, e.g. test_model_metadata.py):
AssertionError: assert 'solstice' not in {...}
_isolated_registry() swaps providers._REGISTRY for {} but leaves
providers._PROVIDER_LIST_CACHE alone. register_provider() clears the cache,
the next list_providers() refills it from the fixture registry, and the
monkeypatch undo restores _REGISTRY but not the cache. Every later
list_providers() then returns only the fixture profile, so
unlisted_provider_names() never sees the hidden pre-release "solstice"
profile and the picker lists it.
The same fixture also left its fixture-provider/fixture-relay rows in
hermes_cli.models.CANONICAL_PROVIDERS: a post-discovery registration
mirrors into the picker catalog, and a string setattr on
"hermes_cli.models..." imports that module inside the patch window, so
the undo "restores" the patched copy.
Fix at the polluter: patch _PROVIDER_LIST_CACHE and _SOURCES alongside
_REGISTRY, and scope the catalog tables (both modules imported before any
patch). test_account_usage_fetch.py's _register_profile had the same
missing list-cache patch.
Repro (test venv python, -p no:randomly, one process; run_tests.sh runs
each file in its own process and cannot hold the order):
test_model_metadata.py test_models_dev_provider_capabilities.py <victim>
main: 1 failed, 120 passed fix: 121 passed
48 models_dev/model_metadata_http files + victim
main: 1 failed, 774 passed fix: 775 passed
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.
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.
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.
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.
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.
- env_loader: secret sources apply into a private staging copy of the
environment; the D32 protected-name check runs before anything is
published to os.environ, so a refused plane URL/credential is never
visible to a concurrent request (the poller reads them live).
- remote backend: the doc's schema version and generation are captured
together under st.lock; a migration whose doc was replaced before it
starts (or at any step/commit) never touches the replacement.
- remote backend: plane value refusals (config_value_invalid,
config_path_invalid/reserved, config_secret_literal, 413 too_large)
become ConfigValueError; the dashboard maps them to 400/413 with the
plane's message; config_request_invalid and others stay opaque.
- stub plane enforces the contract §11.1 depth limit; bulk-save test
asserts the exact PATCH.
The token-read barrier test now allows 2 s (tests/AGENTS.md floor; the old
behaviour still takes ~10 s, so it still catches the regression). The shutdown
comment no longer says API-server runs use the loop default executor; they run
on their own bounded executor since the API-server loop work in this PR.
SessionDB.get_session / list_sessions_rich / get_recent_session_model_route /
list_gateway_sessions drained the async token queue first and waited up to
5 s for the background writer. Gateway handlers make these reads on the event
loop, and the writer can sit behind another connection's write lock, so one
read froze every socket on the gateway (#141966). Measured on a real
multiplex gateway under load: 36 stall samples (~0.7 s) in one 90 s run were
get_session waiting in flush_token_counts.
Reads now use flush_for_read(): on a thread running an asyncio loop it drains
nothing it would have to wait for and reads the committed totals (stale by
the queued deltas, which the next read sees). Off the loop it still waits,
and write barriers (model switch, meta update) keep calling
flush_token_counts and still wait.
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.
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".
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).
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.
_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.
#134799: keep the restore-then-flush reproduction (red on main: 2 -> 4 rows) and the CAS rewrite
guard (a snapshot-carrying restored dict still rewrites its row). #137577: keep the held row above
the watermark (red on main: 3 copies, two active) and the foreign identical row that must still be
cloned. Both reds run through the production writers (AIAgent._flush_messages_to_session_db and
SessionDB.archive_and_compact on a real state.db), not mocks.
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
)
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>
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.
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.
The two broken-pipe tests polled for the fixture CLI closing its stdin with
non-zero time.sleep loops, which tests/AGENTS.md forbids; a missed deadline
now fails with a named timeout instead of continuing silently.
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.
Every field this branch added to ProviderProfile followed main's positional
layout as a positional field, so a dataclass plugin subclass passing its own
option after the released arguments assigned it to account_card instead.
A KW_ONLY sentinel after model_capabilities (main's last field) keeps every
released slot and the subclass's own options where they were.
The compat test now freezes the released positional layout as a literal
instead of deriving it from the new class, which could not catch the shift.
Kanban workers no longer run `chat -q`: the spawned process is
hermes_cli.kanban_worker_client, which submits kanban.run to the profile's
owner gateway, and the owner runs the attempt in _run_task_turns. Those
three run_conversation calls (first turn, in-place recovery, goal turns)
passed no turn_author, so memory providers still filed the dispatcher's
prompt and the worker's notes under the operator (#137406). They now pass
a fixed bot author. Its id is kanban:dispatcher rather than bot:kanban,
which a Bot Mode profile named kanban would also produce.
A failed per-request profile hook stays on the generic answer for the agent's session so request
bytes never flip, but the failure memory survived /new and /resume (reset_session_state reuses the
agent), and the warning was logged once per process, so in a multiplex process every later home's
agent degraded silently. The memory is now cleared at a session boundary and a scoped (agent)
failure is logged once per session; scopeless one-shot callers keep the once-per-process warning.
129f205a0e made a broken pipe on a request write wait up to 5 s for the CLI to exit, so its exit
text is reported. A CLI that closes stdin but stays alive then fell through to the reply loop and
hung for the whole request timeout (900 s default) before a TimeoutError; main failed at once.
After the wait, a still-running CLI now re-raises the broken pipe. Windows reports a write to a
closed pipe as EINVAL rather than EPIPE; both take the same path.
Every AIAgent's _load_tools ran recover_at_startup(say=agent._emit_startup_warning), which claimed the
home's kept notices. Cron runs, subagents, the curator, kanban workers and background-review forks have
no notice_callback, so the notices were parked on an agent nobody watches and dropped; a cron tick
after a gateway start usually beat the user's next message.
Agent init now only runs the migration and keeps its outcomes in the home. The turn start
(deliver_kept_startup_notices) claims them when the turn has a real sink: the CLI's print sink, or a
driver's notice_callback (gateway chat, Desktop/TUI), and not for an unattended turn
(side_question_lease.is_unattended_turn: fork, cron, delegated child) or suppress_status_output.
The restart-the-gateway hint was gated on having a sink; it is now gated on not being the gateway's
own start (recover_at_startup(gateway_start=True)), so an agent-start install still carries it.
53a51a49cc made every attempt of a user turn's first API call (429/5xx retries, fallback
activations) re-send the provider's user_initiated request headers. Hermes has always sent them
on the first attempt only (retries went out with the route's default), and that difference is
billing-visible (premium-request initiator headers), so it is reverted: the first payload built
in a user turn consumes the flag and is the only user-initiated one.
Kept from 53a51a49cc: the flag is consumed exactly once whatever the route answers, so a route
without attribution or a failing request_headers hook never leaves it set for a tool-loop
follow-up.
Under plugins.isolation: host, profile_call encodes kwargs without callable refs, so the
is_suppressed / explicitly_configured lambdas arrived in the host as non-callable Opaque values
and a hosted provider seeded nothing (while _profile_seeds_pool still disabled generic env
seeding). The seam now passes data: suppressed_sources (frozenset) and explicitly_configured
(bool), computed only for profiles that override the seam.
Shell-exported GH_TOKEN-style names are always stripped from child envs, so a hosted provider
that declares them (env_vars + ambient_credentials) never saw a shell-only token. The plugin host
env now re-adds exactly those names through get_secret under the host home's scope: the launch
home keeps its shell value, a routed home gets only its own .env value, never the launch one.
With compression.prepare_ahead, compress() re-planned the tail cut and threw the
completed background summary away whenever the fresh cut landed before the
summary's boundary (the no-LLM prune made tail rows cheaper, tool-group
alignment moved the cut), then wrote a second summary inline while the user
waited. That breaks the one-summary rule: once the background summary exists it
is used, and everything after its boundary is the tail.
The splice check no longer consults the fresh cut at all. A summary is still
discarded only when the messages it covers changed (rewind, shape change, other
session, moved head). The pass planned its own window with a full tail, so the
tail is never empty. The now-unreachable inside_tail reason leaves the
(unreleased) prepared-compaction metric contract.
The union run flaked test_alias_keeps_the_former_gh_extension_diagnosis: a CLI that dies at once
(the old `gh copilot` extension) can close its stdin before ACPClient writes `initialize`, and the
write raised a bare BrokenPipeError, skipping the early-exit path that reports the CLI's stderr
(and the alias's gh-extension diagnosis). Pre-existing on main's CopilotACPClient. A broken pipe on
a request write now waits briefly for the exit and falls into that path. Test drives the race
deterministically (the fake CLI closes stdin before the client's first write).
Greptile on 815681917c3:
- a boundary landing after the pass published (and cleared its pending token) but before the
waiting compaction read the summary still read as a failed pass; take() now notices a discard
that happened during its wait and leaves the boundary's row as the only one;
- compaction_failed was lost when a pre-commit cancel restored the compressor's attempt telemetry
(and its prepared_summary flag) before the record was emitted; the spliced attempt id now lives
on the prepared-compaction state, outside the restored snapshot;
- the deadline-extension test starts its 2 s deadline only once the pass is running.
The live matrix on real processes found two ways a prepared-compaction pass was paid for and never
usable:
- `hermes chat -q` / `-z` runs end with their turn (the gateway evicts the agent right after the
reply), so a turn-end pass there was always cancelled ~0.5 s later. One-shot sessions now join
cron runs and delegated children in skipping turn-end passes.
- Releasing an agent without a session boundary (gateway cache eviction, a Desktop rewind,
managed-worker retire, close()) left a running pass billed to completion. release_clients() and
close() now discard it (shared-metrics reason `agent_released`).
Pass log lines now carry the session id, so concurrent sessions in one gateway are attributable.
Review follow-up (Greptile on 41ac847b3ee): caller-supplied conversation_history
that is never persisted carries no message_uid, so the structure-only check
accepted a dropped user/assistant pair once the transcript regrew to the same
shape, and the old summary replaced messages it never summarized.
Each message identity now also carries a text digest. A message whose uid is
present on both sides is still matched by uid alone, so plugin text rewrites
of persisted messages keep the summary; a message without a uid on one side
is matched by text.
Maintainer ruling on the prepared-compaction design, plus the review findings
(ours and Greptile's) on #144684:
- One pass per compaction. The extension passes (a new summary call every ~8k
tokens of growth) and the "stale after one tail budget" check are gone: the
summary splices at its own boundary and every message after it, however
many, stays verbatim in the tail. No second summary is ever paid for.
- The splice check compares message structure, not text: role, tool call
ids/names, tool result ids, plus the durable message_uid where both sides
carry one. Plugins that rewrite text in place (redaction, pre-compaction
notes) no longer throw the summary away; a dropped/inserted message or a
rewind into the window (new message_uids) still misses. This also settles
the fingerprint gap on input_text/output_text parts: text is not compared.
- A pass that recovered on the main model after the summary model failed now
hands that over on a splice, as an inline call would: summary_model goes
sticky to the main model, and the "configured compression model failed"
warning reaches the user. The attempt telemetry carries the pass's aux call
(model, tokens, duration, fallback) and a new prepared_summary flag.
- The first compaction that needs memory-provider context stops further
passes for the agent; each would have been discarded and paid twice.
- Turn-end passes are skipped for cron runs and delegated children, whose
sessions end with the turn.
Round-two review of the cancel and fast-path commits:
- A cancelled pass's stream raises AuxiliaryExplicitCancellation, a
BaseException that _generate_summary and _run_pass did not catch, so
every superseded pass printed "Exception in thread compaction-prepare"
to stderr (seen in the live probe). _run_pass now catches it and logs
the cancel.
- take() snapshotted the candidate at its start; a pass that published
while compaction was checking that snapshot survived the compaction.
It never spliced (its fingerprint no longer matched), but the
prompt-size skip could then keep it and start no pass for a cycle.
take() now clears every candidate on exit.
- The prompt-size skip measured growth since the plan, so once the
prompt grew past the threshold while the window gap stayed small,
every tool batch re-planned again. Keeping a candidate after a full
check now re-arms the skip from that check.
Tests: one stub models the aux client ending a cancelled stream, the
local wait helper gives way to tests.waiting.wait_until, and the
skipped small-window-delta path gets its own test. Docs and the config
comment name the discard case.
While a completed candidate was still fresh, maybe_prepare re-planned the
whole compaction window and re-fingerprinted the transcript before every
tool batch and at every turn end, only to keep the candidate. Measured on
the turn thread: ~23 ms per call at 180k tokens, ~31 ms at 540k.
The candidate now remembers the provider-reported prompt size its pass
was planned at; while the prompt has grown by less than the extension
threshold since then, the hook returns at once. A shrunk prompt or a
larger growth falls through to the full plan, and compaction still runs
the authoritative fingerprint and gap check.
Passes are also skipped while the summary model is benched after two
fallback summaries in a row: inline compaction would not call it then
either (#63008), and each pass would be a paid call.
A pass that compaction or a session boundary superseded kept streaming
its summary to the provider's own ceiling: billed, then thrown away. The
same happened when a waiting compaction gave up at the host deadline or
on a host cancel, so the summary was paid for twice (once in the
background, once inline). Live probe: after the deadline cut a wait
short, the pass still completed 4 s later and was billed (2 aux calls).
Each pass now carries a cancel event, wired into the existing aux
hard-cancel path (aux_interrupt_protection(cancel_event=...)) so the
stream is closed. take() sets it whenever it consumes or supersedes the
pass; discard() sets it on reset, end and rebind. A compaction waiting
on a discarded pass wakes at once instead of waiting out the pass.
Also:
- the waiting compaction installs its progress hooks before the rest of
the setup; resolving the aux timeout loads config on first use
(~0.8 s), and progress streamed in that window was dropped;
- a miss now says why: deadline, host cancel, discarded, or the pass
failed (every miss used to read "did not finish in time");
- the config comment mentions the wait.
Probe after the fix: deadline miss -> the pass exits ~0.1 s later, 1
aux call billed; reset during the wait -> the wait returns at once.
Inline, a llama.cpp server reading a long summary prompt pushes the host's
compression deadline back (compression_deadline_scope installs a
prompt_reading_hook that extends the fence). A compaction waiting on a
prepared pass lost that: the pass thread had no reading hook, and the wait
read the deadline once. A slow-but-healthy local prefill could hit the
original ceiling and fall back to an inline summary that pays the same
prefill again.
The pass now installs a reading hook that forwards to the waiting
compaction's hook, and the wait re-reads the live host deadline on every
poll.