Commit Graph

72 Commits

Author SHA1 Message Date
Teknium
0216b1a320 fix(sessions): refresh epoch survives compression rotation; --session targets the tip
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.
2026-10-28 19:30:48 -07:00
alt-glitch
a1fa82fe3b fix(state): a reset or branch of the onboarding chat no longer copies its run
_publish_child_session_row copied the conversation-wide model_config keys
(onboarding_run) onto every child it publishes, including the canonical
reset and branch children, which are their own conversations. After /new
inside the onboarding chat the run lived twice: Skip (which names the
chat's logical id) ended the parent's copy, while the reset child's copy
stayed open, so open_session_ids never emptied and onboarding.run stayed
true.

Carry the keys only onto a compression continuation, the same
"continuation" test that already decides pin/archive.
2026-10-24 12:34:49 +05:30
kshitijk4poor
ce28ca328d fix(gateway): list sessions compressed before created_source stamping
Symptom: a conversation compressed before write-time created_source
stamping, and not written since, stays out of `hermes sessions list
--source cli` (and tui/gui/acp) and browse. Its root still has a NULL,
'unknown' or 'local' created_source, while its tip carries the real
surface.

Root cause: #140678 stamps a chain's unset ancestors only when the
chain is written again: on the next usage write or compression publish.
A finished conversation never gets that write, so its root stays
hidden.

Change: the owner runs a one-time repair at authority start-up, next to
the legacy owner backfill. In one write transaction it finds each
compression edge with an unset parent and a stamped continuation child
(branch, delegate, reset and tool children are skipped, as in prune),
and stamps that chain through #140678's stamp_compression_ancestors.
The same preferred-continuation and same-surface checks apply, and a
known value is never replaced. Like #140678's write-time stamp, the
repair copies the nearest stamped value onto unset rows, even a wrong
one. A chain with no stamped segment has no surface to copy and is left
as it is.

Guard: the repair is idempotent, so every start runs it without a
marker. On a store with nothing to repair it costs one join query (a
sessions scan probing the parent index) under the write lock. A stamped
child the walk does not follow (a non-preferred sibling, or one with an
inherited fork marker) still matches, and each start re-walks it one
hop.

Why at start-up: the gateway is the only writer of state.db, and a
list-time tip fallback would bring back list cost on legacy stores.
Measured on a synthetic 30k-row store (10k three-row chains, a third of
them legacy): the first start stamps 6668 rows in about 180 ms; later
starts take about 4 ms. The scan grows with the table's size on disk:
about 65 ms with 8 KB of system prompt per row, and the query reads a
real 23k-row store in about 16 ms.

Refs #134889
Refs #139158
Refs #140678
2026-10-20 15:15:42 +05:30
kshitijk4poor
22c9cf36a7 perf(state): the ancestor stamp's unset probe reads only the walked rows
Symptom: on a 30k-row store, every usage write of a stamped compression
child took about 4.8 ms in stamp_compression_ancestors, even when the
chain had nothing left to stamp.

Root cause: the final lookup of _UNSET_ANCESTOR_SQL (the fast path added
in #140678) joins the recursive ``up`` rows to sessions. Without ANALYZE
stats SQLite picks sessions as the outer loop: it scans the whole table
and probes an automatic index on ``up`` for each row.

Change: CROSS JOIN pins ``up`` as the outer loop, so each walked id is a
primary-key lookup. Same rows, same result. Measured on a synthetic
30k-row stamped store: 4822 us -> 22 us per stamped-tip write.

Test: the probe's query plan has no table scan other than ``up``.

Refs #134889
Refs #139158
Refs #140678
2026-10-20 15:15:42 +05:30
kshitijk4poor
e8b309f8e1 perf(state): the ancestor stamp's fast path follows only compression edges
The one-query check asked whether any same-surface ancestor was unset
without looking at the edge. A stamped chain whose root was reset or
branched from a legacy NULL row therefore ran the full validated walk on
every usage write and stamped nothing (about 2 x depth statements).

The recursive CTE now steps only into parents that ended by compression,
the first condition of _CHAIN_STEP_SQL. Anything it still lets through is
checked by the validated walk as before.

Test: test_unset_parent_behind_a_reset_edge_takes_the_fast_path (6
statements on the previous head, 2 now).
2026-10-20 14:13:35 +05:30
kshitijk4poor
19788a0448 fix(state): a compression publish stamps the chain's unset ancestors
A conversation compressed before write-time stamping has an unset root
(NULL, 'unknown' or 'local') and a stamped tip. The list page filters on
the root, so it stayed out of `sessions list --source cli` and `browse`.
publish_compression_child stamped only the new child, so compressing the
conversation again did not repair the root either.

The publish now runs stamp_compression_ancestors on the child, in the same
transaction, after the parent is closed with end_reason='compression'.
Reset and branch children never pass the chain-step check, so they stamp
nothing.

Test: test_compressing_a_stamped_tip_stamps_its_legacy_root[None|unknown|
local] (red on the previous head).
2026-10-20 14:13:35 +05:30
kshitijk4poor
a8ec6b9337 fix(state): the routing label local is never creation provenance
The creator upsert (`COALESCE(NULLIF(created_source,'unknown'), excluded)`)
let any upsert carrying source='local' turn an 'unknown' placeholder into
'local'. A later real creator could not repair it, and the compression
ancestor stamp copied 'local' onto unset ancestors. On main the row stayed
'unknown'.

created_surface() already says 'local' is not a surface. The store side now
names one unset set (_UNSET_CREATED_SOURCES / _UNSET_CREATED_SQL: NULL, '',
'unknown', 'local') and uses it in the creator upsert, the managed-worker
heal and the ancestor stamp. An upsert never writes 'local' over anything,
and a row already holding 'local' is repaired by its creator.

Test: test_routing_label_local_is_not_creation_provenance (red on the
previous head).
2026-10-20 14:13:35 +05:30
kshitijk4poor
154a89398d perf(state): skip the ancestor stamp walk when no ancestor is unset
Walking through same-surface ancestors (so a NULL root behind a stamped
mid segment gets repaired) removed the walk's early stop. Every
update_token_counts and managed-worker usage write then walked a fully
stamped chain to its root, running two statements per hop (the row read
plus the _CHAIN_STEP_SQL join) inside the write lock.

stamp_compression_ancestors now runs one recursive query first: it climbs
parent_session_id through ancestors on the tip's surface, bounded by
_CHAIN_CAP, and asks whether any ancestor is NULL or 'unknown'. If none
is, it returns immediately. Only then does the validated per-hop walk
run, unchanged, so root(NULL) -> mid(cli) -> tip(cli) is still repaired
and a non-continuation edge or another surface still stops it.

Measured with a chain-depth probe (real SessionDB, chain fully
stamped 'cli'):

  statements per stamp call on the tip   depth 50: 99 -> 2
                                         depth 400: 799 -> 2
  stamp time on the tip                  depth 2/20/180:
                                         0.029/0.389/3.790 ms ->
                                         0.011/0.029/0.231 ms
  update_token_counts on the tip         depth 50: 2.76 -> 1.37 ms
                                         depth 400: 15.10 -> 2.19 ms

A NULL root behind the stamped chain is still stamped after one write
(probe: "root after write: cli" at depth 50 and 400).
2026-10-20 14:13:35 +05:30
kshitijk4poor
5b24af1145 refactor(state): name the unset created_source values once in the ancestor stamp
stamp_compression_ancestors spelled (None, "unknown") and its row SELECT
twice. Hoist both to module constants. created_surface() is not used
here: it also treats '' and 'local' as unset, which this stamp never
overwrote, so behaviour stays identical.
2026-10-20 14:13:35 +05:30
kshitijk4poor
f4861545f5 fix(state): stamp a NULL compression root behind a same-surface segment
stamp_compression_ancestors stopped at the first ancestor that already
had a real created_source. In root(NULL) -> mid('cli') -> tip('cli') the
root was never repaired, and list pages filter on the root, so the
conversation stayed out of `sessions list --source cli`. Walk through
ancestors already on the same surface, stamping only unset ones; a
different real surface or a non-continuation edge still stops the walk.
2026-10-20 14:13:35 +05:30
kshitijk4poor
d093ff694d refactor(state): one not-a-surface set for created_surface callers
Review suggestions on the salvaged created_source stamp, no behaviour change:
- created_surface: a single _NOT_A_SURFACE constant. The second check after
  mapping could never be true, since no SURFACES value is '', local or
  unknown.
- compression/reset/branch child: `created_surface(parent) or
  created_surface(source)` replaces a second copy of the reject-list literal.
  created_surface passes a real parent surface through unchanged.
- gateway_session_store: move the comment left orphaned by the
  _LOCAL_LABELLED removal into the _expand docstring it describes.

Not folded: binding created_source=None for source='unknown' in
insert_session_row_in_transaction, in place of record_auxiliary_usage's
existence read and profile UPDATE. That leaves a placeholder row created by
aux usage, ensure_session or update_token_counts without a source as NULL
instead of 'unknown', which is a behaviour change
(test_placeholder_provenance::test_known_provenance_survives_later_creators_and_accounting
fails with `None == 'unknown'`).
2026-10-20 14:13:35 +05:30
kshitijk4poor
e3cc0ca0cb perf(state): stamp compression ancestors at write time, drop list-time walk
An earlier commit in this series (fix(cli): list a compression tip by its own
created_source) let a filtered list admit a compression
root whose chain tip matched, through a correlated EXISTS(WITH RECURSIVE ...)
OR'd into _source_match_clause. That predicate defeats the MULTI-INDEX OR
plan on idx_sessions_local_created_started, so every `--source` list
(in-chat /sessions, `hermes sessions list/browse`, TUI pickers) scanned the
table and walked a chain per row. It also copied _CHAIN_STEP_SQL's edge and
order SQL into hermes_state_common, two copies that could drift (#114271).

Move the guarantee to the writer instead. When a write fills a session's
created_source (the creator upsert behind update_token_counts, or the managed
worker's usage.main heal), stamp_compression_ancestors copies it onto
compression ancestors that are still NULL/'unknown', in the same transaction.
Each hop must be the parent's preferred continuation per the one
_CHAIN_STEP_SQL. In this commit the walk stops at the first ancestor that
already has a surface. Later commits in this series walk through ancestors
already on the same surface, so a NULL root behind a stamped segment is still
repaired, stop at another surface or a non-continuation edge, and skip the
walk after one query when no ancestor is unset. The list filter is back to main's indexed predicate, and the
duplicated chain SQL is gone.

Measured on a 32k-row store (local benchmark, limit 50,
best of 3):
  --source  walk on   this commit   origin/main
  acp       93.4 ms   0.8 ms        0.8 ms
  gui       94.9 ms   4.6 ms        0.8 ms (now also matches desktop rows)
  cli       14.3 ms   13.8 ms       13.3 ms

Chains whose tip was healed before this commit keep a NULL root until the
next usage write on the tip. On main that conversation was not listed
either.
2026-10-20 14:13:35 +05:30
David Dudok de Wit
33ee730853 fix(cli): stamp created_source on reset, branch and compression children
Copy a real parent surface. local and unknown are not stored. Automatic
compression does not create the child again, so a NULL column stays open
for update_token_counts(source=...) and for the managed worker's usage
payload. Auxiliary usage must not write unknown into that NULL first.
2026-10-20 14:13:35 +05:30
Teknium
0715474bfd Merge origin/main into feat/unified-gateway-runtime
375 commits from main (0e427d788d). 24 files conflicted; the resolutions that carry a decision:

- /initiate-setup: main removed the command (25bf722063). Its gateway rewrite, CLI handler and the
  Desktop kickoff go with main; this branch's command-layer admission of it is dropped too
  (gateway/session_commands.py _PROMPT_COMMANDS, its slash.exec test row, the parity doc row), and
  the Desktop slash dispatcher loses the `hidden` option that only the kickoff used.
- Code this branch moved out of its old file, carrying main's edits to the moved copy:
  first-contact notes (gateway/run_turn.py -> run_turn_prepare.py: no message/setup_command),
  the TUI agent factory (tui_gateway/server.py -> agent_factory.py: onboarding toolsets at build,
  setup_beat/set_theme lifecycle cards, no cli platform extras on a coding selection), the serve
  lifespan (web_server.py -> web_server_app.py standalone_lifespan: first-install probe before the
  state.db reconcile, onboarding due answer after the setup bootstrap), and the compression child
  publish (the shared _publish_compression_child_on_conn reads the parent's model_config).
- agent/auxiliary_client.py: both import changes (_route_key from main; this branch's move of
  _without_structured_output_format).
- Desktop: main's onboarding run (decideOnboarding, OnboardingEnd, card-waiting Send) replaces the
  kickoff; this branch's prepared-submission slash path, request_id on session.create and
  PreparedImageRecovery stay. Pool-limits imports are dropped (this branch removed the pool).
  createBackendSessionForSend takes main's (preview, overrides) signature.
- ci.yaml detect job: main's `ref: inputs.commit` plus this branch's sparse checkout.
- package.json / lock: main's vitest 4.1.11 plus this branch's ws 8.21.1.
- Generated: gateway-contract.openrpc.json regenerated; parity doc regenerated.
2026-10-14 05:52:49 -07:00
alt-glitch
bad05d6961 fix(onboarding): a run change lands on the compression tip in its own transaction 2026-10-13 23:18:35 +05:30
alt-glitch
bd0bc52757 feat(onboarding): run record in sessions.model_config and the safe facts
agent/onboarding_record.py stores a run as one onboarding_run key in the
session's model_config (no schema change). advance() is the one writer:
load, onboarding_flow.apply, save; when the run ends (done, skip or the
quiet-spell fallback) it writes onboarding.run false and the profile
offer latch in the root config, so the next launch neither reopens
onboarding nor offers the memory profile. start() writes run true, so a
crash mid-run reopens the chat. observe_tool_result() settles a beat
from set_theme, manage_connections display and gui_tour results; it
reads a record only when the agent carries setup_beat.

agent/onboarding_facts.py reads the class A facts once at start: OS,
architecture, machine kind and nvidia_platform from the host summary,
the onboarding plugins this OS runs by name (onboarding_names, no
presence probe), and whether tours are on. The account's full name is
read only for the name card.

SessionDB gains session_ids_with_model_config_key (finds the run in
progress), and a compression rotation now carries conversation-wide
model_config keys (_CONVERSATION_MODEL_CONFIG_KEYS: onboarding_run) onto
the child, so the run survives the legacy rotating mode too.

agent/onboarding.py re-exports observe_tool_result, and its first-contact
note stays silent in an onboarding chat (onboarding_run_active).
2026-10-13 22:08:20 +05:30
Teknium
e1a10b0bc2 ci: bring the branch's own code under main's strict ruff config
Main made the strict ruff config the default (`ruff check .`, blocking), and
the branch's code carried 278 findings under it (main itself is clean). Fixed:

- PLW1510 (86): `check=False` on each subprocess.run, preserving behaviour,
  as main's own sweep (0006a5e229) did.
- ASYNC220 (9, test fixtures only): `noqa` with the reason, main's convention
  for a Popen that returns at once and whose handle the test drives.
- ruff's safe autofixes plus the narrow unsafe ones (UP006/UP037/RUF100/RUF013/
  PLR0402/RUF059 underscore renames/UP031/UP041/UP017/FURB167/PIE807/RUF007/
  RUF015/RUF022/FURB162), and by hand: four %-formats to f-strings, three
  unused unpacked names, one fixture loop over `.items()`.

No behaviour change. `ruff check .` passes; scripts/check passes; the 412 test
files mirroring every edited file pass (3 tests/pm files that fail only under
that batch's uv lookup pass solo, before and after this commit).
2026-10-10 17:59:08 -07:00
Teknium
607a23e858 Merge origin/main (#30: 54 commits to 1744a19e0d) into feat/unified-gateway-runtime
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 21:38:54 -07:00
Maciej Lisiewski
4278b6aa24 ci: RUF013, RUF015 2026-10-08 21:29:48 +02:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
1bb22926ee Merge origin/main (#20: 54 commits to c538ec5f40) into feat/unified-gateway-runtime
No conflicts.
2026-10-07 15:22:46 -07:00
Teknium
b8788c3cb1 fix(agent): bound lease lock tolerance by the row's committed expiry
Review of #134577 found two ways the lock tolerance could still outlive
the lease row, letting a successor reclaim it under a running turn:

- The local deadline was taken AFTER acquisition/renewal returned, while
  the store stamps expires_at BEFORE its write-lock wait, so a renewal
  that waited 20s gave the turn 20s more than the row. The deadline now
  starts from the admitted row's committed expiry
  (SessionDB.session_turn_lease_expires_at) and from a timestamp taken
  before each successful renewal; neither can exceed the row.
- A retry that started before expiry could block in the write-lock wait
  past it. Each renewal's write patience is now capped at the remaining
  authority minus a 2s margin (refresh_session_turn_lease patience_s),
  and the next-tick check budgets that margin too.

Test: real SessionDB + a second-connection write lock. Red on the PR head,
green here; the lock-clears control renews with no interrupt.
2026-10-07 14:24:22 -07:00
Teknium
1e500ebce2 Merge origin/main (#16: 4,465 commits to 9dcab1e440) into feat/unified-gateway-runtime
99 conflicted files resolved in nine area lanes (Desktop composer, Desktop renderer/shared
client, Electron main, Ink, tui_gateway, gateway, state, CLI/config, cron/tools/CI). The
unified runtime's architecture wins where it deliberately replaced a mechanism (pool,
fallback lanes, claim poller, renderer queue); every orthogonal main change is kept, ported
into the <stem>_<topic> sibling that now owns relocated code.

Notable ports and repairs in this merge:
- tui_gateway/server.py relocated regions: atomic _attach_built_agent (#49852), slash ranking
  registry names, minted-key helpers methods_session.py calls, request_overrides, service tier.
- gateway/run_turn*.py: i18n accessors for the removed reply constants, first-contact
  internal/DM rule, rotated-compression persist, fast-mode tiers, prompt-pin rehydration.
- webhook: route_from_chat_id decodes main's opaque webhook:v2 chat ids (old ids still read).
- ws.py: main's per-connection dispatch queue with authority-first dispatch inside it.
- state: schema event for runtime revision renumbered to 31; worker mirrors updated for
  main's message uid/merge fields, on_contended lease arg, compression columns.
- config: branch's bot_chat_delivery_timeout removal renumbered v47 -> v50.
- Electron: primary-profile pin, redirect header scoping, remote fetchJsonForBackend, SSH
  teardown on profile delete, held-update dial gate restored (lost in earlier merges).
- Desktop: canonical clarify.request mapped to main's questions[] card; replay truncation vs
  snapshot_required; periodic secondary prune tick restored; DELETE already_absent restored.
- cron/tools: diagnostic category on cron failure notices restored; owner_holds_delivery
  ported onto the authority; admitted receipts can no longer be cancelled locally.
2026-10-06 14:24:24 -07:00
Eva
55d82b04ae refactor(compression): name the adopted-snapshot lease watermark in docs and strip row ids explicitly
The lease watermark now means the highest row the compaction already
represents: MAX(id) at lease start, advanced to the newest row of an
adopted durable snapshot. Say so wherever it still read as the lease-start
value, and compute the adopted maximum with newest_exact_held_id() before
removing _row_id in a separate loop instead of popping inside max().

(cherry picked from commit 3e5331777a580c9ffe337b4623746fa78a966bbb)
2026-10-03 16:30:48 +05:30
John Paul Soliva
247b6a1640 fix(sessions): a pin covers the segments compression publishes after it
set_session_pinned writes the pin on every compression segment of a chat,
but a segment published later started unpinned. Prune then deleted the
newest part of a pinned chat, and the stale sweep archived the chat with
its pinned start.

The compression child now takes its parent's pin. Prune and archive
selection also spare the continuations of a pinned segment, so stores
that already hold a pinned start with an unpinned tip are covered.

(cherry picked from commit 4c854e6199fd1797605c5369c81c8038c50f7de8)
2026-10-03 16:30:15 +05:30
Brooklyn Nicholson
55412951c5 test(search): simulate the real chain-walk bound in the deep-lineage fake
The fake's get_compression_tip hardcoded the raised cap, so the test
passed on main too — it could never catch the 100-hop truncation it
exists to prevent. Name the bound (_CHAIN_CAP) in hermes_state_compression
and have the fake walk _CHAIN_CAP hops from the START id, like the real
get_compression_chain. With main's bound the test fails (root walk
truncates to s100); with the fix it resolves s178. Verified against a
real 179-deep SessionDB lineage: main truncates root->s100/mid->s120,
the fix reaches s178 both ways.
2026-10-01 01:50:07 -05:00
Yuan Li
c004e97e3d fix(search): resume deep compression lineages from the matched id, not the capped root walk
Search results remapped session_id via compression_root(hit) followed by
get_compression_tip(root), but the forward chain walk is defensively
bounded at 100 hops. Real in-place compression lineages run ~179 deep,
so the root walk truncated to a stale mid id and resuming a search hit
landed on (or failed against) a dead session. The CLI already resumes
from the matched id and reaches the live tip; align search with it:
resolve the tip from the matched id, keep dedupe keyed by lineage root.

Desktop's resolve-target-session also resumed without omit_messages, the
only session.resume call site missing it; deep lineages then exceed
max_resume_messages in assert_resume_safe and the resume fails outright.
Match the contract every other desktop resume already uses.

Raise the chain walk bound to 1000 (the seen-set already guards cycles)
so root-based tip walks also terminate at the live tip (issue #125041).
2026-10-01 01:50:07 -05:00
Yingliang Zhang
b8b38e55dd fix(state): handoff rows keep the durable parent timestamp for lineage dedupe
Rotation re-inserts the compressor's handoff tail as fresh child rows. Carried
tail dicts arrive without a timestamp, so _insert_message_rows stamped them
with publish-time now(); the parent's durable originals kept their own
timestamps. The two copies then differ in _display_dedupe_key
(role, content, timestamp, tool fields) and _dedupe_display_generations shows
both -> duplicated rows in the ancestor-lineage display read (#59661), once
per segment boundary in a long chain.

publish_compression_child now adopts the durable parent row's timestamp onto
carried rows before insert (best-effort, never overwrites a timestamp the dict
already carries). archive_and_compact gets the same carry for in-place double
compaction, and _insert_message_rows back-stamps the persisted timestamp so
later rotations inherit it. The existing dedupe key and every read path are
unchanged; the collapse happens because identities now agree.
2026-09-28 20:17:37 -05:00
Austin Pickett
6397a84a91 fix(sessions): un-hide an auto-archived chat when it is resumed or compressed
The idle sweep archives a whole compression lineage. When the chat later
resumed and compressed, the new tip was inserted with archived=0 under the
archived root, and the sidebar admits a lineage by its root's flag, so the
live chat stayed hidden.

Record sweep provenance in a new sessions.auto_archived column. Publishing a
compression child or reopening a session under a sweep-only archive
un-hides the lineage; a deliberate archive (sidebar, API, CLI) clears the
provenance and keeps the chat hidden. Compression children now inherit the
parent's archive state so a manually archived lineage stays uniform.

Fixes #117713
2026-09-28 21:03:09 -04:00
kshitijk4poor
73f7fc2ca5 fix(state): a busy state.db is not a turn-lease wait
acquire_session_turn_lease treated a write-lock timeout like a lease that
another holder owns. It called on_wait, so the agent announced "Another
Hermes process is using this session", and it then slept a full poll
interval after the attempt had already spent its write patience.

A lock timeout now retries at once. The poll interval moves into the
retry's write patience, so the retry takes the lock as soon as it is free.
It reports through a new on_contended callback instead of on_wait. The
agent does not announce it, but it still reloads the transcript after
admission, because the busy writer may be the previous holder's final
flush. The failed-attempt cadence, and with it the lock-holder log line,
stays at about one per 1.5s.

With the first-turn lease from #126309, this path also runs on first,
delegate, cron and one-shot turns.

Live test on a real state.db, with another connection holding the write
lock for 1.5s: before, admission took 2.11s and on_wait fired once;
after, 1.52s, with no on_wait and one on_contended.
2026-09-29 02:47:39 +05:30
kshitijk4poor
c8173e0387 fix(state): sweep turn-lease rows left behind by dead holders
A turn that dies without releasing (SIGKILL, crash, parent killed with
children in flight) leaves its session_turn_leases row forever when
nobody resumes that conversation. Acquisition only reclaims the row of
the conversation it is acquiring.

Each acquisition now deletes rows that expired more than 24h ago, in the
same write transaction, through the existing expires_at index (which had
no reader). Recent expiries are kept, so a live owner with a starved
refresher can still renew its own row on its next write.

On a copy of a real state.db lease table, one acquisition removed the four
rows expired 16 to 25 days ago and kept the row expired 15.6h ago and the
live rows.
2026-09-28 19:33:44 +05:30
teknium1
6f2aeb528f Merge origin/main (#10: 382 commits to 8f897d2d23) into feat/unified-gateway-runtime
Conflicts:
- hermes_state_sessions/maintenance: main's shared write-guard filter
  (_guarded_ids, delegate-child cascade guard) runs first, then the branch's
  mutation retirement (retire_sessions / retire_prunable).
- hermes_state_messages/compression: the branch's _append_messages_in_transaction
  split keeps main's serialize/decode repair hooks and runs under main's
  _execute_transcript_write (caller row state restored on rollback).
- web_routers/sessions delete: the gateway-executed canonical delete stays
  (busy sessions already answer 409 session_busy); docs keep that contract.
- web_server lifespan lives in web_server_app: main's orphan-reap startup
  grace (min_age_s, #122533) ported there.
- Desktop uninstall teardown: main's quiet 'quit' intent; its pool-PID seeding
  is dropped because attach-model pool entries own no child process.
- Desktop lifecycle/slash imports: union.
2026-09-27 12:42:14 -07:00
kshitijk4poor
f337631f43 fix(persistence): restore caller row state when any transcript insert rolls back
_insert_message_rows stamps _row_id and the stored-row digest onto the
caller's dicts inside the write transaction. Only append_messages_batch
restored that state on rollback. archive_and_compact, replace_messages
and the rotation handoff left the rolled-back id + digest on the dicts;
SQLite reuses the id, so a later flush found a digest mismatch on the
foreign row, adopted it and silently dropped the user's message.

Move the capture/restore into _execute_transcript_write, used by every
caller that inserts caller-owned dicts: each attempt starts from the
caller's state and a final failure restores it before re-raising.
(Rewind replacement and import insert dicts built inside the txn.)

Also: bind _message_row_params directly on insert instead of the
serialized-dict round-trip, import the public DB_ROW_SNAPSHOT /
CANONICAL_ROW names, set adopt=False once, and reuse target_row
instead of re-SELECTing when nothing was written.
2026-09-27 20:45:44 +05:30
teknium1
c6dc7ab120 Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime
Merge #8: 2,771 commits from main (4b05f764fa). Ports main's moved code into the
unified runtime (run.py/run_turn.py splits, tui_gateway server, backup/restore
split), keeps the detached-daemon Desktop lifecycle, and adapts main's new tests
to the owner/authority contracts (canonical session deletes, retired-id
tombstones, zero-writer browsing, hermes_yaml, platforms() markers).
2026-09-27 02:30:04 -07:00
kshitijk4poor
7ac231fcdb docs(agent): keep the overload-escalation rationale on the constant only
The why (retry can win vs. deferred compression_exhausted wipe, and why the
streak is durable) was spelled out in full at the constant, in
_on_summary_failure, in record_completed_compaction and in the durable
getter docstring. Keep it once on _CONSECUTIVE_OVERLOAD_ABORT_ESCALATION
and cut the other copies to one line, matching the sibling fallback-streak
getter. Comment-only.
2026-09-26 22:42:38 +05:30
kshitijk4poor
50066dda6e fix(state): bump the summary-overload streak atomically
The durable overload budget was a read-modify-write (memory += 1, then
set the column), so two agents compressing the same session concurrently
could each write N+1 and lose a strike, delaying the fallback escalation.
Bump the column with one UPDATE ... RETURNING inside _execute_write and
take the returned row value as authoritative; memory-only counting is
kept for unbound compressors. No try/except or legacy-setter shim: the
existing _durable_read plumbing already degrades on unsupported DBs.

Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
2026-09-26 22:42:38 +05:30
Yuan Li
2305385042 fix(agent): persist the summary-overload budget in session state so fresh bindings inherit it
Review P1 on #123186 (ehz0ah): the N=3 sustained-overload budget was
object-local. The gateway binds a fresh compressor to the same session on
every turn / cache eviction, and restart / API-server requests construct
one too, so each fresh instance restarted the budget at zero and a
sustained summary-provider outage walked the session back into
compression_exhausted and auto-reset — the exact wipe the PR exists to
prevent. Reproduced by the reviewer with three fresh compressors bound to
one session: every attempt ended at counter=1.

Persist the streak as sessions.compression_overload_streak through the
same durable channel the fallback streak and recovery deadline already
use (#100185): SessionCompressionMixin get/set pair over the sessions
row, loaded in the compressor's durable-load block, written on every
change (overload abort, successful summary, committed boundary, runtime
model switch).

- Compression rotation carries the streak to the child row at the
  boundary, same as the fallback streak: the parent's value is read
  before the bind, re-applied, and persisted onto the fresh child row.
- A completed compaction boundary settles the budget to 0 — including
  the committed degraded fallback, so a recovered provider regains a
  full budget instead of the session staying degraded forever.
- Schema event appended to SCHEMA_HISTORY["sessions"] (seq 28, after
  compression_recovery_deadline) so salvage replay maps the new column.
- Fresh-instance regression: two aborts on one compressor, then a fresh
  compressor bound to the same session inherits streak=2 and the third
  session-wide attempt commits the fallback; plus a rotation carry-over
  test. Both fail red against the memory-only implementation.

(cherry picked from commit 3742fee8d03d7077d23b0dac3a3c79fe48e102ac)
2026-09-26 22:42:38 +05:30
teknium1
444dd0af3b Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
# Conflicts:
#	apps/desktop/electron/main.ts
#	apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
#	apps/desktop/src/plugins/hermes-bots/i18n.ts
#	gateway/run_shutdown.py
#	gateway/run_startup.py
#	gateway/run_turn.py
#	gateway/session_lifecycle.py
#	tools/bot_mode_dm.py
#	tui_gateway/server.py
#	website/docs/user-guide/features/acp.md
2026-09-23 17:42:41 -07:00
teknium1
d956f0ae57 fix: key the tools[] pin by code version; never re-add config-excluded tools
Review follow-up on the byte-identical tools[] pin.

- The pin records the code identity that built it (checkout/build sha, else
  the release version). Written by the same code, every pinned tool that is
  still available keeps its pinned bytes, including tools whose parameters
  are derived per surface (delegate_task, text_to_speech, memory, patch).
  The per-tool "parameters differ -> take current" rule replaced those bytes
  on every surface hop and rewrote the ~44KB pin each time. A pin from other
  code (`hermes update`, legacy name lists) takes the current definitions
  once and is re-pinned.
- A pinned tool this process did not build is carried forward only while
  this agent's toolset selection allows it (enabled minus disabled toolsets
  and role reservations, before check_fn). It must also pass the session
  schema gates on the merged array, so browser_exec never comes back once
  terminal is gone. Client-surface toolsets (desktop_ui, project) still
  carry across hops: no config choice removed them there.
- The rotation compaction child inherits the parent's pin in the publish
  transaction.
- `hermes sessions recover` keeps pin rows in its system_prompts sweep and
  clears dangling pin hashes, as lost-and-found now does too. Profile moves
  carry the pin like the prompt. A continuing session whose pin is missing
  or unreadable (a row swept by an older build) pins the tools it sends on
  that turn, so later hops stay stable.
2026-09-23 15:43:51 -07:00
teknium1
eec5bd6673 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
4,048 upstream commits (Sep 16-23) composed onto the unified gateway runtime by six
per-domain conflict lanes (gateway, desktop/shared, cli/state, cron, bots/tui_gateway, ink).
Retired lanes stay retired (Desktop secondary pool + exit supervisor, deferred Bot Chat
pending queue, subprocess retry adoption); main's gateway.standalone, host-role claim,
clarify capability gate, config-read caches and idle gates ride on top.
2026-09-23 03:25:31 -07:00
teknium1
52a293fb07 fix(state): stale-agent recovery ignores reset forks of a compression parent
_NON_CONTINUATION_CHILD_FILTER_SQL now excludes a child whose
_reset_from marker is bound to the queried parent, like the branch and
delegate markers, so find_live_compression_child never recovers to (or
fails closed because of) a reset fork and a lone reset child no longer
blocks reopen_orphaned_compression_session (#114271).
2026-09-18 10:39:13 -07:00
teknium1
09cf1b926f fix(state): reset forks leave the Python lineage walk too; /resume ranks lineages by activity
The SQL chain step (#114287) stopped a `_reset_from` child of a compression-ended parent
from winning tip projection. The Python twin had the same blind spot:
`_is_compression_child_row` / `_compression_lineage_root` treated the reset fork as a
continuation, so `get_compression_lineage(tip)` collapsed to `[tip]` (ancestors lost for
prompt-cache scope and export) and the fork shared the lineage's turn-lease key. Both now
ask `_is_explicit_fork_child_row(include_reset=True)`; `get_compression_lineage`'s own
early return keeps excluding only branch/delegate/tool so a reset child that later
compresses still walks forward to its children.

Gateway bare `/resume` lists with `order_by_last_active=True`: a lineage compressed for
days is projected onto its live tip and belongs where the user last touched it, not at
its root's `started_at` (the reporter's tip, active yesterday, was buried under a
September-12 start). Desktop already requests `order=recent`.

Docs: `/resume` row in slash-commands reference. Tests: one lineage-walk invariant, one
/resume ranking invariant, both red on origin/main.

Part of #114271
2026-09-18 10:39:13 -07:00
liuhao1024
714c2be565 fix(state): keep reset forks from stealing the compression lineage tip
A reset fork child (model_config._reset_from, or the legacy same-key
heuristic) is a separate user-visible conversation that already lists
as its own row, but the compression chain step only excluded
branch/delegate/tool children. When a reset sibling ended later than
the real continuation it won the last_active tiebreak, so the lineage
tip projection landed on it: the newest session became invisible in
every list and the reset sibling showed twice (#114271).

Exclude _RESET_CHILD_SQL children in both forward-chain walkers
(get_compression_chain's _CHAIN_STEP_SQL and the order_by_last_active
CTE in list_sessions_rich), mirroring the resume path's exclusion.
2026-09-18 10:39:13 -07:00
Teknium
b17aa114d2 Merge origin/main into feat/unified-gateway-runtime
Keep-both resolution across 22 conflicting files; main's Sep 10-11 multiplex fixes
(17 PRs) retained alongside the unified runtime's rewrites. Local-backend pool
files removed on the branch stay removed.
2026-09-11 19:22:30 -07:00
Efe Büken
a239c4f811 fix(state): tolerate malformed session marker JSON 2026-09-11 06:24:54 -07:00
Teknium
7e2c7e1581 Merge origin/main into the gateway cutover repair branch
Preserve new queue loading and notification types alongside canonical input
retention. Keep current cron mirror eligibility documentation and the
canonical completion admission contract. Validation continues on the combined
repair tree before publication.
2026-09-10 04:32:25 -07:00
Teknium
a0749d583a refactor(sessions): trim #106543 to the host-side heal and two invariants
The publish-side taxonomy (_end_stamp_class, _compression_parent_obstacle,
compression_parent_deliberately_ended) and the agent-guard delegation produced
exactly main's verdict -- every non-automatic stamp still fails closed -- so
they only changed an error string. Inline the "explicit close with no
continuation" test into reopen_if_explicitly_closed(), restore main's publish
branch and agent guard untouched, and keep two tests: the field shape rotates
after the host clears the stamp; boundary/compression/automatic stamps and a
session already claimed for teardown are never cleared.
2026-09-10 03:04:51 -07:00
Totoro-qaq
9cd1453f26 fix(sessions): a stale explicit-close stamp no longer makes a session permanently uncompressible
Consolidated from PR #106543 (5 commits, final tree d2c4d908) by @Totoro-qaq.
publish_compression_child() fails closed on any non-automatic end stamp and
end_session() is first-stamp-wins, so a stale tui_close on a session the TUI
still routes turned every rotation into "compute the summary, then discard it"
(#106459). The host that still routes the session clears the stale explicit
close via SessionDB.reopen_if_explicitly_closed() before the turn starts;
publication never heals explicit closes. Review probes by @ehz0ah.
2026-09-10 03:04:51 -07:00
Teknium
7288a3cf05 Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime 2026-09-09 09:53:48 -07:00