A model that answers and then closes the same message with a marker line
("Here is the answer.\n\nNO_REPLY") had the marker delivered as text: the
silence filters only match a response that is exactly a marker. Strip a
marker on the reply's last line at every delivery door (final send, stream
previews and final edit, crash-left replay, Bot Mode relays). A bare marker
still goes through the silence verdict, a marker inside a line is prose, and
stored history keeps the model's text.
Review of #145598 (comment 6448254020):
- Chats a Webapp tab imported before the upgrade open again: session_history_mount._reader read the
import binding by string equality while the sidebar (authorize_history) used the owner rule, so
the sidebar listed the chat and the open refused it. Both now ask binding_names().
- An old chat a Webapp tab edited is adopted again: bind_legacy_target compared the binding exactly.
- gateway.owner_identity.same_owner is now the one owner rule (owns_row_stamp folded into it), and
every comparison of a stored owner/binding/principal with a caller in gateway/ goes through it.
- Local stamps match this machine's account only.
- hosted_auth_probe: restore the refused groups.create over another tab's room id and the
'FORBIDDEN' never reaching the model, adapted to the single-owner contract.
Follow-up to the cherry-picked fix for #143715, from review.
- A stamp now counts as an owner when a native ticket carries it as its subject: the host's own
OS identity (`owner_worker_subject()`: `uid:<n>`, Windows `sid:<sid>`, the subject a same-user
native socket ticket carries) or a structured login subject `auth:v1:[...]` that a same-user
peer may forward (#138915). Such a row is kept when `validate_legacy_row` accepts it for that
subject (unrouted, own profile), and a native ticket carrying the same subject adopts it in
place with its history.
- Host-identity rows: the cron/bot_relay door carries that subject, so the delivery itself
adopts the row in place, as on main. The previous commit moved it aside and restarted the
bot's chat empty.
- Forwarded-subject rows: kept and refused (`not_found`) for the cron door, as on main, until
the peer whose ticket carries that subject adopts it. The previous commit moved it aside.
- Any other stamp on a non-Desktop row (a login label such as `basic:alice`, another OS user's
`uid`) names no subject a ticket carries, so nobody can adopt the row. It stays moved aside, as
in the previous commit. Such a row that also carries a route column a crash left behind (no
binding) is now moved aside too. The previous commit kept it, so it still refused every
delivery (#141243).
- Desktop rows a served login stamped with its label (`<provider>:<id>`) are unchanged from main
and the previous commit: kept, even with a stale route or another profile's name. The Nous
account label (`nous:...`) still follows the legacy rule, as on main. A Desktop row stamped with a native subject
follows the subject rule: kept when adoptable, moved aside when a route column or another
profile's name makes it unadoptable (main kept it and refused every delivery).
- Docstrings and the inline comment describe the rule the code enforces.
- Tests: the moved-aside case covers `cli`, the stale-route shape, another OS user's `uid` and a
routed Desktop row stamped with a subject; the Desktop refusal asserts `not_found`; a
host-identity stamp is adopted in place; a forwarded login subject is kept.
Validation: tests/gateway/test_bot_chat_unadoptable_local_title.py 12 passed. With the previous
commit's session_bot.py, 4 fail (host-stamp adopt-in-place, stale-route, forwarded subject,
routed Desktop subject); against origin/main, 6 fail. A mutant that keeps every `uid:`/`sid:`
stamp turns the other-OS-user case red.
An unbound legacy local row carrying a user_id stamp held the canonical
"Bot Chat" title and counted as kept history, so the door neither moved it
aside nor minted the profile's chat. The delivery principal is submit-only
and validate_legacy_row refuses a foreign stamp, so every routine
deliver: bot-chat ended "unverified: not_found" for good (#143715).
A stamp now keeps a row in place only on a Desktop source (a served login's
own chat, #140183) or when the row carries a binding.
The Bot Mode roster gave the default profile the @hermes handle unconditionally, so
an install with a pre-reservation profiles/hermes listed two @hermes teammates in
every Bot Chat system prompt, signed the default's DMs as @hermes, and the Bot Chat
admission door accepted profile='hermes' on the default profile's authority.
_handle now takes the roster: the default answers to @hermes only while no live
profile holds that name, and to @default otherwise. Every caller (teammate roster,
"You are" line, DM signature and author, relay sender stamp, local_taken_forms,
session_bot admission) passes it, so they all agree with message_agent's lookup.
_admission_outcome read the admission row, then its result blob, in two
statements. The drain settles from a worker thread (commit_and_publish), so
the commit could land between them: the result was present while the stale
started row had no outcome, and a completed turn projected as a terminal
`failed` receipt carrying the reply as its error. Terminal receipts leave
_bot_receipt_index, so the settle wake re-read nothing and no reply watcher
existed; the sender kept the false failure for good.
Read the result first; when one exists but the row read was not terminal,
re-read the row (the result and terminal outcome commit together, and
terminal is final).
This is the CI flake test_paused_receipt_rearms_on_resume_without_polling_rpc
("the paused delivery never settled"). Repro: an in-process loop of that
scenario with a 0-20 ms stall between the two reads strands 251/2400
receipts on main (all `failed`/error=reply, row terminal/completed), 0/2400
with this fix. The new test commits the settlement between the two reads
through refresh_receipt and fails on main with ('failed', 'pong').
Round-3 re-review of #144708:
- A lane's /new frees a handed-off Bot Chat's title from the store's worker
thread, outside the titled-create lock. A Bot delivery it landed in the
middle of (after the title read, or under the lock before its own displace
write) re-read an empty title and crashed on row['id'], so the delivery
failed and nothing was minted. _create_bot_chat now mints when its displace
write lost to that rename and the title is free; _target mints when its
re-read finds the title gone.
- The platform's /resume of a local conversation resolved its title to the
first segment, so after a local /new it moved that stale segment onto the
lane and released the receipt of the live segment, which stayed local and
was refused storage_unavailable after a restart. It now resolves the
conversation's current head through the same conversation_head step
/handoff uses, and a Desktop still viewing it follows it onto the lane.
Greptile on df9746d5f09:
- A chat handed off to a route again after another one took it (H, then Y,
then H) skipped the supersede loop because it was already on that route, so
Y stayed writable while the route named H. _publish_route now treats a
superseded session coming back as a takeover too.
- The Bot Chat a delivery minted under its automatic creation id, reset
locally and handed off, leaves its first segment untitled on the lane once
the name follows the head. _bot_chat_creation_id read that untitled row as an
interrupted creation and reused its id after the platform's /new, so the next
delivery hit the released receipt (storage_unavailable). A creation handed
off to a messaging lane is spent.
- A moved receipt whose lineage holds a non-string entry raised TypeError in
the boot heal and stopped the profile's start; hand_off_conversations now
leaves such a receipt as it is (its own reads refuse it, logged).
- The title follow-the-head rule ranks provenance with SessionDB._title_rank
instead of a copy (a pre-provenance title ranks as the user's).
Three defects an independent re-review found on #144708 (#143286):
- Data safety. After a local /new (receipt now names the new segment), a
/handoff of the chat's id moved the stale first segment to the lane and the
owner-row branch of moved_receipts released the receipt guarding the
post-/new segment, which was still local: that transcript was reachable from
nowhere and the platform resumed the stale history. The handoff now repoints
the receipt's current head (latest /new segment, then its compression tip,
hermes_state_local.handoff_head); a receipt is released only when the row its
CURRENT target names moved to a messaging lane, and the rest of that
conversation moves with it in the same write (hand_off_conversations): its
earlier segments open as the lane's read-only history and its name follows
the head over a generated title. A Desktop still holding the chat follows it
(follow_hand_off).
- Bot Chat after the platform's /new. The roster's canonical_session (raw title
registry) still named the superseded handed-off chat while the title lookup
hid it, so Desktop's bot row failed closed ("Could not confirm ... not
starting a new chat") on every click. The title now moves aside at the moment
the lane moves off the chat (SessionStore._promote_session_reset, every route
transition, and at boot), so the registry, the roster and the lookup agree
at every step; the lookup-side filter and the create-side move-aside go.
- Second handoff to the same home chat. A live local chat handed off to a route
that already carried a handed-off chat skipped the supersede loop, leaving
the first chat writable while the route named the second. _publish_route now
supersedes every other handed-off/history mount on a route whenever a
session takes it over.
The PR's own history='reset' case asserted the old (stale-segment) behaviour;
it now asserts the head carries on and the earlier segment is read-only history.
Review of #144708 (Bot Mode keeps one canonical forever-chat per profile + title):
- A Bot/cron delivery after the handoff treated the handed-off Bot Chat as displaceable
(a messaging row with no receipt), renamed it aside and minted a new canonical chat, so
the bot row silently switched chats. `displaceable_bot_chat` keeps a handed-off chat whose
lane still holds it, and `_target` delivers to it on that lane.
- The Desktop view that followed the chat onto the lane stayed writable after the platform's
own /new, with a route naming the new conversation (Stop, agent lookup and turns would act
on it). A handed-off live session is now superseded like a history mount when its lane
publishes another conversation.
- After that /new and a restart the bot row adopted the read-only chat forever. The title
lookup no longer resolves a handed-off Bot Chat whose lane moved on, and Desktop's titled
create (and the delivery door) move it aside, `Bot Chat (<platform> <id>)`, before minting
a fresh one.
- The in-handoff receipt release applies the startup heal's messaging-lane filter.
Also: a chat with a /new reset segment handed off by its conversation id (a platform
`/resume <title>` or a resumed CLI) kept a receipt naming the reset segment while its owner
row moved to the lane, so every cold open failed the lineage check. A receipt whose owner
row a repoint moved is released too (in the write and by the startup heal).
A CLI/TUI/Desktop row titled "Bot Chat" that no native open can ever adopt
(a crash/reconnect left a route column on it with no local binding, or another
profile stamped it) refused every Bot Chat delivery for good: _target found it
by title, displaceable_bot_chat treated every LEGACY_LOCAL_SOURCES row as owned
history, and adopt_legacy_session -> validate_legacy_row raised not_found. A
cron `deliver: bot-chat` job booked delivery_failed: not_found on every beat.
displaceable_bot_chat now keeps a local-source row only when it is real local
history: adoptable (validate_legacy_row passes) or stamped by a login as its
owner. Any other unbound local row is moved aside as "Bot Chat (<source> <id>)",
as API and messaging rows already are, and the profile's local Bot Chat is
minted under the titled-create lock. Rows with history keep their id and
messages; a submit-only principal still never moves the title.
The producer pins the Bot Chat id it discovered, so the first delivery after
any move-aside (this case and the existing API-row one) was refused
admission_conflict and landed only on the next beat. The deliver door now
accepts a pin naming the holder its own _target just moved aside.
Live (real `gateway run --force`, scratch HERMES_HOME, fake LLM): origin/main
fails `not_found` on both beats with 0 LLM requests; head delivers both beats
into the minted local Bot Chat; the API-row leg goes from admission_conflict on
beat 0 to delivered.
Fixes#141243
Refs #134889
displaceable_bot_chat also moves a messaging row that took the canonical
title, and _displace_bot_chat renamed every such row "Bot Chat (API <id>)".
The new name now says where it came from: API for api_server/bot_peer_dm
rows, else the platform ("Bot Chat (telegram <id>)"). The refusal hint
names the same shape.
It also runs on every delivery (twice per peer DM): a bound local chat,
the common case, now answers from its own row before any compression-tip
or session read.
Tests: test_a_messaging_bot_chat_moved_aside_is_labelled_by_its_platform,
test_a_local_bot_chat_is_never_displaceable_without_a_lineage_read (both
red before; green).
Review finding by @kshitijk4poor on #140973
Refs #134889 (MSG-21)
Refs #140719
A profile whose canonical "Bot Chat" title is held by a conversation no
FIFO can own (an api_ row an older gateway or a plain POST /api/sessions
minted, chat_id NULL) refused every delivery for good:
- a peer DM or `hermes peer run` / POST /v1/runs got 502
bot_chat_not_local, "rename or delete it there". Neither is possible:
`hermes sessions rename` refuses the canonical title by design, and the
API server has no rename route (#140769);
- a local bot_relay or cron delivery found the row by title, failed
adoption (validate_legacy_row) and answered not_found (#140374).
The Bot Chat door now moves such a row aside under the titled-create lock
and mints the profile's local Bot Chat there: the old row keeps its id and
history and becomes visible as "Bot Chat (API <id>)", which the user can
find, rename or delete. A peer turn aimed at it is admitted under the
peer's create grant (the same principal create_peer_bot_chat uses), so the
owner mints the chat once and every later DM finds it by title. A bound
local chat, and old CLI/TUI/Desktop history a native open adopts, are
never moved; a submit-only principal (owner recovery) cannot create the
replacement, so it never moves the title either. The refusal that remains
names the remedy that now runs.
Refs #134889 (MSG-21)
Refs #140374
Refs #140769
Refs #140719
Desktop creates the Bot Chat with follow_profile_config, so each turn
runs the profile's current model, endpoint and key. A Bot or cron
delivery, a peer DM, a CLI titled create, and adoption of a pre-upgrade
Bot Chat froze the route of that moment instead. Desktop then reuses
the chat by title, and retiring the old key breaks it.
Those producers now ask to follow the profile too. A safe-mode create
stays frozen, and a creation an older build staged before the flag
resumes as it was staged. Adopting a Bot Chat whose profile names no
model keeps the saved model name on the receipt, so the chat can be
opened and follows once the profile has a default. Chats that are not
a Bot Chat are unchanged.
A Bot Chat an earlier build already committed frozen follows from the
first time a client opens it, also on a later open over the same
connection when the first found a turn running. The resume refresh
marks the policy as following inside its own config, so no other
receipt changes shape and the creation request stays the exact-retry
identity, and binds its private values again without the followed
sections, so the frozen key never reaches the profile's current
endpoint. A composer pick is held under adoption's rule, and a
committed /reasoning stays the session's level. Safe mode, a request
that chose false, and other titles stay frozen.
A held pick ends once the named provider entry (or alias) its key comes
from no longer serves the endpoint the pick was made on, so that
entry's new key never reaches the old endpoint. A provider-only or
endpoint-only pick on a new following session holds like a model pick.
Fixes#140470
Refs #134889
(cherry picked from commit acd3e9420ab4d61b7d5147657c42b6fedaccb717)
settle tracked its mutation, so retirement waited for a settle already
running, but nothing refused one arriving after retirement had finished.
A stale connection to a retired authority could still write a terminal
not-sent receipt into the home it had released. Those receipt files carry
no runtime epoch and mailbox_lock belongs to the old authority, so nothing
serializes that write with the home's next owner.
settle now runs require_serving (runtime_retired) and
_require_admission_open (runtime_draining) before it registers its
mutation, the same gates deliver and the other relay verbs use. A settle
already tracked when retirement starts is still joined. The Desktop
writer is still not re-checked: it may release legitimately between the
refusal and the settle.
On the tool side, the refusal is an ordinary GatewayRPCError from
settle_held_delivery. _admit_live_dm re-raises it, and the caller answers
"ambiguous ... Do not resend" (the runner gives the unknown outcome) and
keeps the pinned intent, never "NOT sent". The new tests cover both, and
bot_relay.settle joins the table in test_retired_authority_cron_fence.py.
Refs #134889 (MSG-19)
Refs #140208
_deliver repeated the "admitted receipt -> same-delivery check ->
authorize -> _maybe_retry -> _publish_result / refused receipt ->
answer" block before and after _migrate, and _settle carried a third
copy without the retry. _receipt_answer now holds it once; _settle
calls it without a retry path, as before, and still answers an
unadmitted pin with unknown_execution.
The owner (_not_sent_record, _held_by_another_writer) and the Bot DM
tool (LiveTargetHeldError, _held_disposition, the admitted:false check)
each hard-coded 'runtime_coordination_required' to recognise the
settled no-send. Both now read HELD_NOT_SENT from
tools/bot_failure_reasons.py, kept out of ALL_REASONS so the bot-turn
vocabulary and its passthrough are unchanged. The DM tool imports it
lazily: its top level stays stdlib-only for the direct runner.
No behaviour change; the existing held-writer, receipt and migration
tests cover every branch.
Refs #134889 (MSG-19)
Refs #140208
bot_relay.settle doesn't re-check that a writer holds the Bot Chat: the
writer may release between the refusal and the settle, and what settle
serializes under the mailbox lock is only that nothing was admitted
under the id. Yet the receipt it stored said "Bot Chat is held by
another session writer", a condition it never checked (a settle on a
fresh id with the chat free stored that text too).
The stored error now reads "Settled as not sent after a session-writer
refusal", and _settle's docstring names the trust boundary: any
session:submit principal of the profile can settle an id, the same
trust deliver already grants over that id. The reason code, the tool's
visible answer and the race handling are unchanged.
Refs #134889 (MSG-19)
Refs #140208
A pre-upgrade Desktop backend (classic tui_gateway prompt path) can still
hold a 'desktop' lease on a legacy Bot Chat. The owner's first delivery
adopts that chat through resolve_local_target, whose liveness guard
correctly refuses runtime_coordination_required (one writer per
transcript). message_agent had already fsynced its live-delivery intent,
so it answered "ambiguous ... Do not resend" and kept the pinned intent
for a replay, though nothing was admitted.
The owner's bot_relay.deliver door marks that refusal admitted=false
(field session_writer) when the delivery id has no receipt. That marker
proves absence only while the request holds the mailbox lock: a same-id
attempt (the runner retrying the pinned intent) can admit right after.
So it is a hint, not the verdict. Before the tool says "NOT sent" it
calls the new bot_relay.settle verb with the same identity. Under the
same mailbox lock _admit holds, settle either writes the id's terminal
not-sent receipt (refuse_pin's refused/failed shape, reason
runtime_coordination_required, full identity) or answers with the
admission that won. deliver answers a refused id with that receipt
before anything else, so a not-sent answer and an admission of the same
id can't coexist. Only the tool calls settle: cron's same-id retry of a
refused record still admits once the writer closes.
The tool raises LiveTargetHeldError ("held by another session writer
... NOT sent; safe to resend after that session closes") only for that
settled receipt. A replayed intent that meets it gets the same answer.
_start_delivery and _run_delivery share _settled_no_send, which removes
the intent and the payload. If either file survives the unlink, the
answer is the unknown outcome instead. Any other refusal, an older owner
without the marker, or a failed settle call stays ambiguous. The
refusal itself and the one-writer rule are unchanged.
Refs #134889 (MSG-19)
Refs #140208
Three review follow-ups on startup Bot recovery:
- A profile parked at boot comes back only through a control-socket rescan
(`hermes -p <name> gateway run` sends one). The parked reason now says so.
- A receipt the store cannot answer is logged with its file and the
traceback, not just its delivery id and reason.
- A pending receipt whose session row is gone with no deletion marker still
settles as `ambiguous` (never resent), but that is store damage or a marker
an older release reclaimed, not a plain delete, so it is now logged. The
receipt is final afterwards, so the warning appears once.
Refs #134889 (GW-12)
Refs #140018
The header-less chat walk (`implicit_api_session`) repeated the Bot Chat
creation walk (`_bot_chat_creation_id`). Both now call
`hermes_state_mutation_retirement.first_generation`: the first generation of
a derived id that is not retired, with an optional pin that keeps an exact
retry on the retired generation holding its identity, and an optional
"spent" check (a renamed Bot Chat). No behaviour change; the hosted-room and
A2A paths use it next.
Refs #134889 (GW-12)
Since recovery skips a receipt it cannot answer, a settled or failed
receipt left untouched still read back as expected. The tests now also
assert that nothing was logged as not recovered, so dropping the
expiry handling or the failed-receipt fallback fails them. The guard's
comment says what the next start does with a skipped receipt.
Refs #140018
(cherry picked from commit 8b53a12f7675933ea64fb1a55e7052d03cc076a8)
recover_bot_deliveries now logs a receipt that raises RuntimeStoreError
(delivery id and reason), leaves the file for the next start, and
recovers the rest, so startup recovery can't brick the gateway from a
durable leftover. The lookup-failure pin asserts that log instead of the
raise; the exact-id deliver path still raises.
Refs #140018
(cherry picked from commit 0b17d3b2571e7636756cd1c8b551d838ca317bdd)
An independent review of the first commit found two problems:
- A failed receipt behind an expired admission still aborted boot:
_result called _failure, whose admission_result raised not_found.
_result now keeps the receipt's own error and reason (a failed
receipt always carries both).
- Keeping the retired-session marker forever refused legitimate reuse
for good: a headerless Chat Completions id derived from the first
message, a reused X-Hermes-Session-Id, hosted-room and A2A ids, and
imports of exported sessions. The marker keeps its 7-day horizon;
_expired_outcome already answers a receipt whose session row is gone.
The tests now cover failed receipts, assert the Responses error code,
and prove startup recovery answered a pending receipt.
Refs #140018
(cherry picked from commit 1975dac37ac77406d01bd412811e8ba3061fd28b)
The maintenance prune reclaimed a deleted session's tombstones after the
7-day retry horizon, the retired-session marker included. Bot receipts
never expire, and owner startup re-reads every one: a receipt whose
admission was gone raised storage_unavailable out of
start_gateway_runtime_api, so the gateway failed to start on every boot
(every served profile under multiplex).
- The retired-session marker is the deletion fence and is never
reclaimed; admissions, results and worker tombstones still age out.
- A Bot receipt whose admission is gone keeps a final status it already
holds; a pending one whose session is deleted becomes ambiguous. A live
session missing its admission is still storage_unavailable.
- A Responses Idempotency-Key pointer whose admission is gone answers
409 admission_conflict instead of 503 forever.
Fixes#140018
(cherry picked from commit 426ba053cdbfe42a8fd30681e53695d96faa8303)
A session delete moves its admission rows to retired receipts keyed by the
route principal (automation:<route>), which the pin never recorded, so the
owner scan read a committed pin on a deleted Bot Chat as "never admitted",
withdrew it, and a same-id resend ran the message a second time. A pin whose
target is retired now counts as possibly committed and stays the explicit
unknown record, as on main.
The age, home and admission checks stay apart from the action: requeue_pin or withdraw_pin runs in its own branch and a requeued ticket is appended to the scan's records there, which removes the _requeue helper. No behaviour change. Review feedback from Greptile.
Refs #139138
Refs #134889 (MSG-9)
Refs #139162
A legacy ticket whose _migrate admission got an owner-state refusal stays a
pre-admission pin until the owner scan requeues it past the grace window. A
recovery or delivery inside that window skipped the pin and admitted the
tickets queued after it, so the requeued ticket ran out of order (B, A).
_scan_owner_receipts now also returns the lowest _legacy_order of a legacy pin
of this home that is still unresolved (inside grace, or its requeue lost to a
concurrent change), taken from the same scan. _migrate, which both owner
recovery and delivery go through, admits only legacy tickets ordered before
it. A pin whose admission committed, or one without owner, is no barrier.
The barrier lasts one scan: past grace the pin is requeued and released, and
a failed requeue is re-read by the next scan. An owner-state refusal mid-pass
already raises out of _migrate, so later tickets never ran in that pass; the
new test pins that down.
Refs #139138
Refs #134889 (MSG-9)
Refs #139162
A pre-admission pin `_admit` lays over a legacy mailbox ticket (`legacy=`)
is the only copy of that queued, never-run message. The owner scan withdrew
any stale pin with no committed `bot:<key>` admission, so a transient
refusal on the legacy migration path dropped queued work.
The scan now restores such a pin (it carries the ticket's `owner`) to the
queued legacy ticket under the mailbox lock, only while it is still that
unadmitted pin, stripping only the fields the pin added and keeping id,
message, sequence and created_at. `_migrate` then admits it once under the
same delivery id in its FIFO place. Non-legacy stale pins are still
withdrawn; a pin whose admission committed is never touched.
Fixes#139138
Refs #134889 (MSG-9)
Refs #139162
A pre-admission `ambiguous` pin stays on disk when its admission was
refused by a build older than the terminal-refusal change, when a
process died between pin and commit, or when `_migrate` hit an
owner-state refusal on a legacy ticket (`legacy=` keeps the pin). Every
owner scan then logged it as a malformed receipt, and a same-id resend
answered `unknown_execution` forever.
The owner's scan (`recover_bot_deliveries` and `_migrate`, both under
the mailbox lock `_admit` holds) now collects these pins and withdraws
one with the existing `withdraw_pin` when it is older than
`_PIN_GRACE_SECONDS` (300 s) and no admission row exists for its
`bot:<key>` (`_admission_at`, the lookup `_admit` already uses). It logs
one INFO line per pin (key, age), no message content. A pin whose
admission committed, a pin inside the grace window or one for another
profile home keeps its warning and is never rewritten. The bare
`scan_receipts` without an authority only reads, as before.
Fixes#139138
Refs #134889 (MSG-9)
Refs #139162
A Bot Chat admission refused with nothing committed became a terminal
"refused" receipt for every reason except queue_full. That included
refusals about the owner rather than the delivery: runtime_draining
while the gateway drains for a restart or update, storage_unavailable,
stale_epoch. The same-id resend then answered the stored refusal with
no admission, so cron/bot_chat_legacy marked a report sent during a
restart as transferred and the sender saw agent_blocked.
Classify the refusal with one named set (_OWNER_STATE_REFUSALS):
owner-state refusals withdraw the pin like queue_full, so the resend
admits once; refusals about the delivery (permission_denied,
invalid_params, admission_conflict, ...) keep the terminal receipt. A
refusal raised after the admission row committed still leaves the
unknown pin.
Refs #134889 (MSG-9)
Refs #139162
Refs #139138
A peer-minted Bot Chat is owned by `api-peer`. A local operator's
bot_relay.deliver into it is admitted through `session:operator` (granted only
by the verified interactive transport), and its receipt stores the operator's
principal_id. After a transient provider failure, _maybe_retry() rebuilt that
principal with only session:submit/session:read, so _target() refused the
retry with permission_denied and the promised one retry never ran.
Shape chosen: the receipt records `operator: true` only when the admitting
actor actually held session:operator (AuthorityConnection strips any claimed
operator capability unless the transport grants it). The retry adds
session:operator back only when that flag is set, and the existing check that
the resolved target is the receipt's admitted session still pins the retry to
the same chat, so nothing is widened. Receipts written without the flag (older
receipts, non-operator senders) retry exactly as before. The api-peer
ownership decision is unchanged, and the retry still reuses the derived
admission identity (`bot:<id>:retry`) and the committed payload.
Refs #134889 (MSG-12)
Refs #139162
Refs #139370
A same-id resend of a delivery the FIFO refused (nothing committed) answers
its terminal refused receipt, which has no admission. CanonicalBotDeliverResult
required admission_id, so through AuthorityConnection.dispatch the answer was a
ContractViolation under test isolation, and in production Desktop's
settleRelayDelivery() treated it as "identity unavailable" and kept the
envelope retained: the refusal never reached the sender.
The contract now declares the refused shape explicitly: admission_id is
optional and `refused: true` marks the receipt, with a validator that a result
either names its admission or is a refused `failed` receipt without one. The
resend carries `refused`; the generated TS/OpenRPC are regenerated with
scripts/gen_gateway_contracts.py. The relay settles a refused failed receipt
for its envelope as the sender's terminal answer (posted back, no longer
retained); an answer with neither an admission nor a refusal is still retained.
The first refusal is unchanged: a JSON-RPC 4001 refusal whose data.reason the
relay already forwards.
Refs #134889 (MSG-9)
Refs #139162
Refs #139138
The refused-receipt branch of _deliver compared only message and
principal, while both admission-backed branches and the mailbox writer
also treat author and notification_category as delivery identity. A
reused id with another bot author or category got the old refusal
instead of admission_conflict. All three branches now share one check.
Refs #134889 (MSG-9)
Refs #139162
Refs #139138
_admit pins the receipt (status ambiguous, no admission_id) before
admitting. Only queue_full withdrew that pin; every other refusal
(permission_denied and friends) left it behind for good, so each bulk
mailbox scan warned about it as a malformed receipt and a same-id
redelivery answered unknown_execution forever.
When the admission raises and no row exists at the delivery's FIFO
identity, the pin now becomes a terminal failed receipt (refused, typed
reason agent_blocked, content-free error; the refusal clause goes to
gateway.log only). The scan validates that shape, recovery and legacy
migration never re-send it, and a same-id redelivery answers it. A pin
without that proof (a refusal raised after the row committed, a crash
in the two-store window) is unchanged and still warns.
Refs #134889 (MSG-9)
Refs #139162
Refs #139138
Mechanism: _create_bot_chat (a profile's first Bot delivery, retry or legacy
migration with no "Bot Chat" yet) ran create_local_session and
title_new_session synchronously on the owner loop: two BEGIN IMMEDIATE
commits that wait up to the SQLite busy timeout behind any other writer, so a
held writer stalled every session, Stop and socket the owner serves. Cron's
creation got the same fix in d65ff063255; session.create commits off-loop
since N50.
Fix: _target and _create_bot_chat are async; creation stages on the loop and
commits (commit_local_session, then the title) through tracked_write, like
session_controls._create. The old "no await between lookup and titled
creation" invariant is kept by the authority's _titled_create_lock (the lock
titled session.create takes) around re-lookup + commit + title, so concurrent
first deliveries and a `session.create -c "Bot Chat"` converge on one chat.
The three callers await _target; two tests that called or patched the sync
_target follow.
Test: tests/gateway/test_owner_loop_writes_bot_chat_create.py (held writer,
loop ticker, two concurrent first deliveries) is red on r13-integ1 (5.09 s
loop stall).
Review: dokterdok N90
Mechanism: session_bot._admit pins an `ambiguous` receipt (no
admission_id) before admit_automation, so a process death between the two
stores leaves explicit unknown state. queue_full is raised inside the
admit transaction before any INSERT, but the pin stayed; the next
delivery of the same id (bot_mode_dm / deliver_to_live_owner / cron retry
by contract) read a receipt without admission_id and answered
unknown_execution forever, and recover_bot_deliveries skips such records.
Today this needs 32 queued rows; with the cap enforced for a paused FIFO
too (authfollow lane, ruling B2-07: cap in BOTH states) it becomes the
normal outcome for a Bot Chat paused by an owner restart mid-turn.
Fix (class rule: a producer that saves before admission withdraws it on a
definite pre-commit refusal):
- _admit: on RuntimeStoreError('queue_full') for a non-legacy record,
drop the pin under the mailbox file lock iff it is still `ambiguous`
with no admission_id, then re-raise. The crash-window pin is unchanged.
- _maybe_retry: queue_full on the one derived retry is treated like
runtime_draining (no retry was admitted; the projection stays pending
and the next wake/delivery performs the same derived retry) instead of
escaping with a stale `queued` projection.
Agrees with the cap-in-both-states ruling: the refusal is the same
queue_full whatever the FIFO's pause state.
Red on r13-base2: tests/gateway/test_bot_receipt_queue_full.py (the retry
after the backlog drains raises unknown_execution).
Review: dokterdok N81
Mechanism: 998df8cc0b moved main's relay-edge cap (methods_bot_relay:
len(message) > MESSAGE_MAX_CHARS + 200 -> 4091) into session_bot._deliver,
which every producer now crosses: cron `deliver: bot-chat`
(scheduler_delivery -> deliver_to_live_owner), its deferred
drain_legacy_pending, the relay and the API peer turn. An ~18k-char cron
digest was refused invalid_params before admission on every attempt; the
deferred record stayed queued and was retried each tick. Main's cron
bot-chat delivery had no length cap.
Fix: the 16,200 cap applies to a bot DM (every bot DM carries a turn
author: bot_mode_dm, the Desktop relay's canonical translation, the
legacy bridge); an authorless trusted producer report gets a 1 MiB
resource bound and is admitted whole under its stable delivery id.
Red on r13-base2: tests/gateway/test_bot_door_message_cap.py (the cron
digest raises invalid_params); keep-working half: a 16,201-char relayed
DM is still refused, a 16,000-char one admits.
Review: dokterdok N89
Class: retirement without a full fence on every per-authority resource.
bee54c37e64 set authority.retired and fenced session_cron.operation. The
other verbs a stale connection (or an AuthorityConnection._sibling_for
cached sibling) can still reach on the retired object and that WRITE the
released home are the Bot relay verbs: bot_relay.outbox.drain renames the
home's outbox envelopes into claimed/ (the successor's Desktop then never
receives them), bot_relay.reply and bot_relay.roster.sync write the
replies/roster files. They carry no epoch, so not even a successor's
epoch bump fences them.
One guard, session_authorities.require_serving, now fences
session_cron.operation and session_bot.relay_operation. bot_relay.deliver
and the remaining authority verbs pass _require_admission_open (retiring)
or SessionAuthority.authorize (authority lane, NOT_COVERED).
Test: tests/gateway/test_retired_authority_cron_fence.py (table over
cron.cancel, bot_relay.outbox.drain, bot_relay.reply,
bot_relay.roster.sync; the three relay rows fail without this commit).
Scope: new in PR (gateway/session_bot.py, retirement are branch-only).
Review: andrexibiza andrexibiza-5479692359-P1.6
Review: andrexibiza andrexibiza-5480238075-4
(cherry picked from commit b9a7337821f8148e7089bd0adbb6108528a3396f)
_create_bot_chat always created with request_id 'bot-chat:<profile>', i.e. one
deterministic local session id per profile. Once that target was renamed, the
next delivery (no session titled "Bot Chat") replayed the same creation,
create_local_session returned the existing session, and title_new_session
retitled the user's renamed chat back to "Bot Chat". Once it was deleted, the
same identity hit the retirement fence and every delivery failed not_found
instead of minting a replacement.
The current target's lifecycle is now separate from the immutable identity
of an earlier creation: _bot_chat_creation_id walks generations
(bot-chat:<profile>, bot-chat:<profile>:1, ...) and takes the first whose
session is neither retired (deleted; never resurrected) nor titled (renamed;
had it kept "Bot Chat" the title lookup would have found it). An existing
untitled session is the same creation interrupted before its title and is
reused. The choice is derived from durable rows only, so a restart picks the
same identity and concurrent deliveries still converge (it runs on the owner
loop with no await between lookup and creation, as before). Old receipts and
retired ids are left intact.
Red/green: tests/gateway/test_session_bot_target_lifecycle.py fails on the
r6-base gateway/session_bot.py and passes here. Probe (real SessionDB +
authority, fake HOME): after rename target same=True and the renamed title
reverted to "Bot Chat"; after delete RuntimeStoreError not_found -> new
target, rename preserved; after delete a new id distinct from the retired one.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6067585232
tests/gateway/test_peer_dm_bot_chat_authority.py went red with 819b7db20f97:
the peer got `pong` while a re-read of its delivery receipt still said
`queued`. Before that commit the receipt was published synchronously in the
same step the admission settled; now every receipt write runs off-loop under
the mailbox lock, which opened two gaps:
- deliver/_admit published one projection and then answered with a freshly
re-derived one, so a turn that settled during the off-loop write was
answered `settled` while the file held `queued`. They now answer with
exactly the projection they wrote (_publish_result).
- await_peer_receipt reads the outcome straight from the FIFO and returned it
before the owner's reply watcher had published it. It now waits (within its
deadline) for that watcher to finish before answering.
Follow-up to 819b7db20f97 (#135061)
Review: https://github.com/NousResearch/hermes-agent/pull/135061
_record_reply wrote the plain _result after a FIFO pause. Since the
failed->claimed interim mapping moved into _delivery_result, a watcher woken by
the pause whose admission then failed transiently (before it took the mailbox
lock) published `failed`, skipped _maybe_retry because it was paused, and
dropped the delivery from the receipt index. Any await_delivery poller returned
that failure as final while the one transient retry was still owed (the
4a7258dbe8 invariant). Publish _delivery_result instead, like every other
receipt writer.
Follow-up to 819b7db20f97 (#135061)
Review: https://github.com/NousResearch/hermes-agent/pull/135061
Poll the owner's local receipt projection without opening a new admission RPC. Serialize delivery with an async owner lock and short off-loop file transactions, preserve legacy compare-and-set pinning, and refresh paused or adopted receipts from owner publication. Cancelling startup recovery keeps its mailbox operation tracked until physical I/O ends, including repeated cancellation.
The API peer waiter reads the locked receipt off the event loop. Fixtures follow the same public local reader and preserve isolated native daemon homes. The inherited FIFO pause regression retains its behavioral assertions after the mailbox migration.
Validation: scripts/run_tests.sh -j 3 across 11 Bot/receipt files: 112 passed, 3 Linux-only skips on native Windows, no failures or retries. Includes real daemon queued/settled receipts and single/repeated startup cancellation. Log: split-B-tests.log.
Depends-on: "fix(worker): retain persistence and ownership through physical shutdown" (physical worker lifetime)
Depends-on: "fix(gateway): retain mutation ownership through publication and retirement" (mutation ownership helpers)
Depends-on: "fix(gateway): release paused admission observers without false settlement" (shared FIFO pause)
Review-source: itsflownium, https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6050777316
Review-source: Adolanium, https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6055121721
Source-base: NousResearch/hermes-agent#106742 at 0b815190b2
(cherry picked from commit 819b7db20f9791660a0a2ac84771845492e7cd87)
Release every accepted-work observer when its FIFO becomes blocked, preserve unknown managed execution rather than inventing failure, and avoid treating paused hosted or Bot waiters as terminal. The legacy Bot watcher re-arms queued work until durable completion.
Reported-by: Adolanium (https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6055121721)
Validation: tests/gateway/test_authority_pause_recovery.py, tests/gateway/test_bot_paused_waiter.py, tests/gateway/test_session_bot_retry.py, tests/gateway/test_api_pending_daemon.py
Implementation and additional regression probes were AI-assisted with GPT-6 Astra.
(cherry picked from commit 0417de942fa94ed28103b3172486258cca1874c2)
`deliver`, `_record_reply` and `recover_bot_deliveries` held the
cross-process mailbox `_FileLock` (a blocking `fcntl.flock`) for their
whole body: across `admit_automation`, the legacy migration and the
one-retry admission. Taken on the owner's event loop, a DM runner (another
process) holding the lock for a `cancel_queued_delivery` froze every
session, socket and concurrent delivery on that loop. Live probe on a real
`gateway.run` daemon: with a foreign holder for 2 s, an unrelated `ping` on
another websocket took 2.086 s.
The file lock now guards only the pin write a foreign process can race
(`_store`, off-loop via `asyncio.to_thread`), as a compare-and-set on the
status read before: a queued legacy ticket cancelled by a DM runner between
the scan and the pin stays cancelled (nothing admitted), and a claimed one
is marked ambiguous only if it is still claimed. Once pinned, a receipt is
written only by its owner (every foreign writer refuses an admitted ticket),
so republishing it is a plain atomic rename (`_publish`) in the same step
the admission's outcome is read. In-process ordering of an owner's
read → admit → publish sequences moves to an `asyncio.Lock` that yields
instead of blocking.
A2A `forward_to_owner` polled `a2a.forward` every 100 ms for the life of the
forwarded turn. The forward already subscribes the socket to the session,
so it now waits for the admission's `message.complete` frame and re-reads
the exact durable receipt only on a backed-off safety tick (0.25 s → 5 s)
for a frame lost to a replay gap. Live: a 3 s forwarded turn went from 27
RPCs to 5.
After the fix the same probe answers `ping` in 3 ms while the foreign
holder keeps the delivery's own write waiting.
Review: https://github.com/NousResearch/hermes-agent/pull/106742 (itsflownium review: bot mailbox _FileLock held across admission awaits, 100 ms busy-polls, gateway/session_bot.py:396-422)
`await_delivery` (local `message_agent`, the Desktop relay's legacy lane,
`hermes peer dm/run` without an in-process authority) re-read the receipt
through `read_delivery_result`, which replays the whole envelope as a
`bot_relay.deliver` RPC: endpoint discovery, a control-socket ticket and a
fresh websocket on every 0.5 s tick, up to ~3,600 handshakes per 30-minute
wait. While the owner restarted, discovery raised "profile authority is not
ready" straight out of the loop, so the sender lost a reply the restarted
owner later produced (live probe: the wait died 0.02 s after the kill).
Waiters now poll the receipt file the owner already publishes when an
admission settles and again at startup recovery (`_poll_receipt`); a
restart is just a longer pending stretch. `read_delivery_result` keeps the
replay for producers that re-confirm their admission (cron, DM intents).
For the file to be a complete answer the owner publishes what the RPC used
to compute: the admission's status right after it commits (not the bare
`canonical` marker), a failed original whose one transient retry is still
due as interim `claimed` (never the final `failed`), and the final `failed`
once that retry is refused. Startup recovery re-arms the watch on the live
admission or admits the pending retry through the same predicate the peer
waiter uses, so a retry deferred by a draining owner is admitted by its
successor and the same wait gets the answer.
Live (real `gateway.run` daemon, loopback model): a 3 s wait went from 7
authority RPCs to 0; a wait across kill + 3 s down + restart now returns
`settled` / `AUTOMATION_ACK` instead of raising.
Review: https://github.com/NousResearch/hermes-agent/pull/106742 (itsflownium review: receipt read is a full authority RPC polled every 0.5 s and raises through transient restarts, tools/bot_live_delivery.py:316-357)
f879c0c627 added the owner's one-time retry of a transiently failed Bot Chat
delivery, but api_server_bot_chat.await_peer_receipt kept waiting on the
ORIGINAL admission id. After the retry was admitted that future never fired
again, so `hermes peer dm` either slept for its whole budget or returned the
interim failure while the retry was still running.
session_bot.peer_wait_admission now says, on every pass, which admission the
delivery is waiting on: the retry once it exists, or the original. An original
that failed while its retry is still eligible counts as pending (interim), and
the receipt file is re-read for a recorded refusal. await_peer_receipt
re-registers on that id each loop.
Failed receipts lost their typed reason when the CLI lane was retired:
session_bot._result returned status/reply only, so the Desktop relay
(relay.ts postReply reason: res.reason) forwarded `undefined`. A failed
receipt now carries `error` plus `reason`, classified from the committed
result's error + failure_reason with tools.bot_failure_reasons.
_receipt in api_server_bot_chat reuses this logic instead of keeping its own
partial copy.
Tests: the context-overflow bot retry test is back on the owner seam.
result_retry_action classifies an overflow as compress_then_resume, so the
delivery is retried once when the overflow left no open DM row, and refused
with a recorded open_user_tail when the DM is still the durable tail (the
context-pressure classes skip the failed-turn closer and the owner execution
has no adoption seam). Typed reasons are asserted for 503/401/overflow failures.
(cherry picked from commit 65f9e30417a6986d40c59288447948435fd0a994)
Retiring the local CLI DM lane dropped main's one policy-gated re-run of a
failed delivery turn (05e3b864a9). gateway/session_bot.py now admits ONE retry
when the original admission settled `failed` with a committed result that
tools.bot_failure_reasons.result_retry_action classifies transient. The retry
uses the derived FIFO identity `bot:<id>:retry`, so a repeated deliver(), an
owner restart or a second settle reads back the same admission. queued, started
and unknown admissions are never replayed. The delivery's receipt follows the
retry (status/reply, retry_admission_id). No user-row adoption: the failed turn
is already closed by the durable failed-turn boundary. An open user tail is
refused and recorded instead of retried. Stale docs about
HERMES_RESUME_UNANSWERED_TURN and TURN_MAX_ATTEMPTS now describe this retry.
(cherry picked from commit 44cf91b66f97918fe1641af165507430902b3dcd)