Commit Graph
27 Commits
Author SHA1 Message Date
9321a415a6 fix(memory): scope TrafficLearner's SQLite reads to its user_id (#4850)
## Description

`TrafficLearner` saves its rows under its configured `user_id`, but its
two direct SQLite reads ignored `user_id`:

- `_hydrate_persisted_state` (startup) loaded every user's
`traffic_learner` rows into the dedup maps, then applied `LIMIT
dedup_window`. Bob's learner could bind a pattern hash to Alice's row
and later bump *her* evidence instead of creating his own row. Other
users' rows also used up his window.
- `_load_persisted_patterns_from_sqlite` (used by
`_collect_all_patterns` when writing learned context files) returned
every user's patterns, so Alice's learned text ended up in Bob's files.

Both queries now filter on `user_id = ?`. In hydration the filter runs
before the `LIMIT`. Only matters when several user IDs share one memory
database; a single-user setup (`user_id="default"`) is unchanged.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `headroom/memory/traffic_learner.py`: `WHERE user_id = ?` in both
reads. `_load_persisted_patterns_from_sqlite(db_path, user_id)` takes
the user explicitly (private helper; its only caller is updated).
- `tests/test_memory/test_traffic_learner.py`: new
`TestUserScopedPersistence`, which checks that hydration leaves another
user's row alone and collection excludes other users. Hand-built test
schemas gain the `user_id` column that the real `memories` table has,
and direct helper calls pass `"default"`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# new tests against origin/main (c21b0813)
$ pytest tests/test_memory/test_traffic_learner.py -k TestUserScopedPersistence
E   assert ['Alice-only ...ge workflow."] == ["Bob's package workflow."]
FAILED ...::TestUserScopedPersistence::test_hydration_ignores_other_users_rows
FAILED ...::TestUserScopedPersistence::test_collected_patterns_exclude_other_users
====================== 2 failed, 236 deselected in 2.76s =======================

# this branch
$ pytest tests/test_memory/test_traffic_learner.py
============================= 238 passed in 18.28s =============================
$ pytest tests/test_openai_responses_traffic_learner.py tests/test_learn/test_worktree_merge.py tests/test_learn/test_section_lifecycle.py tests/test_memory/test_learn_flag.py
============================== 47 passed in 4.81s ==============================
$ ruff check / ruff format --check (0.17.3): All checks passed!
$ mypy headroom/memory/traffic_learner.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12. One SQLite `memory.db` holding a
`traffic_learner` row for `alice` and one for `bob`.
- Exact command / steps: `TrafficLearner(backend=<backend pointing at
that db>, user_id="bob")._collect_all_patterns()`.
- Observed result:
```text
origin/main:  bob collects: ['Alice-only procedure.', "Bob's preference."]
this branch:  bob collects: ["Bob's preference."]
```
- Not tested: a full proxy run with `--learn --memory` and several
users.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: see Description
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Rows written before this change already carry the correct `user_id` (the
save path always set it), so no migration is needed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4850"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-15 01:52:47 +05:30
662a7f6fd8 fix(memory): keep learned evidence until persistence succeeds (#4229)
## Description

Closes #4224 and #4226.

A full queue or failed save no longer makes the learner forget a pattern
permanently. Observations received while the save is queued or running
are included too. `min_evidence=1` saves the first sighting.

The review caught another case: SQLite can commit before vector indexing
fails or the task is cancelled. Retrying that save now reuses the
committed row rather than inserting a duplicate. If index repair fails
again, the pattern and its save token stay pending until repair
succeeds.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Documentation update

## Changes Made

- Keep queued patterns as live evidence aggregates until persistence
completes.
- Retain the complete aggregate and its save-attempt token after
failure, cancellation or restart.
- Reconcile only the missing evidence. A delayed SQLite update from a
cancelled task cannot count the same observations twice or move
`last_seen_at` backwards.
- Add real SQLite regressions and document recovery behavior.

## Testing

- [ ] Unit tests pass (pytest) — complete changed learner file verified;
not the entire Python suite locally.
- [ ] Linting passes (ruff check .) — changed-file checks and normal
commit hooks passed.
- [ ] Type checking passes (mypy headroom) — normal mypy commit hook
passed.
- [x] Manual testing performed

### Test Output

```text
Complete tests/test_memory/test_traffic_learner.py:
230 passed in 16.40s
```

The complete learner file ran with the normal installed pytest plugins;
no test selection or warning filters were changed.

The normal full `make ci-precheck` pre-push gate also passed: Rust
formatting, clippy and workspace tests; native extension build; all 181
critical Python tests; commitlint. Rust tests used the supported
`RUST_TEST_THREADS=1` setting; no tests, timeouts or gates were changed
or bypassed.

## Real Behavior Proof

- Environment: Linux x86-64, Python 3.13.14, locally rebuilt native
extension, actual `LocalBackend` with `embedder_backend="onnx"`, SQLite,
and default cache/model settings. No live LLM provider requests.
- Exact command / steps: pass `No, use uv instead of pip for Python
packages.` through the public `TrafficLearner.on_messages` at threshold
three. Make the first three actual vector-index calls raise, then let
the fourth call the original index method. Add observations between
attempts; inspect SQLite, pending ownership and actual search after each
attempt. Persistence, embeddings, cache and retrieval are real; only the
failure boundary is controlled.

The learner tests also cover a rejected SQLite UPDATE, shutdown
continuing after one queued save fails, and index-refresh failure on
already-confirmed evidence.

- Observed result: all phase assertions passed and the standalone
process exited 0.

| Attempt | Rows | SQLite evidence | Pending | Search evidence |
| --- | ---: | ---: | --- | --- |
| Initial index failure | 1 | 3 | yes | not found |
| First repair failure | 1 | 5 | yes | not found |
| Second repair failure | 1 | 6 | yes | not found |
| Successful repair | 1 | 7 | no | 7 |

The original memory ID and save token survive failed repairs. Only the
successful repair marks the pattern saved. Normal evidence-only update
handling is unchanged.

- Not tested: live providers, model quality, Windows/macOS behavior, or
the entire Python suite. Hosted checks for this revision are not claimed
here.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; existing live learning.
- Minimum rollout channel: unchanged.
- Stable/default behavior changed: failed writes retain evidence;
explicitly configured threshold one works; observations during saves are
no longer lost.
- Kill switch / disable path: `--no-learn` or existing memory
configuration.
- Unsafe override required: no.
- Qualification impact: actual persistence and retrieval verified
locally.
- Rollback path: revert the fix; no schema migration.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have made corresponding changes to the documentation
- [x] I did not edit CHANGELOG.md — release-please owns it

## Additional Notes

AI-assisted; no subagents.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4229"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
Co-authored-by: Tejas Chopra <tejas@headroomlabs.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:39:53 -06:00
59dbe98042 fix(memory): skip the edit-distance retry check on long commands (#4371)
## Description

`_commands_related_as_retry` (`headroom/memory/traffic_learner.py`)
compares a failed and a successful Bash command with `_levenshtein`, an
O(n·m) pure-Python loop, on the request path (`on_tool_result`), with no
cap on command length. `_levenshtein`'s own docstring says callers must
keep input sizes reasonable. This adds that cap: commands longer than
`_RETRY_EDIT_DISTANCE_MAX_CHARS` (512) skip the edit-distance path and
are judged by the existing linear shared-token check.

Review round (2026-10-24): `_bash_binaries_match`, which runs before
that cap, also called `_levenshtein` on the first-token basenames with
no length bound (e.g. a 2,000-character first token). When one name is a
prefix of the other their edit distance is exactly the length
difference, so that check now compares lengths (same result, linear) and
no longer calls `_levenshtein`.

Fixes #4367

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/traffic_learner.py`: `_RETRY_EDIT_DISTANCE_MAX_CHARS
= 512`; `_commands_related_as_retry` runs the normalized edit-distance
test only when the longer command is within the cap. The
shared-substantive-token check is unchanged.
- `headroom/memory/traffic_learner.py` (review round):
`_bash_binaries_match` replaces `_levenshtein(a_base, b_base) <= 2` with
`abs(len(a_base) - len(b_base)) <= 2`, guarded by the same `startswith`
prefix test, so the accepted pairs are identical and no edit distance is
computed on a first token. This does not reuse
`_RETRY_EDIT_DISTANCE_MAX_CHARS` because no quadratic comparison remains
to bound.
- `headroom/memory/traffic_learner.py` (review round):
`_paths_related_as_typo` returns False for a basename longer than
`_RETRY_EDIT_DISTANCE_MAX_CHARS` before calling `_levenshtein`; test
`test_oversized_path_basename_skips_the_quadratic_edit_distance`.
- `tests/test_memory/test_traffic_learner.py`:
`test_long_commands_skip_the_quadratic_edit_distance` (wraps
`_levenshtein` so any call on an input over the cap fails the test; a
long related pair is still matched through the token path, a long
unrelated pair is not) and
`test_short_commands_still_use_edit_distance`.
- `tests/test_memory/test_traffic_learner.py` (review round):
`test_oversized_first_token_skips_the_quadratic_edit_distance` (records
every `_levenshtein` call on an input over 512 characters;
`_commands_related_as_retry('x'*2000 + ' execute', 'x'*2000 + '3
execute')` must be related and make no such call),
`test_short_binary_names_keep_the_prefix_tolerance` (the pre-existing
0-2 character prefix tolerance is unchanged), and
`test_oversized_first_token_through_on_tool_result` (same pair of
commands through `TrafficLearner.on_tool_result`: no oversized call, one
retry pattern extracted).

## Testing

- [x] Unit tests pass (`pytest`) —
`tests/test_memory/test_traffic_learner.py`: 223 passed; with the
neighbouring learner/cold-start test files, 256 passed
- [x] Linting passes (`ruff check .`) — on the two changed files, plus
`ruff format --check`
- [ ] Type checking passes (`mypy headroom`) — not run; one module
constant and one extra comparison
- [x] New tests added for new functionality
- [x] Manual testing performed — end-to-end driver through
`TrafficLearner.on_tool_result` (below)

### Test Output

```text
# new tests, source at main 4c7acba5 (fail-before)
$ pytest tests/test_memory/test_traffic_learner.py -q -k long_commands --tb=line
FAILED tests/test_memory/test_traffic_learner.py::test_long_commands_skip_the_quadratic_edit_distance   # edit distance computed on an oversized command
1 failed, 219 deselected in 1.46s

# review round: new tests with ONLY the _bash_binaries_match change reverted (head c5681e22 source)
$ pytest tests/test_memory/test_traffic_learner.py -q
FAILED ...::test_oversized_first_token_skips_the_quadratic_edit_distance   # recorded oversized calls: [(2000, 2001), ...] != []
FAILED ...::test_oversized_first_token_through_on_tool_result              # recorded oversized calls: [(2000, 2001)] != []
2 failed, 221 passed in 8.64s

# with the fix
$ pytest tests/test_memory/test_traffic_learner.py -q
220 passed in 2.82s

# review round, with the fix (2707c5b8)
$ pytest tests/test_memory/test_traffic_learner.py -q
223 passed in 3.20s
$ pytest tests/test_memory/test_traffic_learner.py tests/test_memory/test_learn_flag.py tests/test_openai_responses_traffic_learner.py tests/test_cold_start_fast_pass.py tests/test_cache_mode_cold_start.py -q
256 passed, 1 warning in 13.23s

$ ruff check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py && ruff format --check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py
All checks passed!
2 files already formatted

# end to end through the proxy's entry point, TrafficLearner.on_tool_result:
# a failed then a successful Bash tool result whose commands are ~7,880 chars (a heredoc config + a flag change)
[main @ 4c7acba5]                         2nd on_tool_result: 16158.66 ms   patterns: 1 (error_recovery)
[fix-traffic-learner-long-commands @ c5681e22]  2nd on_tool_result:     0.38 ms   patterns: 1 (error_recovery, identical content_hash ca12b320441b0edb)
```

## Real Behavior Proof

- Environment: WSL2 Ubuntu, Python 3.12.15, pytest 9.1.1, ruff 0.17.1; a
clone of this fork at `4c7acba5` with the core runtime dependencies only
- Exact command / steps: add the tests alone and run them (the
long-command test fails: `_levenshtein` is called on an input over 512
characters), apply the source change and run the whole traffic-learner
test file, then ruff, as pasted above
- Observed result: with the fix the edit-distance loop is never entered
for a command longer than 512 characters, a long genuine retry is still
recognised through the token path, and all 218 existing traffic-learner
tests pass unchanged
- End-to-end: a driver awaits `TrafficLearner().on_tool_result(...)`
twice — a failed Bash result, then a successful retry — with
~7,880-character commands, on `git archive` exports of `main` and of
this branch. On `main` the second call takes 16.2 s (the edit-distance
loop); on this branch 0.38 ms. Both extract the same single
`error_recovery` pattern (same `content_hash`), so the recognised retry
is unchanged.
- Review round (oversized first token, unit level only): `_levenshtein`
is wrapped to record any call whose argument is over 512 characters
instead of timing it. On `c5681e22`,
`_commands_related_as_retry('x'*2000 + ' execute', 'x'*2000 + '3
execute')` makes a recorded call with lengths (2000, 2001) from
`_bash_binaries_match`; with `2707c5b8` the record is empty and the pair
is still related. The same two commands through
`TrafficLearner.on_tool_result` behave the same way (`[(2000, 2001)]`
before, `[]` after, one retry pattern extracted). The ~7,880-character
`on_tool_result` timing above (16,158.66 ms on `main`, 0.38 ms here)
covers a long argument body, not a long first token, and was not re-run
for this round.
- Not tested: a live proxy process forwarding real agent traffic (the
driver calls the same entry point the handlers await); a wall-clock
timing of the long-first-token case on `main` or on this branch

## Runtime Rollout Safety

- Rollout-managed feature(s): none (traffic learning is not behind a
rollout flag)
- Minimum rollout channel: n/a (not rollout-managed)
- Stable/default behavior changed: only for command pairs longer than
512 characters, which are now matched by shared tokens alone
- Kill switch / disable path: none added
- Unsafe override required: no
- Qualification impact: none known; no `CHANGELOG.md` edit
(release-please)
- Rollback path: revert this commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (none
needed)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
test runs above were executed on my machine on a clone of this fork.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-28 21:20:11 -05:00
4e6e955cad fix(memory): log storage and SQLite failures that currently make retrieval miss silently (#4111)
## Description

Several storage paths turn a real failure into a quiet miss. They either
log nothing, or log a line that does not say which operation or file
failed. When CCR or memory retrieval misses, an operator cannot tell
corruption or a broken plugin from a genuine "not found". This PR adds
the missing log lines. Return values and control flow do not change.

Refs #4136

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/storage/__init__.py` (`create_storage`):
- A `headroom.storage_backend` plugin that raised on load was swallowed
by `except Exception: pass`. So was a scheme with no plugin. Both then
fell back to `SQLiteStorage(store_url)`, which opens a SQLite file named
after the URL.
- Both cases now log a warning that names the scheme. The URL itself is
not logged, because it can carry credentials.
- A plugin that raises is logged with the exception type only, because
its text can echo the URL. A separate DEBUG line gives
`log_safety.describe_exception` (exception types and code locations,
never the message), so no level carries the URL or its password.
  - The module gets a `logger`.
- `headroom/cache/backends/sqlite.py` (CCR store):
- `_entry_from_json` returned `None` with no log for a row that fails to
decode or rebuild. So `get()` reported a plain miss for an entry that
exists but is unreadable.
- It now logs a warning with the hash, the db path and the exception
type. `items()` decodes every row on each eviction pass, so the warning
fires once per hash.
- The once-per-hash guard is `log_safety.WarnOnce`. Within a one-hour
window it warns for at most 1,000 hashes, then logs one overflow
warning, and later rows log at DEBUG only, so repeated eviction scans
over many bad rows cannot flood the log. When the window ends, a row
that is still broken warns again, about once an hour. A hash is used up
only while WARNING is enabled.
- CCR keys come from model-issued retrieve calls, so they are logged
through `log_safety.safe_id`: a repr (newlines escaped) capped at 80
characters.
- Failed `delete`/`exists`/`clear`/`count`/`keys`/`items`/`get_stats`
all logged as `"op"`. Each now logs its real name, with the key for
`get`/`set`/`delete`/`exists`.
  - The transient-error warning now includes the db path.
- `headroom/memory/traffic_learner.py`: the two read-only SQLite reads
returned `[]` on `OperationalError`/`DatabaseError` with no log: the
hydrate path and `_load_persisted_patterns_from_sqlite`. Both now warn
with the db path. Also:
- dropped a redundant `conn.close()` in an `except` whose `finally`
already closes;
- the two best-effort `conn.close()` calls now catch `sqlite3.Error` and
log at debug, instead of `except Exception: pass`.
- `headroom/memory/backends/direct_mem0.py`:
`get_memory`/`delete_memory` turned any Qdrant/Neo4j exception into "not
found". They now warn with the memory id and the exception type first.
- The exception text is not logged at any level, because backend errors
can carry stored memory or connection details. A DEBUG line gives
`describe_exception`.
- Memory ids come from the model, so they are logged through
`log_safety.safe_id`, which escapes newlines and caps the length.
- mem0 2.x `Memory.delete` raises exactly `ValueError(f"Memory with id
{memory_id} not found")` for an unknown id. Only that message, for the
requested id, logs at DEBUG; the delete is model-driven, so it is
expected. Any other `ValueError`, such as a missing collection, still
warns.
- When a corrupt CCR store is recreated, the unreadable-row guard starts
fresh, because the new file has no rows.
- `headroom/learn/registry.py`: a built-in learn plugin that fails to
import was logged at debug, so `headroom learn --agent <name>` only said
"Unknown agent". It is now a warning with the traceback. Built-in
plugins use only the stdlib, so this never fires on a healthy install.
- `headroom/cache/compression_store.py`: the "Failed to load CCR
backend" warning now says it falls back to the in-process store, and
what that costs. This matches the SQLite branch next to it. It logs the
exception type only, because the backend's text can echo
`HEADROOM_REDIS_URL`. DEBUG gets `describe_exception`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest -q -p no:cacheprovider tests/test_storage_backends.py tests/test_storage tests/test_ccr_sqlite_backend.py tests/test_compression_store.py tests/test_learn/test_registry.py tests/test_memory/test_traffic_learner.py tests/test_memory/test_direct_mem0.py tests/test_private_state_files.py tests/test_adapter_hooks.py tests/test_cache/test_backends.py tests/test_learn/test_opencode_scanner.py tests/test_openai_responses_traffic_learner.py tests/test_learn/test_section_lifecycle.py tests/test_learn/test_worktree_merge.py tests/test_memory_handler_native_ops.py
================= 537 passed, 1 skipped, 5 warnings in 34.37s ==================
# The three new tests against origin/main (product code reverted):
FAILED tests/test_storage_backends.py::test_create_storage_warns_when_a_backend_plugin_fails_to_load
FAILED tests/test_ccr_sqlite_backend.py::TestSQLiteBackend::test_unreadable_row_is_logged_once_and_healthy_rows_are_not
FAILED tests/test_learn/test_registry.py::TestBuiltinLoadFailure::test_broken_builtin_plugin_is_logged_as_a_warning
$ uvx ruff@0.16.8 check <changed files>
All checks passed!
# Added in review: the hydration-failure warning; mem0 delete/get paths (only mem0's exact missing-memory message is quiet; a missing collection warns); newline and 100,000-char model ids; two scans over more bad rows than the cap; and storage-plugin, CCR-backend and mem0 failures whose records are rendered with logging.Formatter at DEBUG and WARNING and checked for credential and content canaries.
# Those tests against the previous head 6c1ad49c, in a scratch worktree:
FAILED tests/test_ccr_sqlite_backend.py::TestSQLiteBackend::test_repeated_scans_over_the_cap_stay_bounded
FAILED tests/test_storage_backends.py::test_create_storage_warns_when_a_backend_plugin_fails_to_load
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[delete_memory-exc1-True]
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[delete_memory-exc4-True]
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[get_memory-exc5-True]
FAILED tests/test_adapter_hooks.py::TestCCREntryPointLoading::test_failing_backend_plugin_logs_no_credentials_at_any_level
$ mypy <6 changed product files> --ignore-missing-imports
Success: no issues found in 6 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, repo .venv, branch checkout at
72a166cb (base a9815bbb plus main and #4138 merged in), temp HOME /
HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps: two runs from this checkout, listed below.
- Ran the shared smoke harness, which starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic and one
OpenAI request with a compressible tool result.
- Ran a direct, unmocked script at DEBUG. A storage plugin raises an
error that quotes its `pg://user:CRED_CANARY@...` URL. Then 5 unreadable
rows are written into a real CCR SQLite store (the cap is lowered to 3
for the run), and `items()` scans it twice.
- Observed result: as listed below. The raw output is in the blocks
after this list.
- Both proxy requests return HTTP 200 with savings, and the proxy log
has no new warnings.
- The storage fallback logs the scheme and exception type at WARNING,
and only types and code locations at DEBUG. `CRED_CANARY` appears
nowhere in the output.
- The CCR store warns for 3 rows, then once for the overflow, and the
second scan (inside the same hour) adds nothing. All 5 rows are kept,
and reads miss as before.
- Not tested: the two paths listed below.
- A live Qdrant/Neo4j outage on the DirectMem0 path. Unit tests with a
raising client cover it.
  - A real third-party storage or CCR plugin.

```text
$ bash smoke.sh <worktree>
branch: cleanup/memory-cache-storage-logging @ 72a166cb
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you 
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$TMP/home HEADROOM_WORKSPACE_DIR=$TMP/ws CODEX_HOME=$TMP/codex python -u run.py   # logging at DEBUG
INFO headroom._ort - Pinned ORT_DYLIB_PATH to bundled ONNX Runtime: /Users/tejas/headroom/.venv/lib/python3.12/site-packages/onnxruntime/capi/libonnxruntime.1.26.0.dylib
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<ValueError>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: ValueError at run.py:11 in factory <- headroom/storage/__init__.py:70 in create_storage
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad0' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad1' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad2' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - More than 3 distinct unreadable CCR SQLite entries; further ones are logged at debug only
scan 1 -> []
scan 2 -> []
rows kept: 5
```

Update 2026-10-15 (head `4e78ca73`). Plugin-load warnings now name the
exception through `safe_id`, which renders `<ValueError>`, or `<object>`
for a class whose name is not a plain identifier. The learn-plugin
failures no longer put a traceback in the WARNING. This is a direct,
unmocked run at DEBUG with `HEADROOM_DEBUG_DUMP` unset. A storage plugin
and an external learn plugin raise errors quoting
`pg://user:CRED_CANARY@db`, one of them through a class named
`PRIVATE_CREDENTIAL_CANARY\nFORGED_LOG_ENTRY`. `grep -c 'CANARY|FORGED'`
on the output gives 0.

```text
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<ValueError>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: ValueError at headroom/storage/__init__.py:70 in create_storage
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<object>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: <exception> at headroom/storage/__init__.py:70 in create_storage
WARNING headroom.learn.registry - Failed to load external learn plugin 'broken' (<object>)
DEBUG headroom.learn.registry - External learn plugin 'broken' failure: <exception> at headroom/learn/registry.py:52 in _discover
learn plugins: ['claude', 'codex', 'gemini', 'grok', 'opencode']
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; logging only.
- Stable/default behavior changed: No. Only log output changes. All
return values and fallbacks are as before.
- Kill switch / disable path: Standard logging level configuration for
the `headroom.*` loggers.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A.

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- Documentation: N/A, because no user-facing option changes.
- On the DirectMem0 path, deleting an unknown id stays quiet at the
default level. Only real backend failures warn.
- Depends on #4138; its two files show in this diff until it merges.
- The `describe_exception` calls run only when
`logger.isEnabledFor(logging.DEBUG)`, so a failure path does no
formatting work at INFO. That PR also touches
`headroom/proxy/handlers/_debug_dump.py`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-16 14:30:34 -07:00
Tejas ChopraandClaude Opus 5.5 e6eaa41179 fix(learn): make live traffic learning use the shared error classifier (#4110)
## Description

Live traffic learning (`--learn`) decides whether a tool result failed,
and why, with its own copy of the learn error patterns in
`memory/traffic_learner.py`. OpenAI-format tool results carry no
`is_error` flag, so on the OpenAI/Responses path the learner sniffs the
output text. The copy has two bugs:

1. **"exit code 0" counted as an error.** Codex, Grok and opencode
append `exit code 0` to the output of every successful shell command.
The copy matched any `exit code` text. So every successful Codex shell
call through the OpenAI path was recorded as a failure, which can turn
into bogus "command X fails, use Y" recovery patterns.
2. **Timeouts and connection errors filed as `runtime_error`.** Every
Python exception repr is `XxxError: ...`. The copy checked its generic
`Error:` pattern before `TimeoutError`, so `TimeoutError: ...` became
`runtime_error`, and it had no connection-error category at all. The
shared `classify_error` in `learn/_shared.py` checks those first.

**Exactly what changes:**
- **Category** (which kind of error) now comes from the shared
`headroom.learn._shared.classify_error`. Timeouts become `timeout`,
connection errors `connection_error`, and an error that matches no
pattern becomes `unknown` instead of `None`.
- **Detection** (whether it is an error at all) keeps the old patterns:
case-insensitive, over the first 2000 characters. Only the exit-code
rule changes:
- an exit code or exit status counts as an error only when it is
nonzero, so `exit code 0` and `exited with exit code 0` are not errors;
  - `exit code 2`, `Exit code: 1` and `exited with status 1` still are;
- `non-zero` still counts, and so does an `exited with ...` line that
carries no code of its own.
- The shared `is_error_content` is **not** used for detection. It is
narrower (a case-sensitive substring list over 1000 characters) and
would miss lowercase `no such file` and `permission denied`, `EACCES`,
`EPERM`, `does not exist`, `Exception:`, `non-zero` and `exited with`.
- I checked a 55-row truth table from review, over real tool-output
strings. Detection matches the old detector on every row except the two
`exit code 0` rows, which flip from error to not-an-error.
- Category changes on that table:
  - `TimeoutError: ...` and `rpc error: deadline exceeded` → `timeout`;
  - `ConnectionError: ...` → `connection_error`;
- a traceback mentioning `net/network_utils.py` → `connection_error`.
This comes from the shared `network` pattern; see Additional Notes.

Refs #4136

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/traffic_learner.py`:
  - Replace the copied `_ERROR_PATTERNS`/`_classify_error` with these:
- `_ERROR_SIGNALS`, the old detection patterns minus the exit-code one;
- `_exit_status_is_error`, the nonzero-only exit-code rule. Signed codes
such as `-9` count, and `exit code 0` never hides another failure in the
same output: a second nonzero code, `exited with signal` or `killed by
signal`. Status evidence belongs to its own line: an `exited with ...`
line with no code of its own is a failure even when another line says
`exit code 0`. A line that ends at `exited with` continues on the next
line, so `Process exited with\nexit code 0` stays one zero status. A
standalone `Killed` line (the shell's SIGKILL message) counts only when
no exit status is reported, since a successful command can print that
word, and it is recognized even below the 10-character short-content
cut-off;
    - `_is_error`, the same length and 2000-character window as before.
  - `on_tool_result` records `classify_error(output).value`.
- Both extractors keep calling `_is_error`: the Anthropic fallback sniff
and the OpenAI sniff.
- `headroom/learn/_shared.py`: `classify_error` maps signal kills
(`killed by signal`, a standalone `Killed` or `Killed: 9` line) to
`exit_code`, since a shell reports them as status 128+N. They were
`unknown`.
- `tests/test_memory/test_traffic_learner.py`:
  - `TestErrorClassification` drives `TrafficLearner` itself.
- A parametrized detection table covers: the exit-code-0 rows; signed
codes; `exit code 0` next to a nonzero code, a signal or `Killed`;
nonzero, `non-zero` and `exited with status 1`; an exit code and a
traceback after 1500 characters; the lowercase, `EACCES`, `EPERM`, `does
not exist`, `Exception:` and `deadline exceeded` signals; and clean
outputs.
- A parametrized category table includes `timeout`, `connection_error`
and the signal kills.
- An end-to-end table runs the OpenAI extractor's result through
`on_tool_result` and checks the recorded `is_error` and category. It
covers a bare `Killed`, `worker exited with an error` plus a wrapper
`exit code 0`, `Killed` plus `exit code 0`, and the controls: clean
`exit code 0`, a signal kill plus a wrapper zero, and `-9`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# New tests against origin/main's traffic_learner.py:
FAILED tests/test_memory/test_traffic_learner.py::TestErrorClassification::test_error_detection[Process exited with exit code 0\nall tests passed-False]
FAILED tests/test_memory/test_traffic_learner.py::TestErrorClassification::test_error_detection[README.md\nsrc\nexit code 0-False]
FAILED tests/test_memory/test_traffic_learner.py::TestErrorClassification::test_error_category_recorded[TimeoutError: deadline exceeded after 30s-timeout]
FAILED tests/test_memory/test_traffic_learner.py::TestErrorClassification::test_error_category_recorded[ConnectionError: [Errno 111] Connection refused-connection_error]
================= 4 failed, 33 passed, 159 deselected in 0.50s =================
# With this change:
$ pytest -q -p no:cacheprovider tests/test_memory/test_traffic_learner.py tests/test_openai_responses_traffic_learner.py tests/test_learn/test_section_lifecycle.py tests/test_learn/test_worktree_merge.py tests/test_learn/test_error_classification.py tests/test_openai_codex_routing.py tests/test_openai_codex_ws_timings.py tests/test_cache_mode_cold_start.py
============================= 290 passed in 39.55s =============================
# The new bare-Killed and wrapper-zero rows against the previous commit (50723621), in a scratch worktree: 4 FAILED. `Killed\nexit code 0` already passed there.
# 55-row truth table (detection must equal the old _is_error except the two "exit code 0" rows):
mismatches: 0
$ mypy headroom/memory/traffic_learner.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, repo .venv, branch checkout at
e063c64b (re-checked at 98f9ea57) (base a9815bbb), temp HOME /
HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps:
- Ran the shared smoke harness, which starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic and one
OpenAI request with a compressible tool result.
- Ran a direct script that feeds seven OpenAI tool messages through
`TrafficLearner.extract_tool_results_from_openai_messages` and then
`on_tool_result`, as the proxy does, and prints what the learner
recorded.
- Ran a script over the reviewer's 55 tool-output strings that compares
the new `_is_error` with the old one.
- Observed result:
- Both proxy requests return HTTP 200 with savings, with no new
warnings.
- `exit code 0` alone is a success, and so is a `Killed` line printed by
a command that reports `exit code 0`.
- A signed code (`-9`), a signal kill, or a worker's `exited with an
error` is a failure, even next to a wrapper's `exit code 0`. So is a
bare `Killed`.
- Signal kills are categorized as `exit_code`, and a real error keeps
its own category.
  - 0 detection mismatches outside the intended rows.
- Not tested: A live Codex session through the proxy with `--learn`. The
smoke run does not send shell tool outputs, so the direct script covers
that path.

```text
$ bash smoke.sh <worktree>
branch: cleanup/memory-cache-traffic-error-classifier @ e063c64b
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you 
   2 headroom.transforms.kompress_compressor - WARNING - Kompress: 'onnx/kompress-int8-wo.onnx' for chopratejas/kompress-v2-base is not cached and HEADROOM_OFFLINE forbids fetching it (HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that n
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$TMP/home HEADROOM_WORKSPACE_DIR=$TMP/ws CODEX_HOME=$TMP/codex python run.py
'ok: 3 files\nexit code 0'                                 is_error=False category=None
'command terminated\nexit code -9'                         is_error=True  category=exit_code
'worker killed by signal SIGKILL\nwrapper exit code 0'     is_error=True  category=exit_code
'Killed'                                                   is_error=True  category=exit_code
'Killed\nexit code 0'                                      is_error=False category=None
'worker exited with an error\nwrapper exit code 0'         is_error=True  category=exit_code
"ModuleNotFoundError: No module named 'foo'\nexit code 1"  is_error=True  category=module_not_found
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None. This only affects `--learn` (live
traffic learning), which is opt-in.
- Minimum rollout channel: Stable; this is a classification bug fix on
an opt-in path.
- Stable/default behavior changed:
- Default proxy behaviour is unchanged. Only runs with `--learn` on see
a difference.
- Output whose only failure signal is an exit code of 0 is no longer
counted as a failure.
  - Error categories use the shared classifier.
  - An unmatched error is labelled `unknown`.
- Kill switch / disable path: Run without `--learn`.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A.

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- Documentation: the behaviour change is recorded in the cleanup docs
ledger for the separate docs PR.
- Detection and categorisation stay separate on purpose. Making the
shared `is_error_content` as broad as this detector would also change
the `headroom learn` scanners, so that belongs in its own PR.
- Follow-up, pre-existing in `learn/_shared.py`: its `network` pattern
files a traceback that mentions a path like `net/network_utils.py` as
`connection_error`.
- Patterns already persisted with a category from the old copy are left
as they are.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:06:10 -07:00
ChesterandJerrettDavis 1631cde686 fix(learn): preserve stable traffic pattern items (#2293)
## Description

Fixes #2294. Follow-up to #231.

TrafficLearner can re-surface a learned section with only a subset of
previously written patterns. The writer currently replaces a same-named
section as one unit, so a valid prior preference, environment fact, or
architecture rule can disappear even though it was not contradicted.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Add opt-in same-section markdown-item preservation to Recommendation.
- Render stable pattern IDs for TrafficLearner preference, environment,
and architecture bullets.
- Prefer new text when a stable ID reappears and deduplicate legacy
ID-less bullets by visible content.
- Keep error-recovery sections authoritative so expiry and refinement
still remove stale entries.
- Leave every other Headroom Learn analyzer on the existing same-section
replacement behavior.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
170 focused writer and TrafficLearner tests passed
full tests/test_learn plus TrafficLearner run completed without failures
ruff check: passed
ruff format --check: passed
```

## Real Behavior Proof

- Environment: macOS, Python 3.13, current Headroom main.
- Exact command / steps: write a prior Learned: preference section
containing a stable-ID item and a legacy ID-less item, merge a new
recommendation with the same section and stable ID, then inspect the
rebuilt marker block.
- Observed result: new text wins for the repeated stable ID, the
unrelated prior bullet remains, and the legacy duplicate appears only
once. Error-recovery recommendations retain replacement behavior.
- Not tested: full repository suite, live proxy traffic, or migration of
arbitrary non-list markdown sections.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented code where the behavior is not self-explanatory
- [x] I have made corresponding documentation changes
- [x] My changes generate no new warnings
- [x] I have added tests that prove the fix is effective
- [x] New and existing focused unit tests pass locally
- [x] I have updated CHANGELOG.md if applicable

## Screenshots (if applicable)

Not applicable.

## Additional Notes

Draft for maintainer feedback on the opt-in merge boundary and stable-ID
representation. Already persisted incorrect rules are intentionally not
deleted automatically.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-02 23:34:27 -05:00
gglucassandClaude Fable 5 4257ed4df3 feat(memory): persist TrafficLearner pending evidence across restarts + expose learner stats (#3104)
## Description

Pending (sub-threshold) TrafficLearner evidence lives only in
`_pattern_counts`, so every proxy restart zeroes the counters. A user
who accumulates 4 sightings of a pattern loses all of them on the next
app update or quit, which makes `min_evidence=5` effectively unreachable
for short or restart-heavy sessions - auto-learning looks dead even
though it is working. (Surfaced by a beta tester who used Claude Code ~6
hours across several days behind the proxy and saw zero learnings.)

This PR persists pending evidence across restarts via a
`pending_patterns.json` sidecar next to `memory.db`, and exposes learner
progress in the `/stats` payload so dashboards can show that learning is
alive before the first pattern crosses the threshold.

Follow-up to #2579, which bounded the same accumulator (the LRU cap is
respected on load).

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `TrafficLearner._save_pending_state()`: snapshot `_pattern_counts` to
`pending_patterns.json` (atomic tmp+rename), called on `stop()` and on
each debounced flush cycle so a crash loses at most one debounce window.
- `TrafficLearner._load_pending_state()`: rehydrate on `start()` after
`_hydrate_persisted_state()`; skips entries whose hash is already
persisted (re-sightings bump the existing row instead), tolerates
corrupt/unreadable sidecars, and respects `max_pending_patterns`.
- `get_stats()` now includes `min_evidence` so consumers can render
progress like "seen 3 of 5 times".
- `/stats` payload gains a `traffic_learner` block
(`proxy.traffic_learner.get_stats()`, `null` when learning is disabled).
- 3 new tests: restart survival end to end, corrupt sidecar ignored,
already-saved hash not rehydrated.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run --frozen --extra dev pytest tests/test_memory/test_traffic_learner.py
============================= 157 passed in 2.82s ==============================

$ uvx ruff check headroom/memory/traffic_learner.py headroom/proxy/server.py tests/test_memory/test_traffic_learner.py
All checks passed!
$ uvx ruff format --check headroom/memory/traffic_learner.py headroom/proxy/server.py tests/test_memory/test_traffic_learner.py
3 files already formatted

$ uv run --frozen --extra dev mypy headroom/memory/traffic_learner.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS 15.6 (Darwin 24.6.0), Python 3.12, branch at
8895e054
- Exact command / steps: scripted two learner "processes" against the
same memory.db in a temp dir: process 1 accumulates 4 sightings of one
ENVIRONMENT pattern (min_evidence=5) and stops; process 2 starts fresh,
then sees the pattern a 5th time.
- Observed result: process 1 stats `{'patterns_extracted': 4,
'patterns_saved': 0, 'pending_patterns': 1, 'min_evidence': 5, ...}`;
sidecar after stop contains the pattern with `"count": 4`; process 2
stats after restart show `'pending_patterns': 1` before any traffic;
after the 5th sighting the DB row is saved with `evidence_count == 5`.
- Not tested: the full proxy path over live agent traffic (learner unit
surface only); mem0/remote backends, where `_resolve_backend_db_path`
returns None and persistence is a silent no-op (pre-existing behavior
for hydrate as well).

## Runtime Rollout Safety

- Rollout-managed feature(s): none - not behind a rollout flag.
- Minimum rollout channel: n/a
- Stable/default behavior changed: pending evidence now survives
restarts (the intended change); a small `pending_patterns.json` appears
next to memory.db. No change when learning is disabled or no local
backend is configured.
- Kill switch / disable path: disabling the traffic learner (existing
toggle) stops both writes and reads; deleting the sidecar restores
per-process behavior.
- Unsafe override required: no
- Qualification impact: none - `/stats` gains one additive key.
- Rollback path: revert the commit; stale sidecars are ignored dead
weight for older builds (never read).

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-10-01 16:09:01 -05:00
TrîggeredandJD Davis 143a38d56f fix(memory): ignore leading cd prefix when pairing Bash error recoveries (#3776)
## Description

`TrafficLearner` pairs unrelated Bash commands into `Learned: error
recovery` rules when both commands start with the same `cd <dir> &&`
prefix. Coding agents add that prefix to almost every Bash call, so most
Bash recoveries written to `MEMORY.md` are bogus. Two examples written
to my `MEMORY.md`:

```
- Command `cd "C:\...\repo" && grep -rn "shopping-vintage" ... -l .` fails (timeout).
  Use `cd "C:\...\repo" && cat components/places/categoryIcons.ts && ...` instead.
- Command `cd "C:\...\repo" && npx vitest run "...SubmitPlaceForm.test.tsx" 2>&1 | tail -40` fails (runtime_error).
  Use `cd "C:\...\repo" && git add -A && git commit -F - <<'EOF' ...` instead.
```

The second rule tells the agent to commit instead of running the tests.

Two defects compound:

1. **Matcher false positives.** `_commands_related_as_retry` requires
the same first binary, plus either ≤40% edit distance or a shared
substantive token. When both commands share a `cd <dir> &&` prefix, the
first binary is always `cd` and the directory path is always a shared
token of ≥5 characters, so any two such commands pass.
2. **Hash collapse inflates evidence.** `_normalize_bash_for_hash` cuts
at the first `&&`, so every cd-prefixed pair hashes to
`error_recovery|Bash|cd <dir>|cd <dir>`. Unrelated pairs in one project
merge into a single row whose evidence is the sum of all of them. That
is how they get past the `min_evidence` gate.

This is a follow-up to #326, which introduced the retry matcher and the
evidence gate. I found no existing issue or PR for this.

Closes # (no existing issue)

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Add `_strip_leading_cd()` in `headroom/memory/traffic_learner.py`. It
removes leading `cd <dir> &&` / `cd <dir>;` segments, including quoted
paths, backslash-escaped spaces (`cd /home/dev/my\ project && ...`) and
repeated segments. A bare `cd <dir>` with no chain is left unchanged.
- Apply it in `_commands_related_as_retry` before the binary,
edit-distance and token-overlap checks.
- Apply it in `_normalize_bash_for_hash`, so the hash key reflects the
command that actually ran.
- Tests in `tests/test_memory/test_traffic_learner.py`:
- `test_shared_cd_prefix_alone_is_not_retry` and
`test_strips_leading_cd` fail on `main` and pass with this change.
- `test_cd_prefixed_retry_still_matches` guards against rejecting real
retries.
- **Changed expectation:** `test_cuts_at_first_chain` previously
asserted `_normalize_bash_for_hash("cd /tmp && ls") == "cd /tmp"`. That
assertion encoded the bug. It now uses `make build && ls`, and the cd
case moved to `test_strips_leading_cd`, which asserts `"cd /tmp && ls"`
normalizes to `"ls"`.

## Testing

- [ ] Unit tests pass (`pytest`) (see Additional Notes)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) (see Additional Notes)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_memory/test_traffic_learner.py -k "CommandsRelatedAsRetry or NormalizeBashForHash or RefineErrorRecovery or NormalizedHash"
=============== 35 passed, 122 deselected, 39 warnings in 0.80s ===============

# New tests on main (fix reverted), full file:
FAILED tests/test_memory/test_traffic_learner.py::TestCommandsRelatedAsRetry::test_shared_cd_prefix_alone_is_not_retry
FAILED tests/test_memory/test_traffic_learner.py::TestNormalizeBashForHash::test_strips_leading_cd

$ ruff check .
All checks passed!

$ mypy headroom/memory/traffic_learner.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.14, headroom 0.38.0, Claude Code via
`headroom proxy --learn --memory`.
- Exact command / steps: Read every persisted `traffic_learner` Bash
`error_recovery` row from my own `memory.db` (read-only). Run
`_commands_related_as_retry` and `_normalize_bash_for_hash` on each
row's `failed_cmd` / `success_cmd`, first with `main` and then with this
branch.
- Observed result: 72 of 96 Bash rows had a cd prefix on both sides, and
`main` accepted all 72 as retries; on this branch 16 are accepted. On
`main` those rows also shared hash keys (e.g. 6 unrelated pairs on one
`cd <repo>|cd <repo>` key); on this branch every row gets its own key.
- Not tested: A full proxy session on Linux or macOS. I also did not
check how long existing polluted rows take to disappear from a live
`MEMORY.md` after upgrading.

## Runtime Rollout Safety

- Rollout-managed feature(s): None
- Minimum rollout channel: dev
- Stable/default behavior changed: Yes, narrowly. Bash error-recovery
pairing and hash keys ignore a leading `cd <dir>` segment. Nothing else
changes.
- Kill switch / disable path: N/A (existing `--learn` opt-in is
unchanged)
- Unsafe override required: No
- Qualification impact: None
- Rollback path: Revert commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes (see
Additional Notes)
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

- **Unit tests.** On my Windows machine, 45 tests in
`test_traffic_learner.py` already fail on `main`. Examples are
`TestProjectForPattern` (POSIX path fixtures) and
`TestUserAuthoredPreferenceFiltering`. The set of failing tests is
identical before and after this change, apart from the new tests. I have
not run the suite on Linux/macOS and am relying on CI for that.
- **Type checking.** `mypy headroom` reports one error on Windows, in
`headroom/fileperms.py:71` (`os.fchmod` does not exist on Windows). That
file is untouched here. The changed module passes mypy.
- **Documentation.** N/A, this is an internal matcher fix.
- **Out of scope.** 16 remaining accepted pairs include some that are
still questionable, where commands share a binary and a file name, e.g.
`git status --short lib/x.ts` → `git add lib/x.ts && git commit`. That
is a broader weakness of the token-overlap rule for compound commands.
- **Existing hash keys move.** Any Bash command with a leading `cd
<dir>` segment now normalizes to a different hash key, so rows persisted
under the old key are not re-keyed. Their accumulated evidence counts
are orphaned and learning for those commands restarts from zero. This is
intentional: the old keys merged unrelated pairs, so their evidence was
inflated.
- **Existing rows.** Rows already persisted with the collapsed hash are
not rewritten. They split into separate hashes on load, so most should
fall below `min_evidence`, and the 21-day hard floor retires the rest. I
did not add render-time re-validation for Bash rows, because
`test_bash_recoveries_not_revalidated` documents that as intentional.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-09-30 22:41:13 -05:00
Abhay SinghandJerrettDavis 7e73438dc5 perf(memory): bound traffic-learner _persisted_ids with the dedup window (#3341)
## Description

`HeadroomTrafficLearner._persisted_ids` (a `dict[content_hash,
memory_id]`) grew **one entry per distinct persisted pattern for the
whole process lifetime** and was never trimmed, while its sibling dedup
set `_saved_hashes` **is** trimmed to `dedup_window`:

```python
self._saved_hashes.add(h)
if len(self._saved_hashes) > self._dedup_window:
    self._saved_hashes.pop()          # trimmed
# ...
self._persisted_ids[pattern.content_hash] = memory_id   # never trimmed
```

`_persisted_ids` is only ever *read* behind an `if h in
self._saved_hashes:` guard (the dedup shortcut at the top of
`_accumulate`). So once a hash leaves the dedup window, its
`_persisted_ids` entry can never be read again — it's pure dead weight
on the long-lived learner (which owns background save/flush tasks). The
asymmetry is the tell: `_saved_hashes` is trimmed and `_pattern_counts`
is LRU-capped right next to this, but `_persisted_ids` was missed.

The fix keeps the two in lockstep:
- When `_saved_hashes` evicts a hash, drop its `_persisted_ids` entry in
the same step.
- The async save worker records an id only while its hash is still
tracked in `_saved_hashes` (it may have been evicted between enqueue and
persist).

Neither changes the dedup/bump semantics — a hash evicted from
`_saved_hashes` was already re-learnable and could already produce a
duplicate row; these only stop `_persisted_ids` from leaking.

Reproduction (before): 200 distinct persisted patterns with
`dedup_window=4` → `_persisted_ids` holds ~200 entries while
`_saved_hashes` holds ≤4. After: `_persisted_ids` stays a subset of
`_saved_hashes`, bounded to ≤4.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [x] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/traffic_learner.py`: on `_saved_hashes` eviction in
`_accumulate`, capture the popped hash and `_persisted_ids.pop(evicted,
None)`; in `_save_worker`, guard the id record with `and
pattern.content_hash in self._saved_hashes`.
- `tests/test_memory/test_traffic_learner.py`: added
`test_persisted_ids_bounded_in_lockstep_with_saved_hashes` — feeding 200
distinct patterns through a `dedup_window=4` learner leaves
`_persisted_ids` a subset of `_saved_hashes` and bounded to ≤4 (not
200).

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality

### Test Output

```text
tests/test_memory/test_traffic_learner.py  ->  153 passed, 2 failed
  (the 2 failures are pre-existing on main in TestProjectForPattern — project-root
   path matching, unrelated to this change; confirmed they fail without this patch)
uvx ruff@0.16.2 check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/memory/traffic_learner.py  ->  Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: drove `_accumulate` with 200 distinct patterns
(each corroborated to `min_evidence=1`) through a `dedup_window=4`
learner, recording an id for each still-tracked hash. Without the fix
`_persisted_ids` held ~200 entries and was not a subset of the 4-element
`_saved_hashes` (test fails). With the fix it stays a subset and ≤4.
Confirmed the two `TestProjectForPattern` failures pre-date this change
by stashing the patch.
- Observed result: `_persisted_ids` no longer grows without bound; it
tracks the dedup window. Dedup/bump behavior for in-window hashes is
unchanged.
- Not tested: an end-to-end run against a live memory backend (the async
`_save_worker` path needs a backend); the eviction/record invariant is
exercised directly, and the worker guard mirrors it.

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: no. Dedup shortcut and evidence-bump
behavior are unchanged for any hash still in the dedup window; only
stale `_persisted_ids` entries (already unreadable) are dropped.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit; `_persisted_ids` goes back to
unbounded growth.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (N/A:
internal memory bound)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

This mirrors the bounding already applied to `_saved_hashes`
(dedup_window trim) and `_pattern_counts` (LRU cap) in the same class,
closing the one companion structure that was left uncapped.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-09-30 11:16:58 -05:00
Chester c471800e8e fix(memory): keep vector metadata in sync (#2295)
## Description

Fixes #2296.

Metadata-only memory updates can leave the primary store, vector-index
metadata, and cache inconsistent. TrafficLearner also performs an atomic
SQLite evidence increment that bypasses normal secondary-index refresh.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Refresh vector metadata for HierarchicalMemory metadata-only,
importance, and entity-reference updates.
- Add a LocalBackend path that reloads a memory from the primary store
and refreshes vector metadata plus cache state.
- Preserve the atomic TrafficLearner SQL evidence increment, then
refresh secondary state only when a row was updated.
- Keep refresh failures fail-open and distinguish them from
primary-store increment failures in logs.
- Add backend-neutral contract tests instead of inspecting a specific
vector adapter private field.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`) — verified locally: mypy
1.20.2, no issues in 504 source files
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
141 passed, 1 skipped
ruff check: passed
ruff format --check: passed
```

The first CI run exposed one backend-specific test assertion against
HNSW private state while CI used SQLiteVectorIndex. Commit a1aff399
removes that assertion and keeps the backend-neutral mock contract test.

## Real Behavior Proof

- Environment: macOS, Python 3.13, current Headroom main.
- Exact command / steps: update a Memory with metadata only through
HierarchicalMemory, assert the vector index receives the updated Memory,
then perform a TrafficLearner evidence bump and assert LocalBackend
refresh is called only for an existing row.
- Observed result: metadata-only update refreshes vector metadata
without re-embedding content; evidence bump remains atomic and refreshes
vector/cache state; an unknown memory ID triggers no refresh.
- Not tested: remote memory backends, full repository suite, or live
multi-process writers against one SQLite database.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented code where the behavior is not self-explanatory
- [x] I have made corresponding documentation changes (N/A — internal
bug fix, no user-facing docs/changelog impact)
- [x] My changes generate no new warnings
- [x] I have added tests that prove the fix is effective
- [x] New and existing focused unit tests pass locally
- [x] I have updated CHANGELOG.md if applicable (N/A — internal bug fix,
no user-facing docs/changelog impact)

## Screenshots (if applicable)

Not applicable.

## Additional Notes

Draft for storage-owner feedback on the refresh API and write overhead.
The refresh reuses the existing embedding and does not invoke the
embedder.
2026-08-11 23:46:13 -05:00
Abhay Singh 1f5fefffd3 fix(memory): bound the TrafficLearner pending-pattern accumulator (memory leak) (#2579)
## Description

`TrafficLearner` (the memory/learning subsystem that accumulates
patterns from proxy traffic) has an unbounded in-memory accumulator.

`_pattern_counts` maps `content_hash -> (pattern, count)`. A pattern is
added on first sighting, its count is bumped on each re-sighting, and it
is **removed only when it reaches `min_evidence`** (default 5), at which
point it is promoted and its hash moves to `_saved_hashes`:

```python
if h in self._pattern_counts:
    existing, count = self._pattern_counts[h]
    count += 1
    self._pattern_counts[h] = (existing, count)
else:
    self._pattern_counts[h] = (pattern, 1)
    return  # first sighting — wait for more evidence
...
if count >= self._min_evidence:
    del self._pattern_counts[h]          # only removal path
    self._saved_hashes.add(h)
    if len(self._saved_hashes) > self._dedup_window:  # sibling IS trimmed
        self._saved_hashes.pop()
```

A pattern seen **once but never corroborated** — the common case for
one-off traffic (a unique error string, an ad-hoc shell command, a
distinct file path) — never reaches `min_evidence`, so it is **never
removed**. Over a long-lived proxy processing varied traffic,
`_pattern_counts` grows without bound and RSS climbs. The sibling
`_saved_hashes` is explicitly trimmed to `dedup_window` ("prevent
unbounded growth"); `_pattern_counts` was missed.

Reproduced directly: feeding 500 distinct one-off patterns leaves 500
entries in `_pattern_counts` (one per pattern, forever).

## Fix

Make `_pattern_counts` an LRU-ordered `OrderedDict` capped at a new
`max_pending_patterns` (default 2048):

- On each corroboration, `move_to_end(h)` so an actively-accumulating
pattern stays "fresh" and is never evicted before it can be promoted.
- On a first sighting when the accumulator is full, evict the
least-recently-corroborated pending entry (`popitem(last=False)`).

Evicting a stale one-off is safe: if it recurs it simply restarts
accumulation (delayed promotion at worst) — the same tradeoff
`_saved_hashes` already makes. Promotion at `min_evidence` is unchanged,
and the cap (2048) is generous enough that any pattern receiving repeat
sightings within a normal window reaches `min_evidence=5` long before
eviction.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring

## Changes Made

- `headroom/memory/traffic_learner.py`: `_pattern_counts` becomes a
capped LRU `OrderedDict`; add `max_pending_patterns` (default 2048);
`move_to_end` on corroboration and evict-oldest on overflow.
- `tests/test_memory/test_traffic_learner.py`: a regression that 500
one-off patterns keep the accumulator at its cap, and one that a
corroborated pattern still promotes into `_saved_hashes` (both sync via
`asyncio.run` so they run without the pytest-asyncio plugin).

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_memory/test_traffic_learner.py -q
35 failed, 109 passed

# the 35 failures are pre-existing @pytest.mark.asyncio tests that need
# pytest-asyncio (not configured in this environment); they fail identically
# on clean main (35 failed, 107 passed) and pass in CI. My two new tests are
# synchronous and pass; they add +2 passing with no new failures.

# with the fix reverted, test_pending_accumulator_is_bounded fails
# (the accumulator holds all 500 one-off patterns)

$ uvx ruff@0.15.17 check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py
All checks passed!
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/memory/traffic_learner.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, project venv (`uv sync --extra
proxy`), `uvx ruff@0.15.17` / `uvx mypy@1.20.2`, pytest in the venv.
- Exact command / steps: built a `TrafficLearner(backend=None,
min_evidence=5, max_pending_patterns=8)` and drove `_accumulate` with
500 distinct one-off `ExtractedPattern`s; separately corroborated one
pattern to `min_evidence`; then reverted the source and re-ran.
- Observed result: with the fix `len(_pattern_counts)` stays at the cap
(8) after 500 one-offs, the corroborated pattern is removed from pending
and present in `_saved_hashes`, and an actively-bumped pattern survives
LRU eviction; with the fix reverted the accumulator holds all 500
one-off entries (the unbounded leak). Ran against the actual module.
- Not tested: a live multi-day proxy run measuring RSS (the leak is
inferred from the removed unbounded-growth path; the accumulator bound
is verified directly).

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable
2026-08-06 19:21:59 -07:00
gglucass a70e5ff78d fix(learn): run project discovery off the event loop (#2731)
## Description

`TrafficLearner.flush_to_file` is a coroutine, but it called
`plugin.discover_projects()` inline. That function walks the filesystem
to decode escaped project directory names — in
`learn/plugins/claude.py`, `_greedy_path_decode` recurses through
`iterdir()` at every level and tries each tokenization of each child,
backtracking on a miss — so on a large home tree it runs for minutes.

Doing that on the event loop freezes uvicorn for the whole window. The
port keeps accepting TCP, but `/readyz` never answers, so a supervisor
health-checking the proxy kills a process that is merely busy.

Field thread dumps show exactly that:

```
Current thread (most recent call first):
  File "python3.12/pathlib.py", line 1056 in iterdir
  File "headroom/learn/plugins/claude.py", line 454 in _greedy_path_decode
  File "headroom/learn/plugins/claude.py", line 478 in _greedy_path_decode
  File "headroom/learn/plugins/claude.py", line 478 in _greedy_path_decode
  File "headroom/learn/plugins/claude.py", line 426 in _decode_project_path
  File "headroom/learn/plugins/claude.py", line 71 in discover_projects
  File "headroom/memory/traffic_learner.py", line 591 in flush_to_file
  File "headroom/memory/traffic_learner.py", line 535 in _flush_worker
  File "python3.12/asyncio/events.py", line 88 in _run
  File "python3.12/asyncio/base_events.py", line 1999 in _run_once
  File "python3.12/asyncio/base_events.py", line 645 in run_forever
  File "uvicorn/server.py", line 75 in run
  File "headroom/proxy/server.py", line 4992 in run_server
```

Accompanying signals from the same incidents: port accepts TCP,
`/readyz` times out, process CPU 2-13s across the window (I/O bound, not
spinning), proxy log silent 66-336s.

## Type of Change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/traffic_learner.py`: `flush_to_file` now awaits
`asyncio.to_thread(plugin.discover_projects)` instead of calling it
inline. `asyncio` was already imported. The result is cached per learner
(`_project_roots_cache`), so the steady-state flush path pays nothing
for the thread hop.
- `tests/test_memory/test_traffic_learner.py`: added
`test_discover_projects_does_not_block_the_event_loop`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ uv run --frozen --extra dev pytest tests/test_memory/test_traffic_learner.py -q
..................................................                       [100%]
============================= 152 passed in 2.93s ==============================

$ uvx ruff check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py
All checks passed!

$ uvx ruff format --check headroom/memory/traffic_learner.py tests/test_memory/test_traffic_learner.py
2 files already formatted

$ uv run --frozen --extra dev mypy headroom/memory/traffic_learner.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS 15.6 arm64, Python 3.10.18, pytest 9.0.3, branch
off `main` @ `01df2452`.
- Exact command / steps: reverted only the one-line source change in the
working tree (`await asyncio.to_thread(plugin.discover_projects)` back
to `plugin.discover_projects()`), left the new test in place, ran `uv
run --frozen --extra dev pytest
tests/test_memory/test_traffic_learner.py -k does_not_block -q`, then
restored the line and re-ran the full file.
- Observed result: without the change the test fails — `flush_to_file`
runs to completion synchronously the moment the task is created, so the
loop never regains control while `discover_projects` is parked on a
`threading.Event`. With the change the loop stays responsive and the
flush completes once discovery returns. Full file: 152 passed.
- Not tested: no live proxy run against a multi-minute real home tree;
the blocking behaviour is reproduced deterministically in the test
instead. The thread dump above is captured field evidence, not a run in
this environment.

Failing output with the fix reverted:

```text
$ uv run --frozen --extra dev pytest tests/test_memory/test_traffic_learner.py -k does_not_block -q
tests/test_memory/test_traffic_learner.py:1254: in test_discover_projects_does_not_block_the_event_loop
    assert not flush.done()
E   AssertionError: assert not True
E    +  where True = <built-in method done of _asyncio.Task object at 0x10882dff0>()
E    +    where <built-in method done of _asyncio.Task object at 0x10882dff0> = <Task finished name='Task-1' coro=<TrafficLearner.flush_to_file() done ...>>.done
========================= 1 failed, 151 deselected in 5.51s =========================
```

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

- Documentation: N/A — no user-facing behaviour or interface change.
- Bounding `_greedy_path_decode`'s backtracking is the real cost fix and
belongs in its own change. This one only stops a slow walk from taking
the server's liveness with it.
2026-08-03 06:00:52 -07:00
Chester 3eb0122068 fix(learn): filter ambient user-role scaffolding (#2275)
## Description

Fixes #2274.

Headroom Learn currently trusts `role=user` as sufficient preference
provenance. Agent harnesses can transport ambient UI and orchestration
context in user-role messages, and OpenAI Responses normalization also
promotes missing roles to `user`. Correction-like text in those inputs
can therefore become durable user preferences.

This change keeps preference learning fail-closed for known non-user
sources while preserving genuine user corrections.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Refactoring only

## Changes Made

- Preserve missing OpenAI Responses roles as `unknown` instead of
promoting them to `user`.
- Canonicalize user-role text before preference extraction.
- Remove proxy-appended `## Relevant Memories` suffixes from preference
evidence.
- Reject strict ambient-only harness prefixes such as heartbeat,
environment, workspace-instruction, delegation, and app-context
envelopes.
- Apply the same guard in `on_messages` and `_extract_preferences` for
defense in depth.
- Add regression coverage for system/developer/unknown roles,
ambient-only user messages, memory-only messages, and mixed
genuine-user-plus-memory input.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
149 passed, 1 warning
ruff check: passed
ruff format --check: passed
git diff --check: passed
```

Focused test files:

```text
tests/test_memory/test_traffic_learner.py
tests/test_openai_responses_traffic_learner.py
```

## Real Behavior Proof

- Environment: macOS; Python 3.13; current Headroom main; direct
invocation of the real `TrafficLearner` class, with no proxy or database
mocks
- Exact command / steps: create `TrafficLearner(backend=None,
min_evidence=1)`; feed system, developer, heartbeat user-role, and
memory-only user-role messages; read `patterns_extracted`; feed a
genuine user correction followed by a `## Relevant Memories` suffix;
read `patterns_extracted` again
- Observed result: `ambient_patterns=0`, `after_user_patterns=1` — the
ambient batch produced no preference evidence; the genuine correction
produced one pattern, while the appended memory content did not become
evidence
- Not tested: live provider traffic against a remote OpenAI endpoint;
every possible third-party harness envelope; migration or cleanup of
already-persisted noisy memories

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] No new dependency
- [x] Fail-open proxy behavior is unchanged
- [x] Regression tests added
- [x] Public examples contain no real user data
- [x] CHANGELOG update, if requested (not requested — N/A)

## Additional Notes

This extends the source filtering introduced by #466 rather than
replacing it. The prefix checks are deliberately strict and anchored at
the start of a canonicalized message. The intended failure mode is a
missed preference, not durable storage of non-user instructions.

Note: the strict prefix set was discussed and confirmed in
JerrettDavis's review approvals.
2026-08-02 19:40:14 -07:00
Abhay SinghandJerrettDavis 6cdfd3f64d fix(proxy/openai): feed chat/completions traffic into the traffic learner (#2333)
## Description

Addresses the chat/completions portion of #2060.

The live traffic learner is wired into the Anthropic `/v1/messages`
handler and, since then, the OpenAI Responses HTTP handler
(`_observe_openai_responses_traffic`, called from
`handle_openai_responses`). But `handle_openai_chat` has **no**
ingestion call site:

```text
headroom/proxy/handlers/openai.py
  handle_openai_responses -> _observe_openai_responses_traffic   (wired)
  handle_openai_chat       -> (no traffic_learner call)           (gap)
```

So OpenAI-compatible clients that route through `/v1/chat/completions` —
GitHub Copilot CLI, opencode, OpenAI SDKs — run through an apparently
healthy proxy with Learn enabled while producing no learned patterns:
the learner starts, but it never receives their tool results or user
messages.

## Fix

Observe the original client payload (before memory/compression mutates
it) at the top of `handle_openai_chat`, mirroring the Responses and
Anthropic ingestion paths:

```python
await self._observe_openai_chat_traffic(original_client_messages, request_id=request_id)
```

`_observe_openai_chat_traffic` is the chat counterpart of
`_observe_openai_responses_traffic`: same lazy backend wiring, same
`on_tool_result` / `on_messages` lifecycle, same fail-soft `try/except`.

The one format-specific piece is tool-result extraction.
chat/completions encodes tool calls differently from Anthropic — the
call is on an assistant message's `tool_calls` array (`id` -> function
`name` + `arguments`) and each result is a separate `role: "tool"`
message keyed by `tool_call_id`, so the existing
`extract_tool_results_from_messages` (which scans for Anthropic
`tool_use`/`tool_result` blocks) finds nothing. A new
`TrafficLearner.extract_tool_results_from_openai_messages`:

- builds the `tool_call_id -> function` map from assistant `tool_calls`;
- for each `role: "tool"` message, resolves the tool name and joins
string-or-list content;
- parses the OpenAI `arguments` JSON string into a dict, so the
downstream environment/recovery extractors (which call
`input.get("command")`, `input.get("file_path")`, ...) see the same
shape as an Anthropic `tool_use.input` instead of a raw string;
- sniffs `is_error` from the output (chat tool messages carry no error
flag).

It returns the same `{tool_name, input, output, is_error}` shape as the
Anthropic extractor, so `on_tool_result` stays format-agnostic.
User-message preference extraction (`on_messages`) already reads plain
`role`/`content`, so it consumes chat messages unchanged.

Scope: this wires the **chat/completions** path. Codex WebSocket
ingestion (`handle_openai_responses_ws`) additionally needs
per-`response.create` evaluation plus transcript-replay baselining on
reconnect, so it is intentionally left as a follow-up rather than
half-implemented here.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/traffic_learner.py`: add
`extract_tool_results_from_openai_messages` (OpenAI chat tool-result
extraction with `arguments` JSON parsed to a dict).
- `headroom/proxy/handlers/openai.py`: add
`_observe_openai_chat_traffic` and call it from `handle_openai_chat` on
the original client payload.
- `tests/test_memory/test_traffic_learner.py`: cover the OpenAI
extractor (name resolution, arguments parsing, list content, error
sniff, malformed/orphan handling, empty case).
- `CHANGELOG.md`: Bug Fixes entry.

## Testing

- [ ] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ uvx ruff@0.15.17 check headroom/memory/traffic_learner.py headroom/proxy/handlers/openai.py tests/test_memory/test_traffic_learner.py
All checks passed!
$ uvx ruff@0.15.17 format --check <same files>
3 files already formatted
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/memory/traffic_learner.py
# clean for this file (the one reported error is a pre-existing
# headroom/_subprocess.py:18 no-any-return, unrelated to this change and
# present on main with these edits stashed)
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, `uvx ruff@0.15.17` / `uvx
mypy@1.20.2`. A full `pytest` OOMs this box (ML-stack import), so I
reproduced the extractor with a dependency-free script and left the full
pytest to CI.
- Exact command / steps: replicated
`extract_tool_results_from_openai_messages` and ran it over a typical
chat round-trip (assistant `tool_calls` for `bash` + `read_file`, then
two `role: "tool"` results, one erroring and one with list content),
plus malformed-`arguments`, orphan-`tool_call_id`, and no-tool cases.
- Observed result: tool names resolved from the call-id map; `arguments`
parsed to a dict so `input.get("command")` works; list content joined;
`is_error` sniffed from output; malformed arguments degrade to `{}` and
an orphan id yields `unknown` without raising. The added unit tests
assert the same through a real `TrafficLearner`.
- Not tested: a live Copilot CLI session end to end; the added tests
drive `TrafficLearner.extract_tool_results_from_openai_messages`
directly, matching the existing
`test_extract_tool_results_from_messages` pattern.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

The "unit tests pass locally" box is unchecked because a local pytest
run imports the ML stack and OOMs this box; the added tests reuse the
existing `TrafficLearner(backend=None, ...)` harness in
`test_traffic_learner.py` (no real backend) and run under the normal CI
pytest job, and the extractor behavior is corroborated by the standalone
proof above. This PR is deliberately scoped to `/v1/chat/completions`;
I'm happy to follow up with the Codex WebSocket ingestion path (which
needs the transcript-replay baselining discussed in the issue) as a
separate change if useful.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-18 10:09:01 -07:00
Rudimar RonsoniandRudimar Ronsoni b4571cc346 feat: headroom wrap opencode / unwrap opencode CLI (#1105)
## Summary

This PR implements transparent `headroom wrap opencode` support without
asking users to edit OpenCode provider URLs, choose an extra CLI flag,
or maintain a static provider list.

The wrapper now lives at the runtime transport boundary: OpenCode keeps
its user/provider config, while Headroom intercepts outbound provider
traffic in-process and routes it through the local Headroom proxy.

## What changed

### Transparent OpenCode wrapping

- `headroom wrap opencode` injects the `headroom-opencode` plugin
through `OPENCODE_CONFIG_CONTENT`.
- Existing OpenCode provider URLs are preserved. We do not rewrite user
config URLs to point at Headroom.
- Existing `OPENAI_BASE_URL` and `ANTHROPIC_BASE_URL` env vars are
preserved.
- Local OpenCode traffic, localhost traffic, and Headroom proxy traffic
bypass the shim to avoid loops.

### Runtime transport interception

- Added an OpenCode plugin transport shim that wraps:
  - `globalThis.fetch`
  - `http.request` / `http.get`
  - `https.request` / `https.get`
- External provider calls are routed to the local Headroom proxy.
- The original upstream origin is passed through `x-headroom-base-url`,
so the proxy can forward to the real provider without changing OpenCode
config.
- External `http2.connect` is blocked loudly instead of allowing direct
provider traffic to leak outside Headroom.

### Live provider additions

Provider coverage is no longer based on a static config scan. Because
routing happens at outbound request time, providers added mid-session
are routed through Headroom automatically as long as they use the
covered Node transport paths.

### Subagent and child-process coverage

- The parent OpenCode plugin sets a packaged Node preload shim through
`NODE_OPTIONS=--import=.../hook-shim/handler.js`.
- The transport shim patches `child_process.spawn`, `exec`, `execFile`,
and `fork` so child Node processes receive the Headroom preload even
when OpenCode passes a custom `env`.
- The child-process shim fails closed if it loads without
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL`.
- This closes the subagent leak path where a child Node process could
otherwise start without Headroom transport interception.

## Why this goes beyond PR #1089

PR #1089 improves OpenCode provider registration, but it still focuses
on provider config shape. This PR moves the enforcement boundary to
runtime transport interception.

This PR goes further because:

- No provider URL rewriting is required.
- New providers added mid-session are covered automatically.
- Subagents and child Node processes inherit the Headroom transport
shim.
- Direct external HTTP/2 paths fail loudly instead of leaking.
- The wrap remains transparent to the user's OpenCode provider config.
- The wrapper is fail-closed for unsupported child-process preload
state.

## Additional robustness fixes

While validating the change in Docker, the full Python suite exposed
unrelated Linux/container robustness issues. These are fixed in this PR
so the suite is green:

- Binary cache handling now treats cache paths under a non-writable
existing parent as unavailable, including when tests run as root in
Docker.
- `release_version.py` honors `MANUAL_VER` before git calls so direct
script execution works outside a `.git` checkout.
- Test logger isolation now resets relevant Headroom child loggers so
proxy logging setup cannot poison later `caplog` tests.
- The scanner missing-path test now uses a guaranteed missing `tmp_path`
child instead of relying on `/nonexistent/path`.

## Validation

All implementation validation was run inside Docker.

- Full Python suite from a fresh Docker copy: `6605 passed, 523
skipped`.
- Ruff on changed Python/OpenCode paths: passed.
- OpenCode plugin typecheck: passed.
- OpenCode plugin tests: `9 passed`.
- OpenCode plugin build: passed.
- Hook shim preload smoke test: passed.

## Notes

This PR intentionally does not add a CLI option. `headroom wrap
opencode` means full wrap. Either Headroom wraps OpenCode transparently,
or the path fails loudly instead of silently leaking provider traffic.

---------

Co-authored-by: Rudimar Ronsoni <6081613+rudironsoni@users.noreply.github.com>
2026-06-22 11:07:12 -05:00
chopratejas 0be0eede9e fix(memory): traffic_learner indexes system-reminder fragments as user preferences (refs #464)
`TrafficLearner._extract_preferences` ran three regex patterns over raw
user-message text and saved any match as a `User preference: <captured>`
memory. Two compounding bugs made ~10% of the reporter's saved memories
(187 of 1796) garbage:

1. **System-reminder content was matched.** Claude Code injects
   `<system-reminder>…</system-reminder>` blocks into user-role
   messages — scaffolding ("don't mention this reminder", "use colgrep
   instead of Grep", "never bypass signing") that hits every correction
   trigger. The learner happily persisted scaffolding as authoritative
   user preferences.
2. **Capture groups were fixed-length windows.** `(.{10,100})` grabbed
   the next 10–100 chars with no boundary awareness, producing
   mid-word truncations like `User preference: of Grep, Glob. When
   spawning agents, mention colgrep features a`.

This change rewrites `_extract_preferences` to be **regex-free** and
adds two layered defences:

- `_strip_system_reminders` (literal `str.find` scan, no regex)
  removes `<system-reminder>…</system-reminder>` blocks from user
  text before any pattern matching. Unclosed reminders drop to
  end-of-string. Case-insensitive on the tag name only. ~95% of the
  reporter's noise sample comes from this single layer.
- A token-based correction scanner replaces the three `re.compile`
  patterns. It tokenises on whitespace (lowercasing once, up front),
  matches trigger sequences as ordered token lists (`don't`, `do not`,
  `stop`, `never`, `avoid`, `no use`, `no try`, `no do`, `instead`),
  and captures the trailing content until a sentence terminator
  (`.!?\n`) or end-of-input. Captures shorter than 10 chars are
  rejected (stray triggers), and captures that hit the 78/98-char cap
  without finding a terminator are rejected (rambling fragments). The
  former noise — `colgrep instead of Grep, Glob. When spawning…` —
  fails this gate; short complete user utterances
  (`don't use git push, I'll push manually`) still pass because
  end-of-input counts as a boundary.

Net regex count in this file: -3, +0.

`_hydrate_persisted_state` already runs in `start()` and seeds
`_saved_hashes`/`_persisted_ids` from prior rows, so cross-restart
dedup is already wired up — the reporter's "doesn't survive restarts"
note was partially outdated. The narrow remaining edge (in-process
`_dedup_window=100` eviction within a single very-long-running
process) self-heals on next restart and is left as a separate
follow-up.

Tests: 17 new across `TestStripSystemReminders`,
`TestExtractPreferencesSystemReminderFiltering`,
`TestExtractPreferencesRealCorrections`, and
`TestExtractPreferencesSentenceBoundary`. Full traffic_learner suite:
139 passing. ci-precheck green.
2026-05-13 16:13:04 -07:00
Tejas Chopra 5ceca13c65 fix: harden learn path handling across platforms 2026-05-09 15:45:26 -07:00
GarmandClaude Opus 4.7 4512a0626e test(traffic-learner): cover helper edge cases + apply ruff format
CI flagged two issues on the rebased branch:
1. ruff format --check failed on server.py and test_traffic_learner.py
   after the rebase; line-collapse / trailing-whitespace nits.
2. Codecov reported 80% patch coverage with 20 lines missing in the
   matcher helpers — mostly branches not exercised by the high-level
   tests (empty Levenshtein inputs, source-prefix Bash parsing, env-var
   skip, equal-string short-circuit in binary match, the substantive-
   token path that beats the edit-distance gate, error_recovery patterns
   with non-canonical content in _drop_contradictions).

Adds 16 targeted unit tests for those branches and applies ruff format.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 18:05:54 +09:00
GarmandClaude Opus 4.7 606131451b fix(traffic-learner): tighten matchers and drop contradictions
The recovery matchers paired any failed and successful tool call within
a 5-call window with no semantic check that the pair was actually a
retry. This produced confidently-wrong rules like:

  File `state.rs` does not exist. The correct path is `lib.rs`.

…where the user simply read two unrelated files in the same directory.
Across sessions the same user can also typo in opposite directions,
producing directly contradictory rules side by side.

This commit adds three structural checks:

1. Read recovery: require the failed and successful basenames to be
   identical or close in Levenshtein distance. Rejects the "same dir,
   different file" case that was the most common noise source.

2. Bash recovery: require both commands to share a binary (allowing
   path-prefixed variants and short prefix-versions like
   `python` ↔ `python3`) AND either have low normalized edit distance
   or share a substantive non-flag token. Rejects pairs that share only
   the binary name but differ in every meaningful argument.

3. Contradiction filter on flush: detect A→B and B→A pairs in
   error_recovery patterns and drop both. They almost always indicate
   opposite-direction typos in different sessions, not stable advice.

Also: stash failed_path in metadata so the contradiction filter and
downstream consumers can reason about pairs without parsing content.

Tests: 13 new tests covering the heuristics directly. Existing tests
exercising legitimate recoveries (`python`→`python3`, `ruff`→`.venv/bin/ruff`,
`pip install`→success) continue to pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 17:45:45 +09:00
GarmandClaude Opus 4.7 a8ebf9ac5e test(traffic-learner): regression test for shutdown evidence gate
Asserts that stop()'s final flush_to_file does not bypass the evidence
threshold. Earlier behavior collapsed the gate to 1 at shutdown,
persisting every singleton pattern. This guards against that change
sneaking back in.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 17:44:22 +09:00
GarmandClaude Opus 4.7 ac493cba1e test(memory): raise patch coverage from 83% to 98% on error_recovery fixes
26 new tests covering:

- TestNormalizeBashForHash — empty string, no-suffix, head/tail strip,
  trailing context flags, stderr redirect, chain-boundary truncation
- TestParseIsoTimestamp — None, empty, non-string, invalid format,
  naive (assumed UTC), tz-aware preserved
- TestLoadPersistedPatternsTimestamps — reads first_seen_at/last_seen_at
  from metadata, falls back to created_at, collision-merges timestamps
  and bumps importance to max, handles malformed JSON and non-numeric
  importance cells gracefully
- TestBumpPersistsLastSeenAt — verifies _bump_persisted_evidence writes
  $.last_seen_at into metadata JSON
- TestHydrateLegacyRow — legacy rows without category, rows with
  unknown/invalid category, rows with empty content
- TestCollectAllPatternsTimestamps — in-session re-sighting bumps
  last_seen_at past stale persisted timestamp
- TestRefineErrorRecovery (additions) — refine-empties-section skips
  recommendation entirely, OSError during re-validation keeps the row,
  Read patterns without success_path skip re-validation cleanly

Remaining uncovered lines in patch (4): defensive exception handlers
in _hydrate_persisted_state (sqlite connect OperationalError, asyncio
thread exception, JSONDecodeError on metadata) that require heavy
mocking for marginal value.

91 tests pass, ruff + mypy clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:53:51 +02:00
GarmandClaude Opus 4.7 879064fea5 fix(memory): collapse and decay error_recovery patterns in MEMORY.md
The Learned: error recovery section was bloating with stale, near-duplicate,
and contradictory entries because the dedup key was the literal rendered
bullet text and there was no TTL or re-validation.

- Normalize the hash key for error_recovery patterns. Read recoveries key
  on (basename(error_path), basename(success_path)); Bash recoveries strip
  volatile suffixes (| tail -N, 2>&1, etc.) and hash only the primary
  command before the first | or &&. Non-error-recovery categories keep
  literal-content hashing.
- Stamp first_seen_at / last_seen_at on every pattern; bump both in
  _bump_persisted_evidence via json_set. Stored in metadata JSON — no
  schema change.
- Refine at render time (error_recovery only): drop rows not re-observed
  in 21 days, re-validate Read success paths against the filesystem,
  collapse same-error_path-with-multiple-targets into one "use Glob/Grep
  first" bullet, rank by evidence_count * 0.5 ** (days/5), cap at 15
  bullets.

15 new tests (TestNormalizedHash, TestRefineErrorRecovery). Full suite:
526 passed, 1 skipped. Ruff + mypy clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:20:51 +02:00
GarmandClaude Opus 4.7 b2536e602a test(learn): cover flush_to_file, backend edge cases, and hydrate/bump error paths
Adds 17 targeted tests to close the coverage gap on the new traffic_learner
paths (codecov flagged ~51%). Exercises:

- `flush_to_file` end-to-end with a fake learn plugin + writer: verifies
  anchored patterns are bucketed per project, recommendations are passed
  to the writer, writer exceptions are swallowed, and each early-return
  branch (no plugin, no patterns, discover_projects failure, un-anchored
  patterns) is hit without raising.
- `_resolve_backend_db_path` on None backend, backend without
  `_config`, and backend with empty `db_path`.
- `_collect_all_patterns` merging persisted + accumulator patterns by
  content_hash with summed evidence_count, plus the missing-DB branch.
- `_hydrate_persisted_state` with backend=None and with a backend
  pointing at a non-existent DB file (both no-ops).
- `_bump_persisted_evidence` with no backend, missing DB, and
  unknown memory id (all silent no-ops so the proxy hot path never
  blows up on malformed state).
- `stop()` cancelling the flush task cleanly.

All new tests use the existing `_FakeBackend` + `_init_db` helpers so
they exercise real SQLite paths, not mocks.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 20:06:44 +02:00
GarmandClaude Opus 4.7 3e290b734b fix(learn): persist real evidence_count and bump on re-sighting
Before this change, every persisted traffic_learner row in memory.db
landed with evidence_count=1, causing two user-visible problems:

1. The live flush gate (evidence_count >= 2) filtered out every row, so
   CLAUDE.md / MEMORY.md never received the patterns the learner saw
   repeatedly.
2. _saved_hashes is in-memory only and reset on each proxy restart, so
   a pattern seen once in session A then twice in session B would insert
   a *duplicate* DB row instead of bumping the existing one. Users
   accumulated many rows stuck at 1 instead of a few rows with high
   evidence.

Root cause chain:
- _accumulate tracks a running count in the _pattern_counts tuple but
  enqueues the ExtractedPattern dataclass with its default
  evidence_count=1 intact.
- _save_worker writes pattern.evidence_count into metadata verbatim.
- After save, the hash goes into _saved_hashes and further sightings
  are early-returned — never bumped.
- Next process start has empty _saved_hashes, so the same content goes
  through the accumulator as fresh and gets re-saved.

Fix:
- _accumulate now sets pattern.evidence_count = count before enqueuing,
  so DB rows reflect the real number of sightings at save time.
- _save_worker captures the Memory.id returned by save_memory and
  records content_hash → id in a new _persisted_ids map.
- _accumulate's saved-hash branch now awaits
  _bump_persisted_evidence(memory_id), which runs an atomic
  json_set('$.evidence_count', existing + 1) UPDATE via
  asyncio.to_thread to keep the proxy hot path non-blocking.
- start() calls a new _hydrate_persisted_state() that reads existing
  traffic_learner rows' (id, content) pairs from the DB and pre-seeds
  _saved_hashes + _persisted_ids. Cross-session re-sightings bump the
  seeded row instead of inserting a duplicate.
- _load_persisted_patterns_from_sqlite and _hydrate_persisted_state
  query by json_extract(metadata, '$.source') = 'traffic_learner'
  instead of the prior LIKE on raw JSON — the bump path uses json_set,
  which rewrites the metadata string without the default ": " spacing,
  which would otherwise make the LIKE blind to bumped rows.

Adds TestEvidencePersistence with three cases:
- save persists the actual accumulated count (not the default 1)
- re-sightings bump the persisted row instead of creating duplicates
- a fresh learner hydrates _saved_hashes from DB, so cross-session
  re-sightings bump the pre-existing row

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:02:35 +02:00
GarmandClaude Opus 4.7 d9138a3ed8 feat(learn): live flush of traffic patterns to agent-native context files
Replaces the previous shutdown-only flush with a debounced, near-real-time
dirty-flag flush worker that writes patterns into the correct CLAUDE.md /
MEMORY.md bucket as traffic accumulates.

- New FLUSH_DEBOUNCE_SECONDS gate (10s) prevents context-file thrash on
  bursty traffic while keeping updates "live" from the user's perspective.
- TrafficLearner.start() now spawns a _flush_worker alongside the save
  worker; _accumulate() sets a dirty flag; _flush_worker() calls
  flush_to_file() when dirty and past the debounce window.
- flush_to_file() now reads *both* persisted rows (memory.db) and the
  in-memory accumulator via _load_persisted_patterns_from_sqlite and
  _collect_all_patterns, so patterns survive proxy restarts and the
  agent-native files converge toward the full learned set.
- Patterns are bucketed per-project via the learn plugin registry
  (plugin.discover_projects()) and anchored to project roots through
  longest-matching-path on content or entity_refs
  (_project_for_pattern). Un-anchored patterns are dropped.
- Patterns are routed by PatternCategory to either CONTEXT_FILE
  (CLAUDE.md) or MEMORY_FILE (MEMORY.md) via
  _patterns_to_recommendations + _CATEGORY_TO_TARGET.
- Live flushes require evidence_count >= 2; shutdown flushes accept
  single-evidence rows to avoid losing last-session signal.

Adds tests for project routing, persisted-pattern loading, category
routing, and the debounced flush worker.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:00:15 +02:00
chopratejas d9cc4f3991 Fix ruff lint errors in test files 2026-03-24 15:54:12 -07:00
Tejas Chopra 0fd6dfcadb feat: add live traffic learning + cross-agent memory writers (--learn flag)
Live Traffic Learner extracts patterns from proxy traffic in real-time:
- Error→recovery patterns (tool fails → next success teaches right approach)
- Environment facts (working venv paths, test commands)
- User preference signals (corrections, repeated choices)

Agent-native memory writers export learned patterns to each agent's format:
- Claude Code: MEMORY.md + per-topic files
- Cursor: .cursor/rules/headroom-memory.mdc (YAML frontmatter)
- Codex: AGENTS.md
- Generic: plain markdown (Aider, Gemini, any agent)

Memory Budget Manager handles token-optimized memory files:
- Per-agent token budgets (2K Claude, 3K Cursor/Codex)
- Temporal decay, staleness detection (git + filesystem)
- Jaccard-similarity memory merging, dedup

Opt-in via --learn flag on proxy/wrap commands:
- headroom proxy --learn
- headroom wrap claude --learn
- --learn implies --memory; --no-learn overrides
- compress() API completely unaffected (pure function)
- Default behavior unchanged (no memory, no learning)
2026-03-20 15:36:06 -07:00