A pre_llm_call callback (Python plugin or shell hook) may now return
{"action": "block", "message": "..."} to veto the turn: no model call is made,
the message is the reply the user sees and the transcript keeps a normal
user -> assistant pair, and the result carries
turn_exit_reason=blocked_by_plugin_pre_llm_call. This is the supported seam for
DLP / privacy / policy plugins that previously had to patch core (#57364).
The vetoed prompt also stays on the host for that turn: no session titling call,
no external-memory prefetch or sync, no background memory review. Its user row
gets an api_content placeholder for the main-loop replay. That alone does not
keep the prompt out of later turns (compaction, session_search and memory
providers read the row's content); the next commit stores the placeholder as
the content.
First valid block wins; a Python block without a message is ignored (same as
pre_tool_call). Shell hooks accept both the Hermes {"action": "block"} and the
{"decision": "block", "reason": ...} shapes, mirroring pre_tool_call.
Independent review of the hold_stream feature found four paths that still
let the untransformed reply or commentary reach the user:
- History loads showed held commentary. The tool-call assistant row of a
held turn is now typed display_kind="hidden" before its first flush
(withhold_held_commentary), so TUI/Desktop display_projection, the
dashboard and classic CLI resume skip it. display_kind never reaches the
wire: the model's context and cached prefix are unchanged (test replays
the resumed session and compares the request bytes). The TUI projection
still labels the hidden row's tool cards from its calls. Codex held turns
type their earlier agentMessages hidden the same way.
- A plugin reload mid-turn could empty the hook registry before the final
transform. The held turn now snapshots its transform_llm_output callbacks
together with the hold decision under the discovery lock
(held_stream_transforms) and runs that snapshot at the final. If no
callback rewrote and one raised or timed out, the user gets a fixed
"reply withheld" notice instead of the original (fail closed).
- Classic CLI replay-gap recovery painted and spoke pre_transform_response.
A held turn's result (generic and codex) no longer carries the original
at all (public_pre_transform), so receipts, recovery and post-stream
suffix painting only ever see the rewrite.
- Codex error-after-text returned the raw agentMessage. The codex reply is
now transformed whenever it has text, also when the turn errored (and,
when held, when interrupted).
Same class, also fixed: the end-of-stream scrubber flush recorded a held
tail as streamed text (an interrupted turn could return it as an
untransformed partial final), and quiet-mode CLI printed held commentary
via _vprint.
reload-plugins empties the ownership ledger before plugins re-register;
a turn starting in that window read holds_stream()=False and streamed
raw text the holding plugin must rewrite. Read the ledger under the
discovery lock so the turn sees the settled registration set.
Review: https://github.com/NousResearch/hermes-agent/pull/144266#discussion_r4369515508
A plugin that rewrites the reply (redaction, policy filters) can declare that it
must see the reply before the user does. The declaration rides the hook's
registration handle, so it lives exactly as long as the registration and is
scoped to the plugin manager of the profile that loaded it; stream_held()
answers for the active profile. Plain transform registrations keep streaming
(opt-in), and the flag on any other hook is ignored with a warning. The memory-provider hook proxy and the
`plugins validate` probe stub accept the keyword so a declaring plugin loads
through every registration seam.
Shape and seams salvaged from #102481 (mutates= on register_hook, the memory
proxy and validate-stub forwarding).
Co-authored-by: Halldrix <12357213+Halldrix@users.noreply.github.com>
Key the bounded dispatcher's running-callback gate by session_id, so one
session's slow callback no longer skips another session's compaction. Fire the
gateway /compress hook in a finally after the receipt commits, so a failed
runtime projection cannot swallow it; exact retries (applied=False) still
never refire. Review findings from Greptile on #141017.
The salvaged hook fired from ContextCompressor.compress(), which is not where
a compaction commits: compress_context can still refuse or roll back the
candidate (snapshot stale, commit fence, split failure), the gateway's
/compress runs its own compressor and commits elsewhere, and Codex-native,
micro-compaction and proactive-prune rewrites never call compress() at all.
session_id was also the compressor's bound id, which is stale after rotation.
Fire it from the compaction-record seam (agent/compaction_events.py) that
already sees exactly one committed record per rewrite on every agent path,
and from the gateway session.mutate compress commit. Payload: session_id (the
session holding the compacted transcript), old_session_id, kind, reason,
before/after token estimates, messages_removed. Bounded by
plugins.hook_callback_timeout, since it runs inside the commit window.
Tests trimmed to one invariant (fires once per committed compaction, never
for an aborted one, raising plugin isolated); docs in hooks.md and the
plugin guide.
After the cutover no local surface fired pre_command where the command runs.
slash.exec and command.dispatch (classic CLI forwards, Ink TUI, Desktop) never
fired it, and the classic CLI fired it from its own second copy of the plugin.
- The gateway fires pre_command for every recognized command a local session
runs, under the session's profile: before the handler for commands it runs
itself (slash.exec, command.dispatch; an accepted TUI read fires once inside
the read path), and for commands the classic CLI runs in its own process
through the new command.observe (plain data: the command as typed and its
arguments). command.observe replies first, so the CLI never waits on a
plugin. The hook arguments keep main's values: surface and platform "cli"
on every local surface, session_key the session id.
- It fires only for commands that run. A busy rejection or a named refusal
fires nothing; during a turn it fires when the busy dispatcher accepts the
command, so a refused /goal, /loop or empty /queue or /steer fires nothing
either. Every command that does run mid-turn fires, as main's CLI did,
except messaging's escape hatches (/stop and the approval controls).
- Each delivery waits out its callback on its own thread, never the shared
executor, with at most one delivery in flight per session: one session's
deliveries fire in order and a slow callback never holds up another
session's. The hook dispatcher's existing bounds apply
(plugins.hook_callback_timeout and its abandoned-worker cap), and with
plugins.isolation: host the hook runs in the plugin host. pre_command takes
that bounded path everywhere, so off the gateway its callbacks also run on a
worker thread.
- On a gateway session the classic CLI loads no plugin code. It reads skills,
plugin commands and plugin toolsets from the gateway (commands.catalog,
scoped to the session's own folder, and plugins.list) for /help, skill
dispatch and completion, /tools and the status and banner fallbacks. -s and
skills.auto_load are rendered in the gateway, and /reload-skills and
/skills install rescan there and drop the CLI's cached catalog. These reads
are cached per gateway life and never served once the connection has hung
up. The "Unknown toolsets" warning comes from the gateway (a new
unknown_toolsets field when the session opens). An older gateway without
command.observe gets one named notice, and nothing fires locally.
- The canonical gateway connection serves plugins.list for its profile:
loaded plugins with tool/hook/command counts, load error, toolsets and
portable MCP server names (optional fields added to the contract; TS and
OpenRPC regenerated). On a gateway session the CLI's /plugins reads it
instead of this process's plugin manager. Off the gateway the in-process
paths are unchanged.
Key-less inject_message (B2-11), which the classic CLI's own plugin copy
used to serve, is handled in the next commit.
Refs #134889 (PLG-7)
Refs #139523
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); 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). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
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).
main's ratchet caps every >2000-line facade at its main value; the PR grew seven.
- config.py: `hermes config show` rendering -> hermes_cli/config_show.py (reads config names via
the module at call time so hermes_cli.config.<name> patch seams hold).
- backup.py: the cron prompt-field safety net -> hermes_cli/backup_cron_prompts.py; also drops a
dead duplicate _PROTECTED_CONFIG_PATHS left by an earlier merge (the later definition won).
restore_config_model_settings_* stay in backup: they are on the frozen old-updater surface.
- profiles.py: Honcho host migration on rename -> hermes_cli/profiles_honcho.py.
- plugins.py: resolve_plugin_command_result -> plugins_dispatch.py (re-exported from plugins,
the public import path for cli/tui_gateway/plugins).
- main.py: --query-file reader -> hermes_cli/main_query_file.py.
- kanban_db.py: worker-context section renderers (_ctx_* + caps) -> hermes_cli/kanban_db_context.py;
build_worker_context stays in kanban_db.
- config_defaults.py: drop the blank line the gateway block gained.
Patch-target retargets (moved symbols only): test_plugins.py (asyncio / await timeout now in
plugins_dispatch), test_managed_scope_surfacing.py (show_config import), test_backup.py
(restore_cron_prompt_fields_if_degraded import).
(cherry picked from commit 4079d422e0c2283c500c16885e959f5c170eb6cf)
Teknium ruled the post-admission consumer hook (#129958) must fail OPEN, so
reshape the salvaged implementation into one small seam:
- `{"action": "handled", "reply": str|None}` is the only decisive result;
None, any other value, a raising callback or a timeout runs the ordinary
agent turn. One buggy plugin can no longer blackhole every inbound
message on a profile (the cherry-picked version failed closed on any
exception or malformed return from ANY registered callback).
- Fire under the message's ROUTED profile scope. The receiving bot's
handler binds the transport home so auth can read its .env; when that
bot serves a chat for another profile, the ambient scope at the hook was
the wrong profile and that profile's consumers never ran.
- Snapshot-only payload (session_key, platform, source dict, message_id,
text): no live gateway runner / session store handles, so the plugin
isolation host needs no HOST_DEGRADED_HOOKS entry.
- Bounded by plugins.hook_callback_timeout (fail-open) instead of the
fail-closed policy-hook set; the required-but-discarded receipt, alias
table, destination snapshot/restore machinery and hard-coded English
failure notice are gone.
- Tests trimmed to three invariants through the real _handle_message and
real plugin dispatch: consume path, raise path proceeds, routed profile
scope bound.
Keep the contributors' fix (each llm_request / tool_request callback sees
the previous accepted rewrite; each gets its own copy of the payload and of
the original_* snapshot) in PluginManager.invoke_middleware, which stays the
single plugin-failure boundary, and drop the rest:
- the ~90-line iterative container walker in _safe_copy. It only runs when
deepcopy fails (an opaque leaf in the request); main's shallow-copy
fallback stays.
- the original_* freeze/copy in _run_execution_chain. Execution middleware
already composes via next_call; that was defensive isolation, not chaining.
- the second copy of an accepted return inside invoke_middleware
(_apply_request_chain already copies it).
- tests/hermes_cli/test_middleware_isolation.py and the test_plugins.py
additions; tests/hermes_cli/test_plugins_middleware_chain.py holds two
invariant tests (composition, in-place-mutation isolation), each over
both request kinds. test_plugins.py is over its size cap, so it gains
nothing.
_apply_request_chain fanned every llm_request / tool_request callback out
over the ORIGINAL payload and kept only the last result, so a second
plugin's rewrite silently dropped the first's. A new
PluginManager.invoke_middleware_chain threads each dict result under the
payload key into the next callback; invoke_middleware is unchanged, and a
manager without the new entry point falls back to the flat fan-out.
Test: test_request_middleware_chains_each_callback_onto_the_previous_result
— red before (payload missing {'a': True}), green after. Touched files:
178 run, 3 failed — the same 3 fail on unmodified upstream/main 5bb2be179d.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Auxiliary LLM calls (titling, compression, MoA advisors/aggregator, vision,
approval, ...) never reached any plugin hook: hook-based observability and
cost plugins were structurally blind to them. Teknium's ruling on #79733:
NEW events rather than reusing the turn-scoped pre/post_api_request pair,
so existing subscribers keep their per-turn semantics.
- agent/auxiliary_hooks.py (new sibling): builds the pre_api_request /
post_api_request payload shape plus `aux_task`, `api_request_id`
(`aux-...`, shared by every attempt of one logical call), `retry_count`,
`streaming`, parent-turn `session_id`/`task_id`/`turn_id` when a main
turn is in flight; fail-open (a raising/hung subscriber is logged and
the aux task proceeds); post carries `error`/`error_type` on failure.
- agent/auxiliary_client.py: the three relay funnels every physical
attempt shares (_relay_sync_completion / _relay_async_completion /
_relay_sync_stream) run under the hook pair — retries and fallbacks
included. Main-loop *_api_request events do not fire for aux calls.
- Catalogue: VALID_HOOKS, bounded-timeout hook set, `hermes hooks test`
sample payloads, hooks.md / plugins index / observer-hooks / plugins.md
tables, agent + plugins AGENTS.md.
- tests/agent/test_auxiliary_hooks.py: 2 invariants (pair fires with
aux_task and no api_request events; raising subscriber never breaks
the call). First is red on origin/main.
Supersedes #32416 (@zrmnelson), #68060 (@JonZal), #77518 (@hsy5571615),
#79826 (@webtecnica) — their relay-boundary placement, usage
normalisation and fail-open policy shaped this implementation.
Co-authored-by: zrmnelson <zacharynelson1@gmail.com>
Co-authored-by: Jonas Zalys <jonas@tryholo.ai>
Co-authored-by: saitsuki <nukuom976228@gmail.com>
Co-authored-by: webtecnica <webtecnica@gmail.com>
Follow-up trim of the #110265 salvage. `ainvoke_hook` logged raising callbacks
with a bare warning; route them through `_report_hook_failure` (warn-once per
distinct failure, #111922) and, for `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS`, append
the same named block directive the sync path emits (#109624), so the async twin
cannot drift into a fail-open policy path. Tests trimmed to the salvage bar: the
in-loop await is proven once through the real `_handle_message` path
(`test_async_hook_callback_is_awaited_on_the_gateway_loop`); the manager-level
duplicate is dropped and the narrowing test also pins failure isolation. Docs:
`pre_gateway_dispatch` callbacks may be `async def` and stay unbounded.
Credit order for the three PRs fixing this gap: #102485 (dmspark, earliest,
pre-decomposition `gateway/run.py`), #110253 (KoNit-K, bounded the hook —
rejected by design: neither fail mode is acceptable for a policy gate), #110265
(twidtwid, reporter; cherry-picked because it matches the ainvoke_hook shape,
keeps the hook unbounded, and adapts the existing sync test seams honestly).
Part of #110241
Supersedes #102485
Supersedes #110253
Co-authored-by: David Marcus <dmspark@users.noreply.github.com>
Co-authored-by: KoNit-K <konit.block@protonmail.com>
`GatewayInboundMixin._hm_pre_gateway_dispatch_hook` was a plain `def` calling
the sync `hermes_cli.lifecycle.invoke_hook` from the async `_hm_admit_event`,
so an `async def pre_gateway_dispatch` callback was resolved through
`resolve_plugin_command_result` on a helper thread with its own loop: the
gateway loop blocked for the callback's whole duration and any loop-bound await
(an `asyncio.Event` set by a loop task, a loop-bound aiohttp session,
`asyncio.to_thread`) could never complete, failing at 30s.
Add `PluginManager.ainvoke_hook` (+ `hermes_cli.plugins.ainvoke_hook` /
`hermes_cli.lifecycle.ainvoke_hook`): same payload narrowing (shared
`_hook_callback_kwargs`), observer + isolation semantics and result contract as
`invoke_hook`, but awaitable results are awaited on the caller's loop.
`pre_gateway_dispatch` stays intentionally unbounded. The inbound hook becomes
`async def` and `_hm_admit_event` awaits it; the sync `invoke_hook` is untouched
for every other caller. Existing tests that stubbed the hook synchronously are
adapted to the async seam.
Fixes#110241
Salvages #110265
(cherry picked from commit 22bb10d305c7992f43bbfdf1481ad0ef0015b2b7)
`_run_hook_callback_bounded` treated any live abandoned worker for a callback
(`bool(self._hook_abandoned.get(suppression_key))`) as "still running", so one
never-returning `pre_tool_call` callback made every later tool call fail closed
with the timeout message until the process restarted. The timeout path
self-heals through the 60s suppression window; the abandoned path never did.
Policy now: while the suppression window is open the callback is skipped as
before. After it expires a fresh call id may start a new worker even though the
abandoned one is still alive — capped at `_HOOK_MAX_ABANDONED_WORKERS` (3) live
abandoned workers per callback so a hung plugin cannot leak a thread per call
(the #98382 constraint). At the cap the callback keeps being skipped (fail-closed
for pre_tool_call) with a WARNING naming the callback and its module, until one
of its workers finishes and frees a slot.
Test changes: `test_hung_worker_blocks_new_call_identity_after_suppression`
encoded the removed behaviour (exactly one worker, forever); it becomes
`test_hung_worker_caps_new_call_identities_after_suppression`, which pins the
same invariant it was protecting — bounded leak, never one per call — at the new
bound and checks the warning. `test_hung_worker_does_not_fail_closed_forever`
is the #105223 regression (red on base: call-c returned the block directive).
Redone slim against the per-call-id gate that landed in #111177; #105241
targeted the pre-#111177 shape and needed plugins_ledger/__init__ changes for a
one-retry-then-quarantine policy. Its analysis and shape informed this fix.
Fixes#105223
Supersedes #105241
Co-authored-by: fangliquanflq <fangliquan@qq.com>
Follow-up trim of the #109632 salvage: the block directive a raising
`pre_tool_call` guard produces reused the timeout wording, so an operator could
not tell a crashing guard from a slow one from the tool result. Build it from
the callback name and `TypeError: ...` (error text truncated like
`_report_hook_failure`). The two salvaged tests collapse into one parametrized
invariant (caller-thread and bounded-worker path) that also pins the message
shape and that a sibling callback's result still flows.
Part of #109624
Salvages #109632
A `pre_tool_call` guard that raised failed OPEN (only `_report_hook_failure`,
results stayed empty, the tool ran) while one that timed out failed CLOSED with
a block directive. For a veto hook a crashing guard is the control quietly
disappearing; make both failure modes of `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS`
consistent: an exception appends a block directive in addition to the warning.
Fixes#109624
Salvages #109632
(cherry picked from commit 6ccf5d8a4082fc6b9af80270aae9f13b0320cfb8)
Under a multiplexed gateway / serve backend the launch profile's own turns bound
secrets and terminal policy but NO HERMES_HOME override (launch_profile_runtime_scope,
_profile_runtime_scope_tokens(None)). Once multiplexing is active an unset override
is the fail-closed "unbound context" signal (serves_routed_profile, per-home slots,
third-party runtime bindings such as OMH's pre_tool_call gate), so every plugin hook
a launch-profile turn fired looked unscoped and a fail-closed plugin vetoed every
tool call ("OMH runtime binding unavailable", #118538). Routed turns already bind
theirs via gateway/run.py::_profile_runtime_scope; the launch profile is a tenant
like any other, so its scope now binds the launch home too.
Sibling gap in the two hook kinds delivered off-turn by long-lived worker threads:
agent.plugin_stream_hooks (on_stream_*/on_interim_message) and the plugin event bus
(plugins_dispatch._dispatch_event) ran callbacks in the worker's empty context, so
even a routed turn's observers saw no scope. Both now capture the emitter's
contextvars at enqueue and run each delivery under a copy.
Single-profile hosts are unchanged (no override until activation).
Closes#118538
The hook loop now treats SystemExit like any other callback failure; the
three sibling dispatch loops in this module (event subscribers,
invoke_middleware, system prompt section content) had the same
`except Exception` gap and let a plugin dependency's sys.exit() abandon
the loop and kill the turn. KeyboardInterrupt still propagates on all
of them.
Two per-call WARNING surfaces were still outside the warn-once reporter:
- agent/plugin_stream_hooks.py::_worker — the on_stream_start/on_stream_delta/
on_stream_end consumer, which fires once per streaming delta (far more often than
per tool call). A mis-declared callback (signature naming tool_data) logged
"Hook ... raised" at WARNING on every delta: 20 deltas -> 20 WARNING lines.
- hermes_cli/plugins_dispatch.py::_deliver_event — plugin event subscribers that
raise identically were warned on every emit.
Both now go through PluginManager._report_hook_failure (keyed by module/qualname,
cleared on unload): the first failure warns and names the fields the hook/event
provides, identical repeats are DEBUG. Skip-and-continue semantics are unchanged.
Part of #111922
Review follow-up on the warn-once hook reporter. Middleware (agent_tool_execution
etc.) runs once per tool call exactly like a hook, so a mis-declared middleware
callback flooded WARNING identically; route its except through the same
_report_hook_failure helper with a "Middleware" surface label.
The reported-failure set was keyed on (hook, id(cb), repr(exc)) and never
cleared: a hook whose message embeds tool args grew it by one entry per call,
and id() recycling across plugin reloads could swallow a reloaded callback's
first failure. Key on (hook, module, qualname, exc type, str(exc)[:200]) and
clear the set in _reset_after_unload_all next to _hook_timeout_suppressed_until.
Part of #111922
A plugin callback whose signature names a parameter the hook never sends
(on_pre_tool(tool_data) where core provides tool_name/args) raises the same
TypeError on every tool call; core logged a WARNING each time — ~1700 lines an
hour in the report, burying the freeze signature it was trying to find
(finding (c) of #111922). The mis-declared signature is the plugin's bug; the
per-call repeat is ours.
invoke_hook now reports one WARNING per distinct (hook, callback, error) and
names the fields the hook actually provides so the author can fix the
signature; identical repeats are logged at DEBUG. A callback failing in a new
way still warns.
Part of #111922
The timeout branch of _run_hook_callback_bounded unconditionally added
gate_key to _hook_abandoned. A worker that finishes between done.wait()
returning False and the caller taking the lock has already popped its
token via _release_token, so nothing would ever clear that entry: the
callback stayed blocked for every later call id until reload with no
thread behind it. Guard the insert on the worker still being registered.
The new test makes the race deterministic by swapping the module's
threading.Event for one whose wait() lets the worker finish and then
reports a timeout, and asserts a fresh call id still runs.
Also pass tool_call_id inline from terminal_tool_result instead of the
conditional dict plumbing: an empty id is already treated as "no
identity" by _hook_call_identity and unknown fields are withheld from
narrow-signature callbacks (same shape as _fire_approval_hook). Update
the stale "(hook_name, id(cb))" comment above _hook_running_callbacks.
Gating hook callbacks by call identity lets two concurrent calls of the
same tool both run their hooks, but it also let a fresh tool_call_id pass
the gate once the 60 s suppression window lapsed even though the previous
worker for that callback never returned. A hung plugin then leaked one
daemon thread per minute for the life of the process; on the old
coarse-keyed gate it leaked exactly one.
Track abandoned-but-running workers per callback: the timeout branch
records the gate key, the worker's own release discards it, and the gate
treats any non-empty abandoned set as "still running" for that callback.
Healthy callbacks keep distinct-id concurrency; hung ones are back to
at most one outstanding worker.
Concurrent invocations of the same tool in one session collapsed into a single
busy key (hook_name, id(cb)): the second invocation was reported as 'still
running' and dropped. For pre_tool_call a drop is a fail-closed block, so the
gate silenced itself on an ordinary, healthy callback.
Measured on a busy profile: 3574 skip lines and 0 timeout lines in one hour —
every skip was the 'while still running' branch, i.e. pure key collision, not
slowness.
The gate now keys on the call identity that is already in the payload
(tool_call_id, else turn_id, else none — the last case behaves exactly as
before). Suppression stays keyed coarsely on (hook_name, id(cb)): a hung
callback is a fact about the callback, so its back-off must not be diluted
per call.
Refs #98382. Independent of #107894 (that one releases the slot on timeout;
this one stops healthy concurrency from colliding).
(cherry picked from commit 53b3dacd008418fcdf5fa6dfcadde575a35a776e)
Slash-command handlers gained loop-safe awaiting in ca9a61ae38, but
`PluginManager.invoke_hook` still called `async def` hook callbacks directly:
the coroutine object was appended to the results (so `pre_llm_call` context
injection silently did nothing) and Python warned "coroutine was never
awaited". `_invoke_hook_callback` now routes every return through
`resolve_plugin_command_result`, which covers both the direct and the
timeout-bounded paths and is safe under the gateway's running loop.
Fixes#12449 (remaining hook half). Salvage of #63240 by @Bartok9, applied
one layer down so the bounded-worker path is covered too.
Co-authored-by: Bartok9 <Bartok9@users.noreply.github.com>
The identity-guarded token pop appeared twice (the runner's finally and the
new worker-start except); a future edit to one copy would silently reintroduce
the sticky-token class. Hoist into a local closure called from both sites, and
extend the _run_hook_callback_bounded docstring with the new skip reason.
Behavior-preserving follow-up on #104651.
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.