Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(memory): ignore leading cd prefix when pairing Bash error recoveries (#3776)

Trîggered143a38d56f5b
diff --git a/headroom/memory/traffic_learner.py b/headroom/memory/traffic_learner.py
index 8727d3c2d..e3ed50ba6 100644
--- a/headroom/memory/traffic_learner.py
+++ b/headroom/memory/traffic_learner.py
@@ -62,6 +62,10 @@ _BASH_VOLATILE_SUFFIX_RE = re.compile(
r"|\s+2>&1|\s+2>/dev/null)+\s*$"
)
+# Leading `cd <dir> && ` / `cd <dir>; ` prefixes. Agents prepend them to most
+# commands, so they carry no signal about which operation was retried.
+_BASH_LEADING_CD_RE = re.compile(r"""^\s*cd\s+(?:"[^"]*"|'[^']*'|(?:\\.|[^\s\\])+)\s*(?:&&|;)\s*""")
+
# Agent harnesses can encode orchestration metadata as user-role messages.
# These prefixes identify whole messages that are not authored by the user.
_HARNESS_USER_PREFIXES = (
@@ -194,7 +198,7 @@ def _normalize_bash_for_hash(cmd: str) -> str:
if not cmd:
return ""
# Drop paging, line-context flags, and redirections that vary between runs.
- trimmed = _BASH_VOLATILE_SUFFIX_RE.sub("", cmd).strip()
+ trimmed = _BASH_VOLATILE_SUFFIX_RE.sub("", _strip_leading_cd(cmd)).strip()
# Cut at the first pipe or && so we hash the primary command, not the tail.
for sep in (" | ", " && "):
idx = trimmed.find(sep)
@@ -204,6 +208,15 @@ def _normalize_bash_for_hash(cmd: str) -> str:
return trimmed
+def _strip_leading_cd(cmd: str) -> str:
+ """Remove leading `cd <dir> &&` / `cd <dir>;` segments from a Bash command."""
+ prev = None
+ while prev != cmd:
+ prev = cmd
+ cmd = _BASH_LEADING_CD_RE.sub("", cmd, count=1)
+ return cmd
+
+
# =============================================================================
# Error Classification (reused from learn/scanner.py patterns)
# =============================================================================
@@ -372,6 +385,8 @@ def _commands_related_as_retry(failed: str, success: str) -> bool:
arguments, and gets rejected. Genuine retries (extra flag, single
arg edit) pass via the edit-distance path.
"""
+ failed = _strip_leading_cd(failed)
+ success = _strip_leading_cd(success)
if not failed or not success or failed == success:
return False
bin_a = _bash_first_binary(failed)
diff --git a/tests/test_memory/test_traffic_learner.py b/tests/test_memory/test_traffic_learner.py
index 4ff1fcc44..a3ed9052c 100644
--- a/tests/test_memory/test_traffic_learner.py
+++ b/tests/test_memory/test_traffic_learner.py
@@ -116,6 +116,23 @@ class TestCommandsRelatedAsRetry:
)
assert not _commands_related_as_retry(failed, success)
+ def test_shared_cd_prefix_alone_is_not_retry(self):
+ # Agents prefix most commands with the same `cd <repo> &&`; that shared
+ # prefix used to satisfy both the binary and the token-overlap checks.
+ cd = 'cd "C:\\Users\\dev\\my-project" && '
+ assert not _commands_related_as_retry(
+ cd + "npx vitest run src/form.test.tsx", cd + "git add -A && git commit -F -"
+ )
+ assert not _commands_related_as_retry(
+ "cd /home/dev/my-project && sed -n '90,130p' app/actions.ts",
+ "cd /home/dev/my-project && cat components/icons.ts",
+ )
+
+ def test_cd_prefixed_retry_still_matches(self):
+ assert _commands_related_as_retry(
+ "cd /home/dev/proj && cargo build", "cd /home/dev/proj && cargo build --release"
+ )
+
def test_empty_or_equal_commands_rejected(self):
assert not _commands_related_as_retry("", "ls")
assert not _commands_related_as_retry("ls", "")
@@ -1930,7 +1947,15 @@ class TestNormalizeBashForHash:
def test_cuts_at_first_chain(self):
# && boundary collapses to just the primary command
- assert _normalize_bash_for_hash("cd /tmp && ls") == "cd /tmp"
+ assert _normalize_bash_for_hash("make build && ls") == "make build"
+
+ def test_strips_leading_cd(self):
+ # A `cd` prefix is not the primary command; keeping it collapsed every
+ # cd-prefixed recovery in a project onto one hash key.
+ assert _normalize_bash_for_hash("cd /tmp && ls") == "ls"
+ assert _normalize_bash_for_hash('cd "C:\\a b"; cd sub && cargo check') == "cargo check"
+ assert _normalize_bash_for_hash(r"cd /home/dev/my\ project && cargo check") == "cargo check"
+ assert _normalize_bash_for_hash("cd /tmp") == "cd /tmp"
class TestParseIsoTimestamp: