One message, three copies
I spent a day inside Hermes Agent, the open-source personal agent from Nous Research, and came out with two pull requests and one issue. One PR fixes a bug where the agent's memory of a long conversation quietly stored the same message two or three times. The other fixes a command-line shortcut that the help text promised and the code didn't deliver. The first is the real work. The second is small, and I'll say so when I get there.
This is the full record: how I picked the work, how I confirmed each bug on current code, what the root cause was, how I fixed it, and how I tested it. I've written it so someone who has never opened the Hermes codebase can follow along.
| What | Link | In one line |
|---|---|---|
| Issue (someone else's) | #137197 | After every compaction, summarized messages reappeared as new rows. One message existed three times. |
| My fix | PR #137577 | Stop the commit from inserting a carried message and then cloning it again. 104 lines in, 15 out, plus tests. |
| Issue (mine) | #137579 | hermes moa rm is advertised in the help text and rejected by the dispatcher. |
| My fix | PR #137580 | One line, plus a test that makes it impossible to add an alias without a handler again. |
A quick vocabulary
Hermes Agent is a personal AI agent. The same core runs behind a command line, a terminal UI, a desktop app, and a messaging gateway that speaks Telegram, Discord, Slack, and about twenty others. Every conversation it has is stored in one SQLite file called state.db.
Context compaction is what the agent does when a conversation gets too long for the model to hold at once. It summarizes the older turns into one short message and keeps the newest few turns word for word. The summary plus those recent turns become the new conversation. The old rows stay in the database so you can still search them.
A row is one line in the messages table. Each message in a conversation is a row. Rows have an id (a number that only goes up), a flag for whether they're active (shown to the model) and a flag for whether they've been compacted (summarized away but kept for search).
A watermark here just means "the highest row id at the moment compaction started." Anything with a bigger id arrived later. You'll see why that matters.
How I picked the work
Hermes is extremely active. The issue tracker has thousands of open issues, most tagged with a priority from P0 to P3, and a triage bot plus maintainers comment on nearly everything within hours. My goal was the highest-impact open issue that was (a) raised by someone else, (b) not assigned to anyone, and (c) not already being fixed by an open pull request.
The first two filters are one command with the GitHub CLI:
gh issue list --repo NousResearch/hermes-agent \
--state open --label P0 --limit 300 \
--json number,title,assignees,labels,comments,createdAt
Then drop anything with an assignee, or labelled duplicate, needs-repro, or awaiting-reporter.
The third filter was the surprise. Nearly every P0 and P1 issue already had an open PR, some filed the same day. Searching PRs by issue number is unreliable because people don't always mention the number. So I asked GitHub's GraphQL API for every pull request that cross-references the issue, and kept only issues with zero open or merged PRs:
q='query($n:Int!){
repository(owner:"NousResearch",name:"hermes-agent"){
issue(number:$n){
timelineItems(itemTypes:[CROSS_REFERENCED_EVENT],first:100){
nodes{... on CrossReferencedEvent{
source{... on PullRequest{number state isDraft}}}}}}}}'
gh api graphql -f query="$q" -F n=137197 \
--jq '[.data.repository.issue.timelineItems.nodes[].source
| select(.number!=null)]
| map(select(.state=="OPEN" or .state=="MERGED"))
| length'
Of the roughly 40 unclaimed issues, most were Windows installer problems, Electron crashes, infrastructure (Docker Hub tags, CDN 404s), or design questions where the reporter was asking maintainers "do you even want this." I wanted a bug that was reproducible on current main without special hardware, a correctness or data-loss problem (the contributing guide puts these at the top of its priority list), and narrow enough to fix in one PR with a real regression test. Issue #137197 fit all three.
Bug 1: compaction stores the same message twice
The report
The title was "Context compaction re-inserts verbatim copies of summarized assistant messages into the session transcript." The reporter runs Hermes on a long-lived Telegram group chat, about 11,000 messages. After every compaction they saw messages that had just been summarized show up again as new rows, byte for byte identical to the originals, all stamped with the compaction's timestamp. One message existed three times. Their evidence was a table of original row id, duplicate row id, and timestamps, lined up exactly with the "context compression done" log line.
A second person reproduced it and gave the key insight: the duplicates come from an overlap between two de-duplication mechanisms that each assume the other has handled the row. They also published a 100-line standalone script that uses only the real SessionDB class and a temp database, no model calls, and prints how many times each assistant text appears after one compaction. On main it printed 1 -> [3]. One text, three copies.
Nobody had opened a PR. The reporter listed two possible fix directions and left the choice to the maintainers.
Background: what a compaction commit actually does
To understand the bug you need the shape of archive_and_compact in hermes_state_messages.py. It runs inside one database transaction and does four things:
- Rewind the carried tail. The compressor keeps the newest N messages word for word. Those will be re-inserted as part of the compacted set, so their original rows are marked hidden and not-compacted ("superseded duplicate"). They stay in the database but are hidden from search, so search doesn't return the same message once per compaction.
- Archive everything else. Rows that were summarized away are marked hidden and compacted ("summarized, still searchable").
- Insert the compacted set. The summary plus the carried tail become fresh active rows.
- Clone the concurrent tail. The summary call to the model is slow, a minute or more. Messages can land in the database while it runs. To avoid losing them, the commit records the watermark when compression starts; any active row with an id above the watermark at commit time is treated as "arrived during the summary, the summary never saw it," and is copied after the compacted set so it stays live.
There are two flavours of this. The "watermark path" uses only the watermark. The newer "named coverage path" is used when the compressor can name the exact row ids it held; the commit archives only those and clones every other active row.
Root cause
Step 3 and step 4 don't talk to each other.
A row can be both carried by the compressor and above the watermark. How? The compressor works on an in-memory list of message dictionaries. Some of those might not have been written to the database yet when the watermark was read, and get flushed during the slow summary call. Or the compressor holds them fine but can't name them by id (repeated identical text makes the content match ambiguous, for example), so the commit falls back to the watermark path. Either way the row ends up with an id above the watermark.
For such a row the commit inserts the carried copy from the compacted set (step 3), and clones the row again because it's above the watermark (step 4). Two live rows, same content, fresh ids. The original is a third copy, hidden. Across many compactions this compounds. The reporter's triple was two compactions each copying the same text once.
There was a second, quieter effect. The step-1 rewind works by position: "take the newest tail_count active rows at or below the watermark." When some of the tail's originals are actually above the watermark, the positional rewind still takes tail_count rows from below it. So it reaches one row too far and flags a genuinely summarized row as a superseded duplicate. That row gets hidden from search. A small data-loss bug riding along with the duplication bug.
Confirming it
I don't trust a bug report until I've seen it fail on current code. I pulled upstream main at commit 2b50c8c5c8, downloaded the reporter's script, pointed it at my checkout, and ran it:
A: duplicated assistant contents after commit: 1 -> [3]
RESULT: FAIL — verbatim duplicates reproduce the issue
Then I read the code path end to end: archive_and_compact, _archive_named_rows, _clone_message_rows, _proved_coverage, _resolve_carried_row_ids, and the agent-side callers that compute the watermark. The maintainers' own docstring on held_archive_watermark even acknowledges the risk in one direction ("capped below it, the clone would land beside its own carried copy") and handles only the case where the last held dict has no id. The general overlap was unhandled.
Writing the test first
The project's testing rules are strict, and worth quoting from their AGENTS.md:
- Always run tests through
scripts/run_tests.sh. It mirrors CI: clean environment,TZ=UTC, a temp home directory, one subprocess per file. - Tests must be behaviour contracts, not snapshots. One or two invariant tests per fix, proven red on the base commit.
- Tests live in the directory mirroring the source file.
I wrote tests/hermes_state/test_compaction_carried_tail_not_cloned.py with three tests:
test_held_row_above_watermark_is_carried_once. Seed four old turns, read the watermark, append a steer and a reply (now above the watermark), then load those two back from the database so the dicts carry a row id, amessage_uid, and a timestamp, exactly like the real compressor's dicts. Commit with[summary, steer, reply]andtail_count=2. Assert: each text exists exactly twice (original plus carried copy, no clone), only one copy is active, both copies share the samemessage_uid, search returns one hit, and every one of the four summarized rows is still marked compacted. That last assertion pins the positional-rewind side effect.test_content_only_carried_copy_is_not_cloned. The reporter's bare scenario: dicts with no id, uid, or timestamp. Assert two copies, one active.test_foreign_identical_row_above_watermark_is_still_cloned. The false-positive guard. A held row below the watermark carries text X; another surface appends a different message with the same text X above the watermark. The foreign one must still be cloned: four rows, two active, two distinctmessage_uids.
On unfixed code, tests 1 and 2 failed (assert 5 == 3, assert 3 == 2) and test 3 passed. Red confirmed.
The fix
The new logic went into hermes_state_coverage.py, the sibling module whose whole job is "which durable rows did the compressor actually hold." The repo is organised as facades plus topical siblings, and new behaviour is supposed to land in the topical sibling, never get appended to the facade.
_carried_tail_ids(conn, tail_ids, compacted_messages) returns, for every row that would otherwise be cloned, which dict in the compacted set already stands for it. A dict claims its row by trying four rules in order:
_carried_tail_slots(carried, compacted_count, tail_count) counts how many of the last tail_count dicts were matched above the watermark. The positional rewind below the watermark then takes that many fewer rows, which closes the quiet data-loss hole too.
In hermes_state_messages.py both commit paths call these:
carried_tail = self._carried_tail_ids(conn, tail_ids, compacted_messages)
clone_ids = [row_id for row_id in tail_ids if row_id not in carried_tail]
tail_below = tail_count - self._carried_tail_slots(
carried_tail, len(compacted_messages), tail_count)
Rows in carried_tail stay in the rewind list (their original becomes a superseded duplicate, same as any carried original) but drop out of the clone list. The inserted-row count and tool-call count only count real clones. Diff size: 104 insertions, 15 deletions across two source files, plus the test file.
A false start worth mentioning
My first version of rule 1 trusted the stamped row id blindly. The wider test run then failed two tests, one of them in an existing file, but only under the CI runner, not when run directly. The cause: that file shares one module-level SUMMARY dict across tests, and the insert helper stamps a row id onto whatever dict it inserts. By the third test that dict carried a stale id from a previous database, which happened to equal a tail row's id in the new database, and my code claimed it. The fix, require the stored content to match before honouring the id, is the same rule the existing _resolve_carried_row_ids already applies. I also made my own test file create a fresh summary dict per test.
Verification
- The reporter's script now prints
1 -> [2]: the original, hidden, plus one live carried copy. - New test file: 2 of 3 fail on
main, 3 of 3 pass on the branch. - Every suite that calls
archive_and_compact(all oftests/hermes_state/, the agent compaction and persistence suites, the TUI gateway queued-prompt suites, the end-to-end compaction and SQLite contention suites): 176 files, 1,818 tests passed. The only four failures were in two files about virtual-machine filesystem detection, which fail identically on untouchedmainon my Mac. ruff checkclean.
The PR
PR #137577, commit fix(state): stop in-place compaction from storing a carried message twice. The description follows the repo's template: what it does and why, root cause in plain words, the changes by file, how to test with the reporter's script, and the checklist.
Bug 2: finding one of my own
How I hunted
The second goal was to find an unreported bug, file it, and fix it. I tried a few systematic approaches, in rough order of how much I expected from each:
- The repo's own advisory lint, which looks for code that reads the home directory without the profile-aware resolver. Zero findings.
- Greps for the bug classes
AGENTS.mdnames: copying the whole environment into child processes, a hardcoded~/.hermes,shell=True. Every hit was in eval scripts, tests, or a site with a written justification. I read the threeshell=Truesites in real code, including one inside a dashboard web router, and each only runs commands from a trusted manifest, not from the request. - The dashboard's security model: the Host and Origin checks and token verification. Solid, with DNS-rebinding protection repeated for WebSockets.
- Exercising every CLI alias.
AGENTS.mdexplicitly warns that argparse stores the literal the user typed, so a command registered aslistwith aliaslsneeds dispatch code that accepts both, and it names a past bug (hermes webhook ls) that came from exactly this. I grepped everyaliases=[in the CLI, about 40, and ran each alias against a throwaway home directory.
Approach 4 paid off twice: once for a bug that was already known, once for a new one.
(A note for anyone scripting this in zsh: an unquoted $c is not word-split in zsh, so my first loop passed "projects ls" as one argument. Use ${=c}.)
The crash that was already reported
hermes secrets bw, hermes secrets op, and their long forms all die with a 1000-frame RecursionError. The parent parser sets a default handler that overrides the child parsers' handler when no third-level action is given, so the handler calls args.func, which is itself, forever.
I then walked the entire argparse tree programmatically, found all eight "intermediate" command nodes, and invoked each without an action. Only the two secrets nodes crashed. Before filing, I searched the tracker and found it already reported as #92799 with two open PRs. I left it alone. Duplicating a tracked bug wastes maintainer time.
The new one: hermes moa rm doesn't work
hermes moa --help prints delete (rm), advertising rm as the short form of delete. But:
$ hermes moa rm my-preset
Unknown moa subcommand: rm
The other aliases on the same command, ls and config, work fine. The root cause is in hermes_cli/moa_cmd.py:
_SUBCOMMANDS = {
"list": _cmd_list,
"ls": _cmd_list,
"config": _cmd_configure,
"configure": _cmd_configure,
"delete": _cmd_delete}
The dispatcher looks up what the user typed in that table and raises "Unknown moa subcommand" on a miss. Whoever wrote the table remembered ls and config but not rm. No existing test covered dispatch; the only moa test file tests the config normaliser.
I searched for duplicates ("moa rm alias", "Unknown moa subcommand"), found none, and filed #137579 with the reproduction, the root cause with the code, and the proposed fix.
The fix, and the test that stops it recurring
The fix is one line:
"delete": _cmd_delete,
"rm": _cmd_delete,
The more interesting part is the test file, tests/hermes_cli/test_moa_cmd_dispatch.py:
test_every_parser_choice_has_a_dispatch_handlerbuilds the real moa parser, reads every subcommand name it accepts (canonical names and aliases, straight from argparse'schoices), and asserts that set is a subset of_SUBCOMMANDS. It's a contract between two pieces of data, what the parser accepts versus what the dispatcher handles, which is exactly the style the repo asks for instead of snapshots. If anyone adds an alias later without a handler, this fails.test_delete_and_its_alias_reach_the_delete_handler, parametrized overdeleteandrm, parses["moa", <spelling>, "preset-x"]with an empty config and assertsSystemExit("Unknown MoA preset: preset-x"). That message is the delete handler's own answer for a missing preset, so getting it proves the alias reached the right handler rather than the dispatcher's generic error.
On main, the first test and the rm case of the second fail. On the branch, all pass, and the live CLI prints Unknown MoA preset: nonexistent-x for hermes moa rm nonexistent-x, identical to hermes moa delete. Links: issue #137579 and PR #137580.
Honest sizing
This second bug is real, user-visible, and matches a bug class the maintainers name explicitly. It's also small. I'd rather be clear about that than oversell it. The heavy lifting of the day was the compaction fix.
What I'd take away
1. Read the project's AGENTS.md and CONTRIBUTING.md before touching code. This one told me where new behaviour goes (topical sibling, not facade), which tests get rejected (snapshots, change-detectors, tests that read source text), how to run tests (the script, never bare pytest), and even listed the alias-dispatch bug class I later found.
2. Verify the premise on current main before writing a line. The guide says the most common reason a well-written PR gets closed is a wrong premise. The reporter's script made this a thirty-second check.
3. Write the failing test first. It forced me to decide what "fixed" means (one live row, original hidden, summarized rows still searchable) before I touched the commit path, and it caught my own false start with stale row ids.
4. Filter issues by "has no PR," not by "is open." On a busy repo, the gap between those two sets is where the unclaimed work lives.
5. Don't duplicate a tracked bug. The secrets crash was the scariest thing I hit, and the right move was to search first and walk away.
6. Two lists that have to agree need a test that says so. The compaction bug was two steps that each assumed the other handled the row. The alias bug was a parser and a dispatch table that drifted apart. Different sizes, same shape: two sources of truth with nothing checking them against each other.
Branches, for the record: fix/compaction-carried-tail-clone (commit eaa6c23516, PR #137577) and fix/moa-rm-alias (PR #137580, issue #137579), with my fork's main synced to upstream 2b50c8c5c8.