Use the built-in /model picker's non-blocking catalog path, so no prefetch
thread pool runs outside the conversation's profile scope, and pass the
merged custom-provider view so a current endpoint defined under providers:
is not listed a second time as a synthetic custom row.
Both changes and their tests are patches from @BearHuddleston's review.
Keep raw endpoint matching and config inputs inside core; return detached presentation rows. Share profile-scoped resolution with the display accessor and persisted-pick fallback. Custom endpoint live probes are disabled to avoid config writes.
The developer guide said `hermes gateway ensure` never rewrites service definitions. Since this PR it re-renders the Windows launcher scripts the Scheduled Task and the Startup entry run, when they are the installer's own and their interpreter is gone, and leaves the task and the Startup entry unchanged. The paragraph now names that exception.
Reported by @jquesnelle on #152232.
- `BaseEnvironment.cleanup()` documents the contract teardown relies on:
raise only while the sandbox may still be live, since a raise skips
settling its background processes.
- The plugin guide matches it: settlement also runs when cleanup reports
the sandbox already gone, and `cleanup_stops_processes = True` means the
processes are gone for that env object (ended or unreachable).
- The reaper tests share one env-cache fixture (the two hand-copied blocks
skipped `_calls_in_flight`), the SSH-like double initialises its cleanup
count, and the settlement race patches `_finish_exited` via monkeypatch.
Teardown settles a closed env's background processes only when cleanup()
returned, so a cleanup that raises while the sandbox is still up leaves
them polling. Two backends could raise after the sandbox was already gone:
- Vercel: snapshot() stops the sandbox, then saving the snapshot id
(disk full) raised out of cleanup(), skipping the stop/close and leaving
the processes unsettled; the next poll tried to recreate a sandbox.
The save is now caught and logged, like a failed snapshot.
- Modal: terminate succeeded, then stopping the async worker could raise
on a closed loop before the sandbox handle was cleared. The handle is
dropped first and a worker-stop failure is logged.
Also: eviction logs the key it actually evicted (the image switch passed
no task id), the settlement tests no longer swap the registry lock, and
the terminal-environment plugin guide documents `cleanup_stops_processes`
for plugin backends whose jobs survive cleanup().
Codex/xAI encrypted reasoning and Claude signed thinking from earlier turns are
resent on every request and billed as input at the reasoning count the provider
reported for that turn (live A/B: gpt-5.6-sol 2,765 -> +2,767, grok-4.7 73 -> +76,
claude-opus-5.5 3,959 -> +3,959). Hermes priced the ciphertext at 0 (and Claude
at its ~1/4-size summary), so long reasoning-heavy sessions looked small:
compression found nothing to cut while the real bill sat over the window.
Each assistant row now records its response's reported reasoning count in
display_metadata, and the preflight trigger, tail-budget walk and native
Anthropic projection charge it. Compaction checkpoints still cost 0. Anthropic's
output_tokens_details.thinking_tokens is now read (it was always 0).
Fixes#125920
Drop the _running_agents_ts, _busy_ack_ts, _queued_events and
_pending_approvals legacy dict views from GatewayRunner. The stall
watchdog, shutdown flush/cleanup, /agents and the stale /approve-/deny
path now read SessionState directly (peek, never creating a row), and
tests set SessionState fields instead of the views.
browser-vault-plugin.md tells plugin authors to subclass LoginBackend, return VaultItemMeta and
subclass BrowserPageBackend, and ctx.register_login_backend / register_browser_page_backend accept
only instances of those classes, yet hermes plugins validate warned on all three imports. List them
name-only in plugin_api.json, regenerate public-api.md and drop their docs import seam entries.
LocalEnvironment stays a seam: it is the host implementation class, not a stable base.
#152125 bound shared-chat exec approvals to the requester (or
approvals.approvers / the platform admins), but the other prompts a chat
member can answer for someone else stayed open: another member could press
"Always" on a relay or native /reload-mcp confirmation and run its handler,
or answer the agent's clarify question (a choice button, "Other", or a typed
reply) for the person who asked.
Both prompts now record the same authority an exec approval records when
raised (tools.approval_context.prompt_authority: the turn's actor, else the
command's sender, plus approvals.approvers and the chat type), and every
chat answer path checks it through gateway.approval_actor.may_answer:
- relay prompt_response (gateway/relay/prompt_resolvers.prompt_refusal),
with the bot-owning profile's admins as for exec approvals;
- Telegram, Discord, Slack, WhatsApp Cloud and Feishu button callbacks
(slash_confirm_refusal / clarify_refusal, published on the plugin API
beside approval_refusal);
- the runner's typed-reply intercepts (/always, "2", free text after
"Other"); another member's text is routed as their own message.
A refused tap gets the existing "Only <name> can answer this approval."
and the prompt stays pending. A turn merged from two senders records no
requester, so only approvers and admins can answer, as for approvals.
The default approvers ["*"] keeps today's behaviour.
Supersedes the slash_confirm/clarify half of #72008, whose session-owner
mechanism no longer applies on main (main records the requester itself).
Co-authored-by: necoweb3 <65560494+necoweb3@users.noreply.github.com>
Greptile P2 (thread 4518419778): `_inject_session_context_env` read the session
ContextVars directly, skipping the mixed-turn check in `get_session_env`, so a
terminal / execute_code child started after another member folded into the turn
still got the opener in HERMES_SESSION_ACTOR_ID/_NAME. Both readers now go
through one `_bound_session_value`, so the child env carries an empty actor,
like the approval binding; `_UNSET` stripping is unchanged.
Local entry points for lanes whose workflows stay as they are: catalog-tests.yml is
grepped by tests/ci/test_classify_changes.py, and the others run before or without
setup-pm, so their steps cannot call just. Documents every new recipe.
Nine workflow steps still ran the exact command of an existing recipe:
the tests-js install in the install-e2e workflows (5), the Electron
runtime preparation and the full JS install in js-tests and the Windows
desktop attach E2E (2 each). They now call just js-install-tests,
just electron-runtime and just js-install.
A new desktop-build recipe replaces the `pnpm run build` steps of the
desktop E2E workflows. The contributing guides and the PR template name
just test, just test-all and just check.
`set windows-shell` is dropped: the manual marks it deprecated, and its
value was identical to `set shell`, which applies on Windows when no
Windows setting exists. Checked on a Windows host with just 1.59.0: both
forms run the same bash.
New recipes, each one line over the script CI already ran:
- `just docs-generate`: extract-skills.py, then generate-skill-docs.py.
- `just docs-check-generated`: the "committed skill docs match the
generator" block, moved verbatim into scripts/ci/check_generated_skill_docs.sh
(same `git add -N`, same diff paths, same ::error:: line and exit 1).
- `just docs-check-links`, `just docs-lint-diagrams`.
- `just docs-check`: generate, then the three checks, in CI's order.
docs-site-checks.yml calls docs-install, docs-generate, the three checks
and docs-build. deploy-site.yml calls docs-generate and docs-install; its
generate-skill-docs.py step moves up beside extract-skills.py because it
reads neither the plugin stars nor the plugin catalog the steps between
them write. Its full bilingual `npm run build`, staging and Pages deploy
steps stay inline. Python recipes run through scripts/hermes-python, which
uses the interpreter setup-pm exports as HERMES_PYTHON, as python3 did.
- `just test -v` passed the recipe's one-argument check and then
discovered all of tests/. The runner takes --require-paths, which refuses
a run naming no path or file list, and `just test` passes it.
- `just test-js` ran the TUI tests before @hermes/ink was built. It builds it
first, as the TUI's own `check` script does.
- `just lock` went through run-in-hermes-env, which syncs first; after a
pyproject.toml edit the sync refuses the stale uv.lock before pm lock runs.
scripts/relock.sh runs pm lock with the bootstrap Python, then syncs.
- `just setup` on Windows called pwsh, which a stock Windows does not have.
It uses powershell.exe, as activate.ps1's own caller does.
The justfile held per-workspace eslint recipes that duplicated lefthook and
ran whatever ruff was on PATH. It is now one menu of developer commands:
setup, check, fix, test, the JS workspace checks, the desktop and TUI dev
servers, the website build and the PM re-lock. Each recipe calls an existing
script or tool. Python recipes go through scripts/run-in-hermes-env, so they
work in a shell that never ran `source ./activate`.
`just test` requires at least one path, because scripts/run_tests.sh with no
arguments starts the full suite; `just test-all` is that explicit form.
`python -m scripts.code_health.ruff_runner ARGS` runs the pyproject-pinned ruff
that scripts/check resolves. `just fix` and the pre-commit `just ruff` recipe
use it, so the hook no longer depends on the ruff version on PATH.
lefthook.yml keeps its jobs, globs and roots; each job now runs `just ruff` or
`just eslint`. A shell without `just` on PATH fails the hook with "command not
found" rather than skipping the lint.
CONTRIBUTING.md, the developer guide, the package-management reference and the
desktop and TUI READMEs name the recipes beside the commands they run.
Carries #144799 rebased onto #151023's request-bound approval cards (one
squashed commit, because #151023 rewrote the same resolver, card and
adapter paths that #144799's eight commits patched one by one).
With `approvals.approvers: []`, an approval raised by one person's message
can only be answered by that person, a listed approver or a platform admin;
anyone else who taps Allow/Deny, reacts or sends /approve gets a private
"Only <name> can answer this approval." and the command stays pending. The
default stays `["*"]` (any admitted member answers), unchanged from main.
How it sits on #151023:
- tools/approval.py::resolve_gateway_approval_card takes #144799's
signature (actor_id, admin_ids, extra) with #151023's body: a tap with no
request id resolves nothing, and a Deny-only card can only deny.
- _ApprovalEntry carries both `authority` (#144799) and `card_deny_only`
(#151023).
- Discord, Matrix and Telegram card handlers check the requester first,
then settle through the request-bound resolver; the Telegram refusal
toast goes through #151004's expired-query-safe answer_callback.
- #144799's tests that seeded id-less cards and expected the oldest
request to settle now seed the real request id.
- Relayed approval answers check the bot-owning profile's admins;
identical approvals coalesce only under the same answerers.
Fixes#80281
Review finding (nit): the public-helper row for resolve_gateway_approval_card
did not say an id-less call resolves nothing or that every request starts
Deny-only until the base send_exec_approval lifts the mark.
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
(cherry picked from commit 8be788e276f85c32842faf82992fac1f1b778b7d)
Finding: "Relay _send_result drops partial-delivery info; no MAX_SPLIT_MESSAGES via relay"
(P3, review #6723383713).
The connector splits a long send, and the relay `send` result carries only success /
message_id / error: no field for a dropped or capped chunk (Discord's message-count cap
included). So a relayed full-command send counts as proof only when the command fits one
max_message_length message; a longer one leaves the approval card Deny-only. The wire
format is unchanged; the contract doc says why.
(cherry picked from commit 48b524ea5020c59e0b29091ccde4d4de4a33aba9)
Review finding: "Telegram platform hint recommends clarify even when clarify
is unavailable (cron / clarify-disabled)". The clarify sentence was part of
PLATFORM_HINT, so cron jobs delivering to Telegram (cron always disables the
clarify toolset) and profiles with clarify disabled were told to call a tool
they do not have.
PlatformEntry gains platform_hint_tool_notes ({tool: sentence}); the prompt
builder appends a note only when that tool is in the session's
valid_tool_names, which is fixed when the system prompt is built, so the
cached prefix stays stable for the session. Telegram moves its clarify
sentence there. The stock Telegram prompt-surface render is byte-identical
(that surface has clarify).
(cherry picked from commit bc29be1ee75cc4c8ca8a156166a5cd5f7e2b2168)
Review follow-ups on the observe-mode actor fix:
- HERMES_SESSION_USER_ID stays the session ROUTE (kanban notify, cron, send_message
rebuild delivery targets from it, and in a shared chat it is empty); the trusted
sender of the turn is HERMES_SESSION_ACTOR_ID / _NAME (defaults to the route user).
- Text and photo batch keys of a sender-less shared source carry the sender, so two
members addressing the bot in one batch window are two turns with their own actor.
- build_session_context gets the event positionally (existing stubs take *args).
- e2e marker: pytest.mark.platforms("posix").
Review finding "adding-platform-adapters.md stale after the move": the guide
still said built-in platforms like Telegram ship REST helpers in
tools/send_message_tool.py. Telegram's out-of-process sender is now
plugins/platforms/telegram/standalone.py::standalone_send, reached through the
same standalone_sender_fn hook the guide documents.
Greptile thread "Existing Telegram callbacks fail" / review finding "notify
forwarded unconditionally to telegram standalone_sender_fn".
_send_to_platform handed every Telegram standalone_sender_fn notify=..., so a
user plugin re-registering telegram with the documented signature (no notify)
failed every send with "unexpected keyword argument 'notify'".
send_message_senders._optional_sender_kwargs forwards an optional keyword only
when the sender declares it by name or takes **kwargs (inspect.signature, cached
per callable; an uninspectable callable gets it, as documented). The developer
guide and PlatformEntry comment document notify as optional.
Independent review round:
- P2: post_curator_run fires on `hermes curator run --dry-run` with no way to tell;
the payload now carries dry_run (documented in hooks.md + plugins guide).
- P3: _delivery_manager joined background discovery on every hook call, so a plugin
whose register() hangs cost every invoke_hook/has_hook another 30s; a join that
times out once is not repeated (the mid-discovery race fix is kept).
- P3: hermes hooks test post_curator_run sent the generic session payload; it now
sends the real shape (run_dir, run_json_path, report_md_path, dry_run).
Fires once per curator pass, after the per-run report directory
(run.json + REPORT.md) is fully written, with the report paths in the
payload. Goes through the standard lifecycle hook surface
(hermes_cli.lifecycle.invoke_hook), so Python plugins and shell-script hooks both
receive it with no extra wiring, and per-callback error isolation comes
for free.
Lets multi-profile governance layers (profile routing, archival
overrides, audit logging) react to curator output without polling
logs/curator/. Observer-only: return values are ignored, and a raising
callback never breaks the curator pass.
Kwargs: run_dir, run_json_path, report_md_path.
Follow-up to the discussion on #43113, scoped down to the hook event
suggested there.
Rebased onto main by the maintainers: fired through hermes_cli.lifecycle
(first-party observers, then plugins) without an extra wrapper, documented
in the hooks reference, tests trimmed to the two behaviour contracts.
Inside a workspace folder npm treats the folder as its own project and
resolves it from the registry, past pnpm-workspace.yaml's overrides and
release-age gate; the root preinstall never runs there, and
--ignore-scripts skips it at the root. Each workspace folder and the root
now carry an .npmrc with engine-strict=true and an engines.npm that no
npm satisfies. npm checks engines only when it builds a dependency tree,
so install (with --ignore-scripts, --package-lock-only or --force), ci,
update, dedupe, uninstall and link fail with EBADENGINE on npm 10 to 12,
while npx, npm exec and npm run work. pnpm reads neither.
The root refusal needs the root devEngines gone (npm skips root engines
while it is set), so this builds on the single-source pnpm pin. The root
.npmrc also makes npx strict about engines anywhere in the checkout.
npm-shrinkwrap.json joins package-lock.json in .gitignore.
On a turn with an image, Hermes appends the injected context (recalled
memory, pre_llm_call and gateway notes) to the message as a text part
(#71998, bb87e6abce). The next turn's previous_message, added in
#150569, read that part back as part of the ask. The stored row keeps
the parts as one flattened string, so after a restart nothing in content
separates the ask from the injection.
The turn now records its ask in display_metadata under typed_ask before
the first part is appended. That is a persistence-only field, so it
never reaches the wire. The ask is the human-authored view of what the
row will persist (durable_user_row_content, so a TUI list override's
dropped API-only parts stay out), with a todo snapshot that turn-start
compaction folded onto the turn stripped, so a turn already wrapped in a
summary still stamps just the ask. previous_message reads the stamp and
normalises it the same way as unstamped text (gateway timestamp, memory
fence), and gateway replay carries that one key through
(replay_metadata_fields, next to the scaffolding flags), so a resumed
gateway, CLI and TUI all see the clean ask. A row written before this
change falls back to stripping the memory fence; its notes stay, and the
docs say so.
The in-place backfill writes the stamp (only that key) with the part,
also when only gateway notes landed on the parts. That row can exist
before the turn (a TUI submit row) and take a reaction meanwhile, so the
row-addressed rewrite (set_user_message_content, direct and through the
runtime worker) now JSON-merge-patches the given metadata into the row's
instead of replacing it (a null deletes a key); the veto passes
typed_ask: null to remove a backfilled stamp. Its existing api_content
clear is unchanged and only ever sees list rows here, which carry no
string sidecar.
A later compaction that only wraps the row keeps the stamp, including
when the next compaction restates the still-unanswered turn on its own
(copied whole, or rebuilt from the task text of an earlier
restatement).
Any fold (record_absorbed_message, the merge witness every host fold
calls: repair, micro-compaction, a summary carrier absorbing the
in-flight turn, an anchor led into a scaffolding turn) that brings
content drops it, because the row then holds more than that one ask; an
empty turn folded in changes nothing, so the stamp stays. Such a row
reads as it does on main, after a restart too: the transcript flush
rewrites only the columns a turn owns, keeping metadata other writers
add, so when it writes new content for a row whose live dict no longer
carries the stamp it removes that one key (a reaction stays), and hands
the row's metadata back as written. A pre_llm_call veto and the
expired-confirmation redaction drop the stamp too, keeping vetoed or
redacted text away from providers.
The display_metadata set/read idiom this would copy again in
message_metadata.py becomes two private helpers, which stamp_data_use,
mark_inflight_restatement and withheld_prompt_text there now use too.
Reported by Greptile on #150569.
The memory-provider developer guide lists on_turn_start's other keywords but
not previous_message, and plugin authors work from that page. It now says what
the value is (the person's last message, secret-scrubbed, "" on a first or
image-only turn), which known runtime rows and /steer messages are skipped,
that it is best-effort (a replayed notice without a known prefix can come
through), why a resumed process needs it, and that older Hermes omits it. The
MemoryProvider docstring says the same. _memory_turn_start_and_prefetch's one
caller always passes both values, so they are required, and its docstring no
longer repeats the provider-facing rationale.
Delete native/fts5_cjk/ and the messages_fts_cjk integration: the
tokenizer loader, the sessions.cjk_fts key and its HERMES_CJK_FTS bridge,
HERMES_FTS5_CJK_SO, the cjk table and triggers, its stale breadcrumb,
quarantine, backfill and reset paths, and the cjk_unicode61 cases in the
FTS error classifiers and the repair probe.
No installer, package or image ever shipped libfts5_cjk.so, so the loader
returned False on every install and CJK queries already took the trigram
and LIKE routes. Those routes are unchanged. The integration had about
40 code sites that every FTS change had to keep correct, and its
triggers made writers that never load the tokenizer (the sqlite3 CLI)
fail with "no such tokenizer: cjk_unicode61".
A store that built the index is cleaned up on the next read-write open
and at the start of the repair health probe: drop the three triggers
first so outside writers work again, then the source view, the
fts_cjk_* markers and the table. SQLite before 3.47 cannot drop an FTS5
table whose tokenizer is not loaded; there the schema row is deleted
under writable_schema and the shadow tables are dropped. One warning
says the .so can be deleted. The drop does nothing when no
messages_fts_cjk object exists, so a second open is a no-op.
BREAKING CHANGE: sessions.cjk_fts, HERMES_CJK_FTS and HERMES_FTS5_CJK_SO
no longer have an effect. 1-2 character CJK terms use the LIKE scan on
every install.
The Yuanbao gateway platform (plugins/platforms/yuanbao) and its yb_* tools
(tools/yuanbao_tools.py) now ship as the `yuanbao` plugin in
NousResearch/hermes-labs-plugins, a community-tier, Nous-built, unsupported
plugin. Platform name, toolset name (`yuanbao`), tool names, env vars,
config keys (platforms.yuanbao.*, legacy gateway.yuanbao) and
YUANBAO_HOME_CHANNEL are unchanged.
Migration: a LEFT_CORE row (hermes_cli/left_core_migration.py) installs the
catalog plugin for every home core ran Yuanbao for: YUANBAO_APP_ID (or the
legacy YUANBAO_APP_KEY) plus YUANBAO_APP_SECRET in its dotenv layers (the
process env too for the launch home), platforms.yuanbao on through the
gateway's own config loaders, or the yuanbao / hermes-yuanbao toolset
selected for another platform. The shipped `yuanbao: [hermes-yuanbao]`
platform_toolsets row is not use. The row keeps the yb_* tools off on every
platform whose core composite never carried them, keeps YUANBAO_APP_SECRET
stripped from children (secret_env) and the other YUANBAO_* settings on the
provider blocklist (private_env) while the plugin is absent, and its notice
carries the unsupported sentence.
Core wiring removed: toolsets (yuanbao, hermes-yuanbao, the hermes-gateway
include), Platform.YUANBAO (Platform('yuanbao') resolves once the plugin
registers it), the platform/toolset menu rows, the TUI special case, the
static session note (the plugin's platform_hint carries it), env/config-key
lists, webhook deliver set, startup allowlist list, locales strings and
yuanbao-only tests. Telemetry enum values stay.
When a commit moves or deletes a package, git removes its tracked files
but keeps the directory while __pycache__ is still in it. The bytecode
sweep then removes __pycache__ and leaves the directory empty. An empty
directory at an old package path imports as an empty namespace package,
which wins over the editable finder and hides the package at its new
location: `from pkg.mod import f` fails with "No module named pkg.mod".
Both sweeps (the update completion and the launch-time sweep after a
manual pull) now diff the commit recorded in .bytecode-fingerprint
against HEAD, take the parent directories of every dropped file, and
rmdir them deepest first after the bytecode is gone. rmdir only removes
an empty directory, so one that still holds a user's file or ignored
state is kept. No recorded commit means nothing is removed.
The pre-move syntax preflight and the post-move check skipped any listed
startup file the target did not contain. A change that moved or dropped
one of those files therefore passed both checks, and the next launch
failed on the import.
The list of startup files now lives in the tree it describes:
pyproject.toml [tool.hermes] update-startup-files. Both checks read the
target's own list, so a commit that moves a startup file updates its
path there and updates to it are judged by the new path. A declared
file the target lacks refuses the update before anything moves, and
rolls the pull back after it.
A target that declares no list (every release before this one) is still
judged by the running updater's list with absent files skipped, so
rollbacks and channel switches to older releases keep working: releases
up to v2026.9.24 lack five of the nineteen listed files.
The post-pull guard now always goes through tree_syntax_error, which
already chose the interpreter by requires-python, so the separate
same-interpreter path (_validate_critical_files_syntax) is removed.
Past sessions.max_resume_messages a rotated lineage pages only its current
segment, and a newest-first cursor from that read held no segment. Once a
compaction rotated the tip to a new segment, the old key was looked up in
the new one, the walk ended with an empty page and reset: false, and the
reader kept the old segment's rows. A tip-only newest-first cursor now
holds its segment; when the current segment differs, the reply starts
again from the newest page with reset: true. Whole-lineage newest-first
cursors are unchanged (they page across rotations inside the lineage). A
tip-only cursor issued before this change has no segment, so it resets
once, as an unscoped t3 cursor does.
compaction_summary took the compacted-message count from the first match
over the whole summary, before the quoted user messages were cut, so a
quoted message spelling out the footer's sentence won. The count now comes
from the Context Recovery footer when there is one, else from the summary
with the quotes cut.
Contract doc and gateway-local-sessions.md describe the new reset; the
gateway contract outputs are regenerated.
Reported by Greptile in review.
Two ways a poller could end up holding something other than what a fresh read shows:
- A rewrite (a queued prompt's prologue rewriting its user row with set_user_message_content)
committing between the display-index backfill and the read snapshot left the row without a
display slot. The page skipped it while the cursor stored the rewrite's revision, and the next
poll's backfill moved no cursor counter, so the row never came back. The read now checks the
index inside the snapshot (SessionDB.transcript_display_index_complete); when a slot is missing
it leaves the snapshot, backfills and reads again. When every attempt finds a slot missing the
reply is reset: true, as an unproven read already is.
- Appends that take a rotated lineage past sessions.max_resume_messages switch the read from the
whole lineage to the current segment, but the cursor did not record which one its page read, so
a poller kept the ancestor rows with reset: false. The cursor now holds the scope (format t4);
a read in the other scope answers reset: true in either order. A t3 cursor from an earlier head
of this unreleased read is still accepted and resets.
Regression tests for both suggested by @BearHuddleston in review (appended verbatim).
Review fixes for session.transcript:
- A store without a pooled reader (not WAL, a read-only handle, a reader
that failed to open, the pool's ceiling) pinned nothing, and its
consistency check was always true: a row deleted between the page read
and the cursor-state read stayed in the client forever (reset: false).
transcript_read_snapshot now checks there that no write landed in the
database during the block (_write_generation: the writer connection, its
total_changes for this process's writes and PRAGMA data_version for
every other connection's commits), holding no lock across the block.
_poll reads once more when one did; when the retry also overlaps a
write, the reply is reset: true with the first page and a cursor state
no transcript has, so the next poll resets again. The pooled path is
unchanged. The yielded check gains .pinned.
- page_handoffs deduplicated a handoff only within the current window, so
two carriers holding the same uid-less handoff each showed it once the
window moved past the first (also limit 1, oldest order). A handoff is
now shown before the first row in the whole transcript that holds it: a
rotated lineage checks the rows before the window it already read; one
segment asks the new SessionDB.transcript_handoffs_shown_before for the
display rows before the window's first slot.
Tests: tests/gateway/test_session_transcript_handoff_owner.py (seeded
transcripts with identical uid-less handoffs on several carriers, re-wraps,
in-place compactions and rotations: every limit 1-5, both orders, equals
the full read; two identical uid-less carriers, limit 1 and 2, both
orders). tests/gateway/test_session_transcript_snapshot.py: append-then-
clear and delete-during-page, each pooled and without a pooled reader; a
read that never settles resets twice, then converges.
tests/hermes_state/test_transcript_read_snapshot.py: without a pooled
reader a write from this process or another connection makes the block
inconsistent.
Review fixes for session.transcript (all behind SessionDB methods now):
- One read generation per poll. The cursor check, the page and the state the
next cursor stores are read in one read transaction
(SessionDB.transcript_read_snapshot: _read_ctx hands the thread's pinned
pooled reader to every nested read). Before, a row appended after the poll
started could land on the page and be deleted (clear_messages moves neither
the inactive count nor transcript_revision) before the state was sampled;
the cursor then certified the post-deletion state while the reader held the
deleted row, and later polls answered reset: false forever. A store without
a pooled reader (not WAL, read-only, pool ceiling) is not pinned, so a write
from inside can never wait on its own lock.
- transcript_cursor_state's live count spans the whole displayed lineage: the
segment's own rows up to the cursor, plus every live row of its earlier
segments. Deleting an earlier segment's rows now resets a poller, as its
reactions already did.
- limit bounds the rows sent, compaction rows included. A row's handoffs and
the row can fall on two pages; the cursor then names the row and how many
of its group were sent (a third key part), so no handoff is dropped or
sent twice, both orders, several handoffs on one carrier included.
- Storage interface: every new store read is a narrowly named SessionDB method
in one module, hermes_state_stored_reads.py (was
hermes_state_transcript_cursor.py; hermes_state_display_set.py folds in as
_display_set / _with_removed_identities, the worker calls the latter as on
main): transcript_read_snapshot, transcript_segment_page (with the cursor
slot and durable-id lookups), transcript_tool_calls_before,
sessions_in_workspace, picker_session_facts, session_current_segments,
subagent_session_ids. get_messages and _fetch_conversation_rows gain their
port lines. The gateway and tool modules keep their function names.
Tests: tests/gateway/test_session_transcript_snapshot.py (append+delete during
a page read; an earlier segment's deletion and, separately, its reaction;
limit 1 and 2 across a carrier with two handoffs, oldest and latest) and
tests/hermes_state/test_transcript_read_snapshot.py (one generation inside a
snapshot; a DELETE-journal store is not pinned). One consistency test's first
page now ends at the handoff, which counts toward limit.
session.transcript becomes the one stored-transcript read; session.compactions
and subagent.transcript never ship.
- Forward polling: an oldest-order cursor is never null. It also holds the
segment it read and transcript_cursor_state of the rows it covered; while
both hold, the next read continues after it (reset: false, only appends).
An in-place compaction, a rotation, a rewind, or a rewrite or deletion of a
covered row answers reset: true from the first page. The stored state is
read between two snapshots around the page read, and a non-append change in
between reads the page again. A page is empty only when caught up (windows
that project to nothing are read past). Latest order keeps its relocating
cursor and ends with a null cursor.
- An oldest-order page continues at the next display slot instead of
filtering by durable id, which is not monotonic in display order (a
handoff's new row sits before the carried copies of older messages).
- Every row carries row_kind: "message" (the session.resume display row) or
"compaction" (a handoff at its position: role system, the readable summary
as text, compacted_messages, timestamp, row_id). Older handoffs on earlier
copies of a re-wrapped or unwrapped carrier still show, each once
(SessionDB.transcript_handoff_rows).
- subagent_id reads a delegated child of session_id with the ownership rule
from #140477 (running: the parent's live roster; finished: the _subagent_id
marker and a lineage of delegate-child or compression hops). The reply adds
subagent_id, available, running and child_session_id; a foreign or unknown
child is available: false with no rows, a null cursor and reset: true.
- runtime.describe advertises session-transcript-v1 and
session-list-picker-v1.
- Contracts, OpenRPC/TS and the serve handler ledger regenerated; docs
updated. Storage-interface port names on every new or changed SessionDB
method.
Tests: the stored-read suites move to the one method (resets where a
compaction lands between pages, handoffs as rows); new poll tests drive
appends, compaction, rotation, rewind and rewrites between polls, plus a
seeded random sequence checked against a fresh read after every poll. The
subagent ownership, lineage, multiplex-scope and live E2E tests are adapted
from #140477 to session.transcript with subagent_id.
Fourth review round on session.transcript:
- The cursor's slot lookup OR'd a primary-key match with an identity match, so SQLite walked the
whole segment on every page (a full walk of 30k rows at limit 100 took 2.9 s). It is now one
primary-key read plus an equality read on idx_messages_display_identity (0.6 s).
- The slot lookup, the page read and the durable-id lookup ran as separate statements, so a
compaction committing between them could apply an old boundary to a new generation and skip a
message. They now run in one explicit read transaction (still one read context).
- A reply a later compaction wraps in a summary carrier changes identity; the slot and durable-id
lookups now also follow a carrier's message_uid (carriers only, so a pruned tool result keeps its
own identity), so oldest-first paging no longer shows it twice.
- Tool-result context paired results with every older call of a reused provider id, and a later call
on the page hid an opening result's call. Each result is now paired with its own occurrence: its
stored tool-call uid (tool_call_uids maps id to uid), else the nearest earlier call.
- Cursor ints outside SQLite's signed 64-bit range raised OverflowError at binding; they are now
invalid_params.
- SQL-paged rows skipped the conversation normalization a resume applies; they now go through
_rows_to_conversation with the display row before the page as context, so a background-review
harness prompt and its curator reply split across pages are both dropped, and stale [memory]
markers stay blank. The cursor advances past rows the normalization drops at the page edge.
Third review round on the stored reads:
- session.compactions resolved the lineage inside its own read context. Without the WAL pool a read
runs on the writer under SessionDB._lock, which is not reentrant, so that nested read deadlocked
(the 6bb377a51d boot wedge). The lineage is read first; every new read path is checked by a
test that fails on any nested read.
- A row too large for a page alone was only clipped in text/content and measured escaped but cut by
characters. It now keeps its role, time and ids plus the head of its text, sized by its serialized
JSON, and carries truncated.
- Halving a page could leave a tool call on one page and its results on the next, where they lost
their name and arguments. Cuts fall between tool groups, and results whose call sits on another
page are projected with that call (found on the assistant-calls index) as unseen context.
- Newest-first paging resumed at the cursor message's old display slot, so a compaction that
carried it moved its copy above the cursor and the next page skipped the message before it. The
keyset now starts at the message's current slot, in both orders.
- Compaction copies collapse by occurrence (message_uid and stored content), never by the cleaned
summary text, so two compactions with the same prose are both listed.
Review of the first cut found a hole and several costs:
- Auth: an old local row was checked on the id the caller sent, then its tip's lineage was read, so
transcript(root) showed a tip another principal owns. The read now judges the compression tip, as
the stored list and resume do.
- Cost: every page re-read and deduplicated the whole lineage (0.4-0.8 s a page at 30k rows, a
full walk ~127 s). A single-segment conversation is now keyset-paged on its display index (a few ms
a page, full walk 0.6 s); a rotated lineage is deduplicated whole only under
sessions.max_resume_messages, and past it only the current segment is paged.
- Size: a page stops at 2 MiB of projected JSON (one larger row is cut and marked truncated) and
images read [image] unless inline_images is asked, so no page reaches the 8 MiB client frame.
- Cursor: bound to the session and order, length-capped before decoding, keyed by each message's
first durable row with a carried tail's superseded original included, so a boundary inside the
carried tail no longer repeats a row. order: latest reads the newest page first.
- session.compactions reads the handoff rows themselves (live, archived, or superseded by a later
compaction that carried or unwrapped them) instead of the display dedupe, which lost a handoff
whose carrier a later compaction reused. Summaries drop the model-facing parts and carry
compacted_messages.
- session.list picker fields are opt-in (picker: true), one batched read (receipt targets in SQL,
tip walks on the same connection, one indexed probe per segment for the last reply, a pure
handoff skipped); the stored feed reuses list_sessions_rich's columns. The live poll is back to
its batched reads.
- The reads run on the socket's concurrent read lane. get_messages_as_conversation keeps its
keywords (RuntimeSessionStore parity); the lineage path composes the store's own steps.
A gateway client's session picker had to read state.db itself: session.list carried no folder,
activity or last reply, session.history and session.events.since serve only an attached session,
and a session.resume subscribes the caller. hermes-tern copied Hermes' listing, lineage and
compaction rules into Node to work around it.
session.list (both scopes) now takes a `workspace` filter (hermes -c's workspace_key rule, the
same SQL clause on the stored feed) and returns the current segment's preview, last_reply, cwd,
git_branch, workspace, last_active_at and pinned, in one batched read per page.
session.transcript pages a stored conversation's display rows across its compression lineage:
the same deduped display read and display_messages projection session.resume uses. Its opaque
cursor is keyed by each logical message's first stored row (now exposed by the one display
dedupe), so a page boundary holds across later compactions and rotations.
session.compactions returns the handoff summaries the display rows leave out, without the
model-facing preamble (compaction_summary_text).
Both reads use session.resume's own session:read authorization and build no agent and subscribe
nobody; an old CLI/TUI/GUI row is read by the stored feed's own rule (legacy_readable, extracted
from stored_picker_sessions) and never adopted.
Closes#150091