Provider tool arguments now skip the URL query mask: a memory tool may fetch the URL it
is given (openviking's viking_add_resource indexing a pre-signed S3 or SAS link), so
masking ?X-Amz-Signature=/?key=/?sig= broke it. Storage-only hand-offs keep urls=True.
The URL query pass also masks every name the JSON-field rule treats as a secret
(accessToken, x-api-key, auth_token, private_token, secret_key, passwd, ...), via the
same closed list and affixed-key policy, so the two passes agree.
Refs #119852
Memory-provider sync and telemetry export now opt into the strict URL pass via
redact_for_egress(urls=True), so a prefix-less ?api_key=<opaque> is no longer
archived verbatim. Chat delivery and delegation keep it off: there the agent
hands the user magic links / OAuth URLs that must stay usable.
Fixes#119852
Retain the historical single-profile direct-call behavior while using weak
manager leases to protect duck-typed providers without __weakref__ in
non-multiplexed multi-home hosts. Test the real MemoryManager path.
Follow-up to c2h5oh's fix of nesquena-hermes's #146293 report; original
implementation credit: chengqiZ (#146329).
Refs #145968
on_turn_start ran every keyword through the provider secret scrub to cover
previous_message. author_id and author_name went through it too, and an SMS or
Signal sender id is a phone number, so a provider keying durable state on it got
a masked id, and two senders with the same leading and trailing digits merged
into one. sync_all hands the same author through raw in the same turn.
The message and previous_message are now scrubbed together (one learned-token
set, as before), and every other keyword reaches providers unchanged, as on main.
Review of the previous commit found two defects in it.
previous_message is earlier user text, but MemoryManager.on_turn_start
scrubbed only the positional message and forwarded keyword fields raw,
so a credential the provider redactor masks reached providers unmasked.
The message and the keyword payload are now scrubbed together, the way
the other fan-outs do it.
previous_message was read from the history turn-start compaction hands
back. In-place compaction returns a flush baseline that already ends in
this turn's message, and rotation returns none, so the value was this
turn's own message or empty exactly when a long session compacted. It is
now read before this turn's message is appended, and skips user-role
runtime scaffolding via _is_real_user_message.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Arming checkpoint_required flips the four fork sites to skip_memory=False so
the child can reach the checkpoint contract. That also woke the ordinary
per-turn fan-outs (on_turn_start, sync_all/sync_turn, prefetch_all,
queue_prefetch_all) and the session-end and delegation writes, which leak the
fork's harness prompt and output into the user's real memory. The old
skip_memory=True guard existed to stop exactly that. The escape hatch only
worked for providers that honour agent_context; most bundled providers
(mem0, hindsight, byterover, holographic, openviking, retaindb) ignore it.
Enforce the skip on the host: MemoryManager captures agent_context at
initialize_all() and short-circuits prefetch_all, queue_prefetch_all,
sync_all, on_turn_start, on_session_end and on_delegation for
agent_context "subagent", independent of provider behaviour. initialize(),
on_session_switch() and on_pre_compress() (the checkpoint path) stay
ungated -- the contract needs them; the on_pre_compress docstring and the
provider guide say so, since a v2 provider that applied its non-primary
write skip there would either report success without a save or kill the
fork at its first compaction.
Scoped to "subagent" only: cron and flush agents ran with a provider before
this change and keep the provider-side contract (MemoryProvider.initialize),
so their recall and writes are not changed here.
(cherry picked from commit a2ead2a17eb646bee8c78da41dde1ad971e8335a)
(cherry picked from commit 654f7c7a9ba06ab2379405b180e058978b0eafa8)
The comment in agent/memory_manager.py still named the validator file as
the reason agent.memory_manager is public; the list now lives in
hermes_cli/data/plugin_api.json. Comment only.
A pre_llm_call veto kept the typed text as the user row's content and put
the placeholder only in api_content, which only the main-loop wire replay
reads. Compaction (summary request and handoff), session_search, external
memory providers and the routed background-review digest all read content,
so the vetoed prompt reached a model at the next compaction or search.
- The placeholder is now the row's content and the persist override; the
typed text lives only in display_metadata.withheld_prompt, which the CLI
resume recap, TUI/Desktop session history and the dashboard render.
- A row the TUI/Desktop wrote at submit time is rewritten in place
(set_user_message_content gains an optional display_metadata, also on the
managed-worker store op).
- The hook now runs before turn-start compaction and a blocked turn skips
it: that summary request quotes recent user turns, this one included.
- Memory-provider transcript hand-offs drop the display-only key.
Admitting a probe popped the skip counter, so a long outage logged its
"first skip" warning after every probe (about once a minute). Reset the
counter only when the gate is genuinely open; rename closed_at to
probe_at, which is what it stores after the first probe.
- enter() counts the skip under the gate lock and returns (stuck, in_flight,
skips); the separate count_skip() round-trip could recreate a cleared key or
leave a stale count when the last call left in between.
- The skip warning reports calls in flight too, since the in-flight cap can be
the reason with fewer than four stuck. The prefetch-timeout warning no longer
names the threshold, which no longer tells the whole story.
- The half-open probe test resets the interval before its second call, so it
proves the successful probe reopened the gate (it fails if success is not
recorded); the orphan test uses _MAX_STUCK_CALLS instead of a literal 4.
- Drop a dead empty-dict branch and a duplicated comment.
Requested by the maintainer (teknium1's re-review, problem 2, option B). With
the four-call tolerance the gate still reopened only when a stuck call returned,
so four dead-socket hangs spread over a gateway's uptime turned the provider's
writes and recall off until restart, even after the backend recovered.
Both gates (background sync_turn/queue_prefetch and external prefetch) now share
one _StuckCallGate per kind:
- A successful return stamps the key's last success; stuck calls that started
before it no longer count toward _MAX_STUCK_CALLS, so a recovered backend
clears old orphans the first time a call gets through.
- While closed, one half-open probe per _PROBE_INTERVAL_S (60 s) is admitted, so
a recovered backend proves itself without waiting for an orphan to return.
- _MAX_INFLIGHT_CALLS (16) caps calls in flight per key, orphans and probes
included, so a backend that stays wedged pins a bounded number of threads.
Measured (stub provider, real MemoryManager, stall threshold 0): four separate
orphans each followed by recovery, then 6 fresh managers: 0 writes / 0 recalls
on e4538c2792, 6 / 6 now. Sustained wedge, 30 managers: 4 pinned calls per gate
with no probe due (same as before); with a probe on every call, 16 per gate.
- The skip counter resets when a call is admitted: with the tolerance at four,
one orphan can keep the key alive after the gate reopens, and the next outage
only warned on its 100th skip.
- Log lines report the actual number of stuck calls, not the threshold.
- Comments and the prefetch-timeout warning describe the gate as it is: new
calls stop once four are overdue; calls not yet overdue are not counted, so a
burst inside one stall window can add more (as before). The prefetch class
comment and the timeout warning still said "until the stuck call returns".
- _stuck_calls names what it compares (a cutoff vs stored timestamps).
- Stall tests release hung workers in finally.
The registry key used the home captured when the manager was built.
initialize_all() can bind the providers to another profile (explicit
hermes_home=, recorded in _bound_scope since #140058), so two managers built in
one ambient home but initialized for profiles A and B shared a key, and A's
stuck calls gated B. Both gates now key on the bound home, falling back to the
build-time home before initialize_all() runs.
Both process-wide gates (external prefetch, background sync_turn/queue_prefetch)
closed as soon as ANY call for (home, provider) was overdue and stayed closed
until that call returned. A call that never returns - the case these gates
exist for - therefore dropped every later write and recall for that profile's
provider until restart, even after the backend recovered and fresh managers
held healthy connections.
Tolerate up to _MAX_STUCK_CALLS (4) overdue calls per key before skipping.
Each still pins one thread, so a backend that stays wedged pins at most four
threads per gate per (home, provider); a recovered one keeps working.
Measured (stub provider, real MemoryManager, threshold cut to 0): one hung
sync_turn + prefetch, then 5 fresh managers with healthy instances: 0 writes /
0 recalls before, 5 / 5 after. Ten hung managers: 4 stuck calls and 4 stuck
prefetch threads retained per registry.
The prefetch registry and the stalled-background-call registry had three copies
of "pop my token, drop the key once its dict is empty", and they had already
drifted (one checked the key still mapped to its dict, the others did not).
_forget_inflight() is the single version; behaviour is unchanged.
shutdown_all() gives the single mem-sync worker ~5 s and then cancels whatever
is still queued. Before this PR, release_clients() left the executor alone, so
a retired agent's last sync_turn/queue_prefetch writes still ran in the
background. With the soft-release shutdown they were abandoned instead
(measured: 4 queued 2 s writes -> 2 written, 1 abandoned).
MemoryManager.release_soft() now claims the teardown, flushes (bounded, like
the CLI exit, gateway cleanup and managed-worker paths), then shuts down.
release_clients() calls it, which also moves the soft-release policy out of
the run_agent.py facade (back to main's line count).
The /new cleanup job took the teardown claim only inside
shutdown_memory_provider(), after a flush_pending() that can take up
to 10 s. When /new stops waiting (_RESET_CLEANUP_TIMEOUT_S) it evicts
the agent, and that soft release took the claim and shut the providers
down while the cleanup was still flushing. The cleanup then lost the
claim and skipped on_session_end(), so the session's end-of-session
extraction was dropped. On main release_clients() never touched memory,
so the extraction always ran.
The claim now lives on MemoryManager (claim_teardown(), under the lock
it already has), and _cleanup_agent_resources takes it before the
flush. A session-end caller may re-claim (the cleanup claims, then
shutdown_memory_provider() claims again); a soft release is once-only
and also loses to a manager another owner is already draining, which
replaces the _shutting_down peek in release_clients(). The module lock
and _memory_teardown_claimed attribute in run_agent.py go away, and the
release_clients() comment shrinks to the why.
Claiming earlier than the pool submission is not needed: when /new's
wait_for times out before the job starts, asyncio cancels the queued
job, so it never runs on main or here.
The hand-rolled _MockMM soft-evict test is dropped: its stub manager has
no claim_teardown(), and the real-manager writer-thread test already
asserts the same thing (shutdown, no extraction).
The prefetch thread is registered before start(); if start() raises
(thread exhaustion), the thread never runs its own cleanup, so the entry
would outlive its deadline and gate that provider's recall for the rest
of the process. Drop the entry and re-raise.
With the registry shared process-wide, registering one in-flight thread
per key meant a second session's healthy prefetch was skipped (empty
recall) whenever another session's prefetch on the same provider was
still running inside its timeout; main's per-instance registry never did
that. And with one slot per key, a later timeout overwrote an earlier
stuck thread's entry, so when one stuck call returned it reopened
admission while another call was still hung.
The registry now holds every in-flight prefetch thread per key with its
deadline. New spawns are skipped only while some call for the key is
past its deadline; healthy concurrent prefetches run side by side; each
thread removes only its own entry when it returns.
The stall/registry work pushed agent/memory_manager.py past 1,000 lines.
The memory-provider tool-schema helpers (normalize_tool_schema,
memory_provider_tools_enabled, memory_provider_tools_exposed,
inject_memory_provider_tools) are a self-contained topic with no
dependency on MemoryManager, so they move verbatim to a
memory_manager_tools sibling and every in-tree caller imports from the
new module. agent.memory_manager is a public plugin module
(hermes_cli/plugin_validate_private_imports.py), so it re-exports the
four names, as it already does for the helpers that moved to
agent.memory_context.
A sync_turn or queue_prefetch that never returns pins its mem-sync
worker for the life of the process (Python cannot stop a thread).
Managers are rebuilt per agent, so every fresh manager started another
call against the hung backend and pinned another thread; under gateway
cache churn this grew without bound.
_call_unless_stalled keeps a process-wide registry of in-flight
background calls per (Hermes home, provider name). While any call for a
key has run longer than 30 s, later sync/prefetch calls for that key are
skipped (logged on the first skip and every 100th) until it returns.
Skipping costs that turn's write/prefetch but keeps the thread count
bounded. The builtin provider is local and never gated.
One gateway process can serve several profiles, each with its own config
and credentials for a same-named provider, so key the process-wide
in-flight registry by (Hermes home, provider name): one profile's hung
backend no longer silences another profile's recall. The home is captured
when the manager is built, inside the profile scope the agent is built for.
A timed-out prefetch thread now pops its own entry when it finally
returns, so the process-wide registry never pins a finished thread.
The stuck-prefetch guard dict was a MemoryManager instance attribute, and
a manager is rebuilt per agent init, so every fresh manager whose prefetch
timed out spawned one more memory-prefetch-* thread against the same
provider with no upper bound (#134392). Key the registry by provider name
at class level so a stuck call suppresses new spawns from any manager
until it returns.
Salvaged from #131357 (registry commit only, resolved onto current main,
which has no late-result cache).
Co-authored-by: Halldrix <noreply@users.noreply.github.com>
Every memory tool call resolved two profile-home keys (the caller's and
the bound home's) and ran inspect.signature on the provider's
handle_tool_call. The bound home and the provider never change for a
manager, so initialize_all now records the bound home's key with the scope
(bound_scope) and the manager caches each provider's accepted keywords.
A call resolves only the caller's home. Behaviour is unchanged.
Refs #134889 (PLG-11)
Refs #140208
When initialize_all refuses a provider instance another profile already
bound, it drops the provider, but the agent build still logged "Memory
provider '<name>' activated" and kept a manager with no external provider,
and nothing reached the user. With a singleton-style plugin, which profile
keeps its memory depends on whose message arrives first after boot.
Agent builds now call MemoryManager.initialize_for_agent, which runs
initialize_all, reports each dropped provider through the agent's startup
warning sink (as the unavailable-provider path does) and returns whether an
external provider is still served. The build logs "activated" only then;
otherwise it drops the empty manager like the not-available path. The
warning names the provider, never a home path; the check's code and the
homes stay in the log.
Refs #134889 (PLG-11)
Refs #140208
The refusals log under agent.memory_caller_scope, which gateway.log's
component filter (gateway, hermes_plugins, plugins.platforms) dropped: on a
live multiplexed gateway they reached the profile's agent.log and
errors.log but never gateway.log, which the PR, the docs and the
chat-visible refusal all pointed at. The refusal can also happen in
hermes serve, the TUI and Desktop, where there is no gateway.log.
Add agent.memory_caller_scope to the gateway component's prefixes, and
have the generic refusal (tool error and the checkpoint RuntimeError) point
at `hermes logs errors`, which every host writes. The chat still sees no
check name and no home path.
Refs #134889 (PLG-11)
Refs #140208
The refactor that moved sanitize_context, StreamingContextScrubber and
build_memory_context_block into agent/memory_context.py removed them from
agent.memory_manager. That module is listed as public for plugins in
hermes_cli/plugin_validate_private_imports.py, so an out-of-tree plugin
importing them from the old path would fail with ImportError. Re-export
the three names; in-tree callers keep importing from agent.memory_context.
Also points the scrubber test's docstring at the module the class lives in.
Refs #134889 (PLG-11)
Refs #140208
On a multiplexed gateway every served profile's agents share one process.
Each agent's MemoryManager owns its own provider instance, but nothing stopped
a tool call or lifecycle hook from another profile's context, or from a
context naming no profile, from reaching it. Nothing stopped two agents being
handed one shared instance either. The in-repo providers also bound their
stores from the ambient home rather than the one the manager passed.
MemoryManager.initialize_all records the profile home (and agent_identity) it
bound its providers to. Then:
- Tool calls and every lifecycle hook (prefetch, queue_prefetch, sync_turn,
on_turn_start, on_memory_write, on_session_end, on_session_switch, the
session boundary, on_pre_compress, on_delegation) run only when the caller
explicitly names that profile: the context's HERMES_HOME override, or the
home its secret scope was built for. On a multiplexed process a caller that
names no profile is refused, never resolved to the process's own profile.
A refused checkpoint compression raises, so the transcript stays
uncompressed.
- Background hooks run under the owning profile's HERMES_HOME, set
explicitly in the worker.
- An instance another profile's manager already bound is dropped, not
re-initialized (logged as memory_provider_instance_shared). Claims are
tracked by instance identity, never by the provider's own hash or
equality; on a multiplexed process an instance that can't be tracked
(no weak reference) is refused too.
- handle_tool_call passes hermes_home / agent_identity next to the previous
commit's caller_gsk. A provider with the two-argument handle_tool_call gets
only what it declares; caller_gsk alone made every call to it a TypeError.
- The model sees a generic "refused, check gateway.log". gateway.log keeps
memory_caller_profile_unresolved and both homes.
ByteRover and RetainDB now bind their store from initialize()'s hermes_home.
Both already kept their bindings on the instance and hold no profile state at
module level.
The provider side of the rule is documented on MemoryProvider and in the
memory-provider plugin guide: a new instance per load, every binding from
initialize()'s hermes_home, no profile state at module or class level, no
per-call rebinding. Core cannot see inside an external provider; one that
keeps a process-wide binding still mixes profiles' memories.
The previous commit's two MagicMock tests in test_run_agent.py move into
tests/agent/test_memory_provider_caller_profile.py (test_run_agent.py is over
its line cap and may not grow). That file drives both dispatch paths and
every hook with real managers and two profiles interleaving on threads;
tests/plugins/memory/test_provider_multiplex_contract.py does the same for
ByteRover and RetainDB with a fake backend.
Refs #134889 (PLG-11)
Refs #140208
Refs #140058
agent/memory_manager.py mixes provider fan-out, background work and the
text formatting that fences recalled memory for the model. The formatting
half (sanitize_context, StreamingContextScrubber, build_memory_context_block
and their regexes) is pure text work with no provider calls or profile
state, so it moves unchanged to its own module. Callers import it from
there; nothing in plugins/ imported it, so no re-export is kept.
The only visible difference is the logger name on the "pre-wrapped
context" warning (agent.memory_context). This leaves the manager room for
the profile-ownership checks the next commit adds without crossing its
line cap.
Refs #134889 (PLG-11)
Refs #140208
Single and batch patches each carried their own copy of the span rule,
and the copies disagreed:
- str.count misses overlapping matches, so '00' in "Timeout 1000 ms"
passed the one-span guard and saved "Timeout 150 ms".
- The single call stripped old_text but not the replacement, so
"tea " -> "coffee " saved a double space; the batch stripped both, so
"New" -> "New " was rejected as a no-op.
- The provider mirror rebuilt each batch patch from the arguments,
repeating those whitespace rules outside the store.
_patch_entry now holds the rule for both shapes: it counts overlapping
matches, keeps span whitespace, and runs the no-op check and threat
scan. A batch result reports the entry each patch produced
(patched_entries_after), and the mirror forwards that instead of
rebuilding it.
Reported by Greptile on #137523.
notify_memory_tool_write forwarded a patch as action "patch" with only
the replacement span as content. Providers know add/replace/remove, so
they skipped it (byterover mirrors only add and replace) or would have
stored the span as a fact. Since patch takes over the edits replace used
to make, external memory stopped receiving those updates.
Mirror a patch as what it is to a provider: a replace whose content is
the whole entry after the edit, with the entry before it as
previous_content. Single results carry patched_entry_after; for a batch,
redo the store's splice on that op's entry before the edit.
Without the opt-in, external recall is kept whole up to
max(10 x hooks.output_spill.max_chars, 100k chars) and still spills above
that, so one runaway provider can't overflow the context window and wedge
the session. Normal provider-budgeted recall (~16 KB for Honcho) is
unaffected.
MemoryManager forwarded turns, transcripts and tool output to external
memory providers without the egress scrub, so a key echoed into tool
output was archived verbatim in the provider's store.
Every fan-out now goes through redact_for_egress (the chat/cron delivery
scrub; holds with security.redact_secrets off, fails closed): sync_all
(turn strings + messages), prefetch_all / queue_prefetch_all,
on_turn_start, on_session_end, on_pre_compress (both transcripts),
on_memory_write (content + metadata), on_delegation and provider
handle_tool_call args. Nested dicts/lists (tool-call arguments,
multimodal parts) are walked; data: URLs pass; the live transcript is
never mutated. A value masked anywhere in one hand-off is masked
everywhere in it, so a key the model repeats bare in prose is caught.
redact.py: the JSON-field rule now also matches inside JSON-encoded
strings (tool results wrap config dumps in escaped JSON), which is how
the reported opaque AQ.-prefixed key slipped past.
Co-authored-by: Teknium <teknium1@gmail.com>
- memory tool: one row per operation (a batch counts each op); gate/validation
refusals are "rejected", store-level non-application "failed". Memory provider
tools are counted in MemoryManager.handle_tool_call with the op read from the
action arg or tool-name verb.
- curator: run_curator_review records one row per pass (dry run = skipped) with
the before/after diff bucketed; a scheduled pass whose claim is held by another
process counts as skipped. The home is captured before the review thread starts.
- delegate_task: _run_batch opens the call, each joined unit folds its results in,
and the last unit emits the call's single row, so group-split background calls
are not counted per unit.
- terminal / execute_code / browser: counted per call that reached the backend;
the backend is resolved from the owning profile at call time (terminal plan
env_type, code local/remote, browser CDP > Camofox > cloud provider > engine, or
"extension" when the extension controller served the call). Guard refusals and
Hermes' own _host_local commands are not counted.
Tests read rows back from the real store; each call-site group is red with its
source reverted.
Only column-0 bullets participate in `_drop_repeated_recall_lines`.
An indented line is a continuation of the bullet above it (nested
child, provenance, wrapped prose) and is kept verbatim, so identical
children under two different parents both survive. The docstring
already promised this; the code now matches.
PROOF: with the old code, `- Project A\n - status: active\n- Project B\n
- status: active\n` lost B's child (probe s4_eff_nested.py) and the
new assertion in test_a_bullet_with_continuation_lines_is_never_touched
fails (AssertionError at :49); after the change the probe returns the
input unchanged and tests/agent/test_memory_context_dedupe.py passes.
`_RECALL_BULLET_RE.match(stripped)` was evaluated twice per line and the inline
comment restated the docstring's per-section scoping paragraph. Compute
`is_bullet` once and keep a one-line comment. Behaviour-neutral.
PROOF: mutation `is_bullet = True` → tests/agent/test_memory_context_dedupe.py
1 failed (repeated-bullet), restored → all 44 tests across the PR's four test
files pass; ruff clean; footguns clean; real import OK.
The per-section reset only fired on `#…`, `**…` and `---` lines. The
in-tree RetainDB provider writes prose headings (`Profile:`,
`Relevant memories:`, `Instructions:`), so its second section still
collapsed into the first: `Profile:\n- None\nRelevant memories:\n- None`
lost the second `- None` and left a heading claiming nothing — the
exact failure 931d240e14 set out to fix, for markdown headings only.
Now any non-empty, non-bullet line at column 0 (a heading of any style,
a `---`/`***`/`___` rule, prose) clears `seen`; bullets and indented
continuation lines stay inside the current section.
PROOF: tests/agent/test_memory_context_dedupe.py::
test_identical_placeholder_bullets_under_different_headings_both_survive
(RetainDB prose-heading shape + markdown shape). Red with
agent/memory_manager.py at the previous commit (prose case drops the
second `- None`), green after; the continuation-line carve-out test
stays green.
The `seen` set from #117399 was block-global, so identical placeholder
bullets under different headings ("- (none recorded)" under two stores)
collapsed into the first section and left the second heading claiming
nothing. Reset the set at every heading (`## …` / `**…**`, the PR's own
heading detection) and at `---`, so only a repeat inside the same
section is dropped.
Review follow-up on two real defects in the first cut, both reproduced before fixing.
A dropped duplicate left its continuation lines behind, and they re-parented under the surviving
bullet: `- prefers draft PRs` / ` (logged 12 Jan, supermemory)` followed by the same headline
logged elsewhere collapsed into ONE entry carrying BOTH provenance lines — inventing a record
neither provider reported, then stamping it into `api_content` to be replayed every turn. That is
worse than the duplicate the change set out to remove. A bullet that carries continuation lines is
now never dropped and never suppresses a later one, so two entries that share a headline and differ
underneath it both survive.
And `stripped[:1] in ("-", "*")` treated `**Preferences**` as a list item, so a repeated bold
section heading was silently deleted — contradicting the docstring's promise that headings survive.
The marker test now requires a real bullet: marker, whitespace, content (`[-*+]\s+\S`), which also
keeps `*emphasis*` out. Numbered items stay out of scope, and the docstring says so rather than
claiming "list items" generally.
Measured again on the same 166 real blocks: still 219,260 of 1,302,220 body bytes — 16.8%,
unchanged. Every duplicate in that sample is a self-contained bullet, so correctness cost nothing.
Tests: a bullet with continuation lines is untouched; a nested bullet is a child, not a repeat;
same-depth indented duplicates still collapse; bold headings, emphasis and numbered items are left
as written. Removing the continuation guard fails two. The tautological assertion the review flagged
is replaced by an exact whole-body comparison.
(cherry picked from commit 37a36f23658b8ca1e112f46ff60a705a66f80a5b)
Every user turn injects a `<memory-context>` block built from the providers' prefetch, and nothing
dedupes it: a provider merges several stores and `prefetch_all` merges several providers, so one
prefetch routinely surfaces the same fact two or three times.
It is not paid once. The composed block is stamped into the user row's `api_content` sidecar and
replayed verbatim on every later request for as long as that row is in context — deliberately, so
the prompt-cache prefix stays byte-stable. Compaction cannot reclaim it either: `_demote_tool_result_at`
bails on anything that is not `role == "tool"`, so a user row is never shrunk and drags its memory
dump along while counting against the tail budget. A duplicated bullet therefore costs its tokens
once per turn, for the life of the row, while telling the model nothing that same block has not
already said.
Measured on a real operator state.db (166 rows carrying a block, 46 sessions): 219,260 of 1,302,220
body bytes — 16.8%, ~54,815 tokens on first send alone — are list items byte-identical to an earlier
line of the SAME block. Median block ~2,034 tokens per user turn.
Only list items are considered, and only when identical after stripping: headings, prose, blank
lines and `---` rules are left exactly as the provider wrote them, so sections still read as
written and a line repeated deliberately as prose is untouched. Within one block only — deduping
against earlier turns would save far more (73% of bullet bytes in that sample were already sent
earlier in the session) but changes what the model sees on a turn, so it is not done here.
The "provider returned pre-wrapped context" warning stays keyed on sanitization alone: a deduped
bullet is routine, not a provider fault.
Fixes#117397
(cherry picked from commit e3b08ca9b1708a7cddc2f1a2191b51d60d194624)
Six of eight memory providers spawned plain threading.Thread for prefetch/sync/
writer work. A plain thread starts with an EMPTY contextvars.Context, so under
multiplex profiles the worker resolved the DEFAULT profile's HERMES_HOME (and
fails closed on scoped secrets). honcho and hindsight had each noticed and
written their own copy_context() wrapper; core had a third in memory_manager.
One canonical pair now lives on the ABC module every provider already imports:
agent/memory_provider.py::ctx_bound / spawn_context_thread. memory_manager,
honcho, hindsight, mem0, retaindb, byterover, supermemory and openviking all use
it; the honcho and hindsight wrappers and memory_manager._ctx_bound are deleted.
Five "json.loads(path.read_text()) or {}" readers (mem0._read_mem0_json,
honcho client/oauth/cli _read_config, hindsight save_config/_load_config) fold
into utils.read_json_or_empty, the read half of every read-merge-atomic_json_write
sidecar store.
holographic.save_config was the only config.yaml writer in the tree that
bypassed hermes_cli.config.save_config: raw open("w") + yaml.dump with no config
lock, no managed-mode refusal, no atomic replace, and a swallowed exception. It
now calls save_config(..., merge_existing=True). Behavior change: a managed
install refuses the write (previously silently rewrote config.yaml); other
sections are deep-merged instead of round-tripped through a raw dump.
openviking._hermes_home_path guarded an impossible ImportError of
hermes_constants (the module already imports agent.*) with a ~/.hermes fallback
that is wrong on Windows and under profile overrides; it is replaced by
get_hermes_home() directly.
Tests: tests/plugins/memory/test_provider_threads_inherit_profile.py drives each
provider's real spawn path with a fake backend and asserts the thread sees the
spawner's HERMES_HOME override (sabotage: retaindb back on threading.Thread ->
red). tests/plugins/memory/test_holographic_save_config.py pins merge-with-
existing-sections and managed-mode refusal (sabotage: raw yaml.dump -> red).
`add_provider()` flipped `_has_external` and appended the provider before
calling `get_tool_schemas()`. When schema loading raised, the broken provider
stayed registered and the single-external slot was poisoned for the rest of
the process: every later provider was rejected as "already registered".
Materialize the schema list first; state changes only after it succeeds.
Exception propagation is unchanged.
Hand-port of PR #9997 by @zhouhe-xydt onto the current add_provider() (the
reserved-core-tool filter landed in between); one invariant test.
Fixes#9948
MemoryManager.on_turn_start forwarded the author kwargs to every provider and _each_provider swallowed the TypeError, so a provider with the two-positional on_turn_start(n, text) stopped running. The kwargs are now filtered against the provider's signature the way _provider_sync_accepts filters sync_turn.
on_turn_start already received the author trio. sync_turn did not, so a
provider that wanted to write the turn under its author had to stash state
between the two hooks. sync_turn now takes turn_author as a keyword-only
argument, and MemoryManager sends it only to providers whose signature
accepts it, so existing providers keep working unchanged.
build_turn_context resets the author on the agent at the start of every turn
so a cached gateway agent never carries a bot author into the next human
turn. agent/turn_author.py holds the parsing and the HERMES_TURN_AUTHOR
carrier.
MemoryProvider.identity_signature() is a new optional hook: the identity
values a provider writes under, declared by the provider itself, for the
gateway's agent cache to key on.