← writings

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.

WhatLinkIn 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.

Before compaction: a long row of twelve message boxes. After compaction: one summary box standing in for the first nine, followed by the last three messages kept verbatim. The nine old rows stay in the database, hidden but searchable. before: 12 messages, too long for the model 1 2 3 4 5 6 7 8 9 10 11 12 compaction after: 1 summary + 3 verbatim ("the tail") summary of 1 – 9 10 11 12 rows 1 – 9 stay in the database, hidden from the model, still searchable
Compaction. The old messages don't get deleted; they get summarized and hidden.

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'
A funnel in three stages. About 150 open P0 to P2 issues. About 40 of them have no pull request. One of those is reproducible on main, is a correctness or data-loss problem, and is small enough for one PR: issue 137197. ~150 open P0 – P2 issues, unassigned gh issue list, minus duplicate / needs-repro / awaiting-reporter ~40 with no open or merged PR GraphQL cross-reference check per issue #137197 reproducible on main correctness or data loss one PR + a real test no special hardware
The filter. Most of the forty unclaimed issues were Windows installer problems, Electron crashes, infrastructure, or design questions.

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:

  1. 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.
  2. Archive everything else. Rows that were summarized away are marked hidden and compacted ("summarized, still searchable").
  3. Insert the compacted set. The summary plus the carried tail become fresh active rows.
  4. 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.
A timeline. Compression starts and reads the watermark at row id 100. The slow summary call takes a minute. During that minute rows 101 and 102 arrive. At commit, four steps run inside one transaction: rewind the carried tail, archive the rest, insert summary plus tail, clone rows above 100. start read watermark = row id 100 model writes the summary (slow, ~1 min) row 101 arrives row 102 arrives commit inside one transaction 1. rewind the carried tail (hide originals) 2. archive the summarized rows 3. insert summary + carried tail 4. clone every active row with id > 100 "the summary never saw these" steps 3 and 4 never compare notes. that's the bug.
The four steps of a commit. The watermark is there to protect messages that arrive during the slow summary.

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.

One message, row 102, sits above the watermark and is also in the compressor's carried tail. Step 3 inserts it as a carried copy. Step 4 clones it as a concurrent row. Together with the hidden original that is three copies of one message, two of them live. row 102 "Sure, here's the plan…" in the carried tail (compressor holds it) above the watermark (id 102 > 100) step 3: carried copy new id 204 · active original row 102 hidden, "superseded" step 4: clone new id 206 · active three rows, two of them live, for one message next compaction carries both live ones → it compounds
The overlap. The same row qualifies for step 3 and step 4, and each step assumes the other didn't touch it.

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.

A row of message ids 97 to 102 with the watermark drawn after 100. The tail is two messages, 101 and 102, both above the watermark. The rewind still takes two rows from at or below 100, so it grabs 99 and 100, which were summarized. Row 99 and 100 are marked as duplicates and vanish from search. tail_count = 2, but both tail rows are above the watermark 97 98 99 100 101 102 watermark = 100 the real tail rewind takes "2 newest at or below 100" → 99 and 100 those were summarized, not carried. marked as duplicates, they drop out of search. nobody notices.
The quiet one. Counting by position from the wrong side of the line hides rows that should stay searchable.

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:

  1. 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, a message_uid, and a timestamp, exactly like the real compressor's dicts. Commit with [summary, steer, reply] and tail_count=2. Assert: each text exists exactly twice (original plus carried copy, no clone), only one copy is active, both copies share the same message_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.
  2. 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.
  3. 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 distinct message_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:

A ladder of four matching rules, tried top to bottom. One: the dict's stored row id, but only if the row's content still matches. Two: the message uid, which every copy of a logical message keeps. Three: content plus timestamp. Four: content alone, only when the dict has none of the above. Each dict claims at most one row and each row is claimed once. how a dict claims "that row is me", first rule that fits wins 1 row id stamped on the dict only if the row's stored content still matches. a stale id must not claim a stranger. 2 message_uid the durable per-message id every copy keeps. covers a pruned tool result whose text changed. 3 content identity + timestamp same text at the same moment. 4 content identity alone only when the dict carries none of the above (the reporter's bare case). each dict claims at most one row · each row is claimed once
The matching ladder. The last line is what keeps test 3 honest: a second row with the same text is a different message and keeps its clone.

_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.

Two small tables side by side. Before the fix: the message appears as row 102 hidden, row 204 active, and row 206 active, so the reporter's script prints one to three. After the fix: row 102 hidden and row 204 active, the script prints one to two. before: 1 -> [3] id content active 102 "Sure, here's…" 0 (hidden) 204 "Sure, here's…" 1 206 "Sure, here's…" 1 two live copies. the model sees it twice. after: 1 -> [2] id content active 102 "Sure, here's…" 0 (hidden) 204 "Sure, here's…" 1 one live copy. the original stays, hidden. the hidden original is by design: it's what keeps search from returning the same message per compaction
What the reporter's script sees before and after. Two rows is the correct number, not one.

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 of tests/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 untouched main on my Mac.
  • ruff check clean.

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:

  1. The repo's own advisory lint, which looks for code that reads the home directory without the profile-aware resolver. Zero findings.
  2. Greps for the bug classes AGENTS.md names: 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 three shell=True sites in real code, including one inside a dashboard web router, and each only runs commands from a trusted manifest, not from the request.
  3. The dashboard's security model: the Host and Origin checks and token verification. Solid, with DNS-rebinding protection repeated for WebSockets.
  4. Exercising every CLI alias. AGENTS.md explicitly warns that argparse stores the literal the user typed, so a command registered as list with alias ls needs dispatch code that accepts both, and it names a past bug (hermes webhook ls) that came from exactly this. I grepped every aliases=[ 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.

Two columns. On the left, what the parser accepts: list, ls, config, configure, delete, rm. On the right, what the dispatch table handles: list, ls, config, configure, delete. The rm entry has no partner on the right, and the user sees Unknown moa subcommand. what the parser accepts what the dispatch table handles list ls config configure delete rm list ls config configure delete (missing) rm → "Unknown moa subcommand: rm"
Two lists that have to agree, and nothing made them. The help text came from the left column; the behaviour came from the right.

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_handler builds the real moa parser, reads every subcommand name it accepts (canonical names and aliases, straight from argparse's choices), 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 over delete and rm, parses ["moa", <spelling>, "preset-x"] with an empty config and asserts SystemExit("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.

← more writings