* fix(memory): an entry written before a limit was lowered stays removable
The drift guard reads any entry longer than the whole-file char limit as
free text an external writer appended, on the premise that no tool write
can produce one. Lowering memory_char_limit or user_char_limit breaks that
premise: a well-formed file whose entry was written under the old limit
then refuses every replace and remove (tool, approval replay and the
Journey/dashboard delete alike) and writes a .bak each time, while adds are
blocked by the total. Pruning, the documented way back under the limit, is
refused, so the store stays locked until hand-edited.
A file that round-trips but carries an oversized entry now refuses only a
write that adds or rewrites text. A write that only deletes entries goes
through; when it drops an oversized entry the .bak snapshot is still taken
first and returned as drift_backup, so text glued onto an entry without a
delimiter is never deleted without a copy. Round-trip mismatches are
refused as before.
* fix(memory): a refused write beside an oversized entry still names that entry
With deletions now allowed past an oversized entry, a replace or edit that blows the budget
because of that entry came back as a plain budget refusal ("shorten the new content") with no
snapshot, although the oversized entry is the real obstacle. An over-budget refusal next to an
oversized entry returns the drift error and its .bak again; other refusals (no match, would
empty the store) pass through unchanged. The Journey edit/delete closure reports its budget
refusal through _error so the class is visible.
The Journey drift test (43d3d4e851) pinned "delete is refused beside free text"; it now pins
the edit refusal and that a delete leaving the oversized entry in place goes through, which is
the ruling for #133028 (removes must work while the store is over its limit).
* fix(memory): delete-only batches prune past a lowered cap; snapshots never overwrite or go missing
Review round (Greptile on e0ca0c027a8):
- A remove-only batch skips the final budget check like a single remove (the empty-store guard
still applies), so pruning two small entries beside an oversized one is one call, not two.
- Snapshots are created exclusively (.bak.<ts>, then .bak.<ts>.<n>): two deletes of oversized
entries in the same second no longer overwrite the first snapshot with content that lacks
what the first delete removed.
- A delete that drops an oversized entry is refused when its snapshot could not be written,
instead of deleting possibly glued free text with no copy.
* test(memory): freeze the clock so the same-second snapshot test cannot pass by luck
Greptile on 2eba9c5e78a: with the real clock, two deletes straddling a second boundary get
distinct backup names even without exclusive creation. Pinning time.time makes the collision
certain; reverting to overwrite-mode writes now fails the test.
* chore: retrigger CI (lost synchronize event)
---------
Co-authored-by: John Paul Soliva <soliva.johnpaul@icloud.com>
Greptile on 41ed1f061d9 (Forgetting one fact can fail / Duplicate adds inflate space
advice): after a cap is lowered below the store's size, the one-item batch refused a
remove that the legacy remove allows (it has no budget check), and a duplicate add
reached the overflow error with an inflated excess instead of legacy's "already
exists". A one-item batch that does not grow the store skips the final budget check;
every other batch keeps it.
Review finding (stale wording): the drift remediation and the missing-parameter error
still steered the model to the unadvertised top-level memory(action=...) shape. Both now
name operations[] (a single change is a one-item list); the legacy shape still executes.
The [BLOCKED: ...] load-time placeholder keeps its memory(action=remove, ...) hint: two
origin/main tests pin that exact text, and that call still works.
Review finding: the legacy single add answered an overflow with current_entries, but
the advertised one-item batch took the #97316 no-echo batch failure, leaving the model
to consolidate against its load-time snapshot. A one-item add batch now returns the
same over-budget response as the legacy add; larger batches keep the no-echo rule.
Greptile finding "Last fact cannot be removed": with operations[] the only
advertised memory shape, the #103419 empty-store guard rejected the one way
the agent can forget the final USER.md/MEMORY.md entry, and its error pointed
at the unadvertised single remove() shape.
A batch of exactly one remove is now the deliberate single delete (same as
remove()); any larger batch that would empty a non-empty store is still
refused. Unattended background forks never reach it: the #105921 delete gate
stages their removes. The refusal text now names the one-item batch.
The #103419 store test now seeds two entries and removes both in one batch
(assertions unchanged), so it keeps pinning the consolidation case.
replace overwrote the whole matched entry, and models used it as a
find-and-swap, wiping the sibling facts in multi-fact entries (NVIDIA:
19/40 tasks on Opus 4.8). patch does everything replace did (old_text =
the whole entry rewrites it) without that failure, so the tool now
offers add / patch / remove only.
- A replace call, single or inside a batch, is refused with a pointer to
patch and writes nothing. Writes staged for approval before this change
still pin, display and replay through the store's replace.
- The schema loses the replace warnings, explains patch once, and drops
the added target prose: target is already an enum in `required`, the
runtime refusal teaches a missing or nested target, and batch items now
set additionalProperties: false so a nested target cannot be expressed.
- Net tool tokens per session: 13,264 on main -> 13,188 (-76); the PR
head before this commit was 13,446.
- Model-facing hints that said "shorten (replace)" now say patch.
Reverses the whole-entry replace contract from #117952 by maintainer
decision; the tests that drove replace through the tool now drive patch,
and one new test pins the refusal.
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.
Memory writes now require an explicit top-level target, but the external
drift remediation and the blocked-entry notice in the system prompt still
showed memory(action=add, content=...) and memory(action=remove). A model
copying either call got a missing-target rejection. Both hints now name
the store the file belongs to.
patch replaced every occurrence of old_text inside the matched entry. On
"Jeff drinks tea in the morning; his wife drinks tea at night", patching
tea -> coffee rewrote both facts and reported success: the sibling-fact
loss patch exists to prevent, while the schema promises one span.
Reject a span that occurs more than once in the entry (failure class
ambiguous) and ask for more surrounding text, in the single and batch
paths.
The empty-content errors pointed at 'remove', which deletes the whole
multi-fact entry. They now say to patch a longer span that contains the
text to drop. The batch old_text description and the memory docs now
cover patch.
A partial edit of one clause of a packed multi-fact entry could only be
expressed as a whole-entry replace: old_text located the entry, content
overwrote ALL of it, and the sibling facts in the same entry were
silently lost with success:true (#124582). The documented whole-entry
contract is right for replace; what was missing was the splice shape the
API's old_text/new_text reading already invited.
Add a 'patch' action (single-op and batch): find the entry via the
existing _locate (exact/unique/pinned semantics unchanged), splice every
occurrence of old_text -> content inside it, keep the rest of the entry
verbatim, and report patched_entry_before/after so the loss class #117952
guarded against cannot re-enter through the new path. patch joins
_BG_DELETE_ACTIONS (background-review fail-closed + matched_entry
pinning), the approval gate, the batch walk (atomic, with content scan
and no-op refusal) and the schema enums/descriptions.
Fleet telemetry shows built-in memory writes failing 34-47% and automatic
compression failing ~15%, and several merged fixes each target one cause
(#133038 for memory, #133054/#133040/#133051/#133032 for compression). Both
metrics only carried outcome, so the fleet could not tell which cause a fix
moved.
- hermes.memory.op.count and hermes.compression.count gain one closed-enum
dimension, failure_class; `none` on success.
- Memory: every refusal/failure return in tools/memory_tool.py and
tools/memory_tool_store.py names its class (no_match, ambiguous,
over_budget, would_empty, drift, read_failed, retry_cap, scan_blocked,
missing_content, missing_old_text, invalid_args, stale_entry, disabled,
staged, gate_refused) through a context variable; the result the model
sees is unchanged. Plugin providers report provider_error / exception.
- Compression: the attempt log's own failure_class, collapsed onto the
compressor's closed names (exception:<Type> / rollback:<Type> keep only the
prefix, anything else reads other, a classless failure unknown). Skipped
rows carry the skip reason, and the skip set is now defined once in the
contract.
- Package schema v4 / event schema v4; v3 field sets of both metrics stay
valid so pending rows drain. Doc table rows and the consent copy (CLI
setup and every Desktop locale's collectedActivity) name the new reason.
The typography-folded fallback in _substring_matches rejected a needle only when
it was quotes/dashes at the ends (needle.strip("'-")), so old_text="\u201c \u2014"
(curly quote, space, em dash) folded to "' -" and matched any entry containing
`" -`, deleting it via single or batch remove. The fallback now requires at least
one alphanumeric character; exact-entry and byte-substring priority are unchanged.
Tests: the PR's four new tests are folded into two invariants (layout/typography
match + punctuation-only rejection; self-correcting failure copy + #90468 alias).
Fleet telemetry (14d, v0.21.5) shows the builtin store returning
success=False on 34-47% of add/replace/remove calls. Live `hermes chat -q`
runs against origin/main reproduced the dominant causes:
- Drift guard refused every replace/remove/batch on a file whose only
difference from the tool's own layout was whitespace (blank lines
around the delimiter, an empty entry). Parsing only strips whitespace,
so flushing such a file loses nothing; the round-trip signal could not
protect any content and turned the store read-only until hand-fixed
(#107270). The guard now fires only on the signal that can actually
lose foreign text: one entry larger than the whole store's limit.
- An over-budget add/replace/batch said "would exceed the limit" but not
by how much, so models retried with consolidations that were still too
big. Every over-budget message now states the exact chars to free and
points at the one-batch fix.
- An old_text that matched nothing (paraphrased, stale after a concurrent
write, or several entries glued with the delimiter) returned no hint on
the batch path. Zero-match errors now carry `closest_entries` (top word
overlap) on both paths, and flag a delimiter-spanning old_text.
- A batch replace missing its own `content` now says to set it on the
operation object.
Fixes#107270. Same diagnosis as #107278 (@KoNit-K) and #61612 (@webtecnica),
which normalized the round-trip comparison instead of dropping it.
Background-review (and human /memory) replaces re-emit entry text with
different quote characters (straight ' vs stored ") or re-wrapped lines, so
byte-exact old_text substring matching wrongly reported 'No entry matched'
and the staged consolidation write failed to apply. Fall back to a
quote/whitespace-normalized match only when no exact match exists, preserving
today's unambiguous behavior. Adds regression tests for the quote-style
replace and for unrelated old_text still being rejected.
`_batch` kept three accumulators holding the same selected entry; keep only
the per-op `matched` list and build `replaced_entries`/`removed_entries` from it
on commit. The background delete gate now asks `destructive_ops` instead of
re-spelling the predicate, `destructive_ops` tolerates a None op like the rest
of the batch path, and the pinned lookup no longer threads a dead `ambiguous`.
resolve_batch_entries copy-pasted apply_batch's op loop and had already
drifted from it: no `op or {}` normalisation, no pre-disk content scan, no
empty-store or budget check. A background-review batch carrying an
injection payload was therefore staged (and echoed in /memory pending) and
only rejected at approve time. One private _batch(commit=...) now backs
both: apply_batch persists, resolve_batch_entries returns the per-op
matched entries from the same validated walk, so pin time fails exactly
where the direct batch would.
Also fold the twice-written "pinned entry -> index or stale" lookup into
_pinned_index, and state in _mutate's docstring that any dict a closure
returns is passed through unpersisted (the read-only resolve closures
rely on that, not only error dicts).
A staged replace/remove recorded only its old_text search string, and
/memory approve re-ran that search against the file as it was at
approval time. The background review stages every replace/remove it
wants (#105921), so when the live agent updated the targeted entry in
place and the new text still contained old_text, approving deleted or
overwrote the newer entry the approver never saw, and the output said
only "Approved 1 memory write(s)."
- Both staging gates resolve each replace/remove, under the store lock,
to the full entry it matches and record it as matched_entry. No match
or an ambiguous match is refused at staging, as the direct write is.
- Approval matches that entry exactly. If it changed since staging, the
write is refused and the pending record is kept, as #96059 does for
skills.
- /memory approve lists removed entries next to overwritten ones, so a
record staged before this change (no matched_entry, still replayed by
old_text) never removes an entry silently.
- /memory pending shows the full entry each staged replace/remove
targets, not just its search string.
(cherry picked from commit 28700fa750c9321ded48be77a76531b5809f5fea)
A Journey memory edit or delete (Desktop panel, `hermes journey`, TUI
`learning.*`) rewrote the whole MEMORY.md / USER.md from an unlocked
snapshot via `_read_file` + `_write_file`: a memory the agent stored in
between was dropped, and hand-edited content that does not round-trip
through the § parser was reformatted with no .bak.
Both mutations now go through `MemoryStore._mutate` — the memory tool's
cross-process lock, re-read under lock and drift guard. The node id is
resolved to its entry text inside the lock and matched by exact text
against the re-read entries; a vanished target, drift or an unreadable
file is refused with the store's own message instead of written over.
Router/CLI/TUI response shapes are unchanged.
Fixes#119668
Quality fold on the #117952 salvage stack: replaced_entries keys now match
the 1-based "Operation N" numbering the model sees for failed ops in the
same batch response (0-based dict keys JSON-serialialize to "0" and would
misalign with "Operation 1"); _apply_batch_op docstring states the actual
None/None-success semantics; the missing-old_text replace hint is hoisted
out of the f-string concat.
90/90 across the memory, schema, import-fallback, write-approval,
background-review-scope and honho-write suites.
Reuse fold on the #117952 salvage stack: _mutate's optional third value was
plumbed through a (field-name, lambda-extractor) tuple + extra kwarg + two
module constants. _error already had the convention this needed — caller
supplies a dict, the response merges it. _apply closures now return the
payload dict directly ("replaced_entry"/"replaced_entries") and
_success_response takes **extra, dropping the constants, the extractor
lambdas and ~8 lines of machinery. Add/remove-only batches no longer carry
a noise field (the closure omits the key when nothing was replaced).
79/79 across memory + schema + write-approval suites; E2E re-run on the
final shape (single/batch/replay visibility present, no noise on
remove-only batches); mutation check re-proven (dropping the merge turns
test_replace_whole_entry_contract red).
Review fold on the #117952 salvage stack:
- test_replace_same_across_single_batch_and_approval_replay built three
stores over ONE shared store dir, so the batch/replay stages appended onto
the single-stage result and read its leftover entry back — the cross-surface
equality passed without exercising the batch or replay surfaces. Each
surface now gets its own dir; the batch visibility assertion moved into
test_replace_whole_entry_contract where it binds the batch surface directly.
- _BATCH_REPLACED_ENTRIES now maps an empty dict to None so add/remove-only
batches don't carry a "replaced_entries": {} noise field in every result.
Mutation re-check: reverting the batch visibility field turns
test_replace_whole_entry_contract red; 61/61 suite green after the fold.
A partial-entry replace (old_text = a span inside an entry, content = its
replacement) silently overwrote the WHOLE entry: every clause outside the
match was destroyed with success=true, most damagingly through the
write-approval replay path (/memory approve -> apply_memory_pending ->
apply_batch) that exists precisely so background agents can stage writes for
human review (#117952, dup of #59184).
The cluster's repeated fix attempt (#66321, #61357, four closed predecessors)
flipped replace to naive span-splicing (entry.replace(old_text, new, 1)).
That corrupts the canonical identifier-style call (replace(old_text="3.11",
content="Python 3.12 project") -> "Python Python 3.12 project project"),
breaks the background-review refine consumer, and split-brains external
memory mirrors, which receive the raw op content, not a merged entry.
The defect is the CONTRACT, not the mechanism: the schema invited patch-style
calls ("mirrors old_text (patch-tool shape)") while the store commits
whole entries. This pins whole-entry semantics end to end and makes the
overwrite visible instead of silent:
- schema + recovery error text + memory_tool docstring now say content is the
COMPLETE new entry and old_text only locates it (website docs updated in the
same PR)
- a successful replace surfaces replaced_entry / replaced_entries (full text
that was overwritten) on single, batch, and approval-replay paths, so the
caller can re-add lost clauses instead of discovering them gone later
- _mutate gains an optional extra payload field; _apply_batch_op returns the
replaced entry text alongside the error
Live repro on origin/main dec236b21 before: approve-apply of a staged
partial-entry replace truncated a 3-clause entry to the replacement span
alone. After: same final entry (whole-entry contract, unchanged semantics)
plus replaced_entries in the response. Grafted naive span-splice on main:
2 existing tests red (test_replace_entry,
test_attended_review_keeps_full_operation_set) — the regression this PR
avoids. Mutation checks: reverting the visibility fields or the exact-match
priority turns the new invariant tests red.
A short entry whose full text is contained inside a longer sibling entry
was unaddressable: remove('test') against entries ['test', '...tests
pass...'] hit _find_unique_match's substring scan, reported 'Multiple
entries matched', and refused — the entry could never be targeted.
apply_batch hit the same matcher and aborted the whole operation.
_find_unique_match() now prefers whole-entry EXACT matches
(old_text == entry) and only falls back to substring matches when no
entry equals old_text. Both call sites (_edit for single replace/remove,
_apply_batch_op for batch) share the matcher, so the whole bug class is
fixed at one seam. Substring partial matching is unchanged.
Reproduced red on current main (2 invariant tests), 53/53 green after
the fix; 8 sibling memory suites green via scripts/run_tests.sh.
A failed all-or-nothing consolidation must not echo the whole
store back into the turn. Single replace/remove still return
the entry list so the model can retry with exact text.
Background writers that still carry a tombstoned profile as their Hermes
home (reasoning-caps warm thread, models cache, models.dev ETag, gateway
lifecycle ledger, MCP OAuth tokens, memory store) re-created
profiles/<name>/ with a bare mkdir right before an atomic write. Route the
parent-dir creation through mkdir_under_hermes_home so a deleted named
profile raises FileNotFoundError and stays gone, matching the tombstone
contract already enforced for logging and state.
The cap only fires on add/replace, so an externally written over-budget
file rode silently in the system prompt while every later add was refused
with no visible cause. Warn at load; entries stay loaded (never truncate
a user's memories).
Salvage of #10886 (original hunk targeted memory_tool.py before the
store split); authored by @easyvibecoding.
Refs #10877
Review follow-up on the salvaged #103421 guard: the USER.md/MEMORY.md ternary
was a third copy (also _path_for and memory_tool._memory_target_error); use the
path's name. "profile" → "store" in the error since MEMORY.md is not a profile.
apply_batch() committed an empty USER.md/MEMORY.md as a normal
successful write when a consolidation batch removed the last entry.
Refuse all-or-nothing with live entries so background consolidation
keeps at least one entry; a deliberate wipe stays a manual file edit.
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.
memory_tool_store: _error() helper for every failure dict, reload folded into
_mutate, load_from_disk loops over targets with an inline snapshot sanitizer,
_locate inlined into _edit, batch-op splice, drift check compacted; on-disk
format and every result string unchanged (golden corpus).
memory_tool: single _apply_write_gate handles op + batch, _batch_op_line helper,
gate/validation returns folded, on-disk store built directly.
session_search_tool: _get_session_meta unifies 5 get_session lookups, rebuild
note folded into _discover_payload via _ok, lineage dedupe inlined into
_discover, scroll rebind inlined, title-match shaping via one closure, browse
comprehension, unreachable scroll guard dropped, single hermes_state import.
microsoft_graph_client/auth: signatures hugged, bodiless-response handling
inlined, header dict built in one expression, dead from_env removed.
process_registry_notifications: _preamble merges header/task-source/role lines,
_notice_lines shared, table-driven completion status, comprehension headers.
Schemas byte-identical (SCHEMA-OK); golden corpus old-vs-new identical.