Commit Graph
6 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Opus 5.5 2e497cbec3 refactor(memory): deprecate the never-wired agent memory writers (#4101)
## Description

`headroom/memory/writers/` exports memories to agent files (CLAUDE.md,
`.cursor/rules`, AGENTS.md, generic markdown). It arrived in 0fd6dfca,
and no product code has ever imported it. `headroom learn` writes agent
context files through `headroom.learn.writer`, a separate writer. The
package lists its classes in `__all__`, so it is public API. This PR
deprecates it instead of deleting it. Importing
`headroom.memory.writers` now emits a `DeprecationWarning`.

**What to use instead:** there is no replacement. For writing agent
context files, `headroom learn` (`headroom.learn.writer`) is the
supported path.

Evidence:
- `grep -rnE 'memory\.writers|MemoryWriter|AgentWriter|ExportResult'`
finds only the package itself, `memory/budget.py` (removed in a separate
PR) and tests. The search covered `headroom crates plugins sdk docs wiki
scripts benchmarks examples e2e .github pyproject.toml` and the consumer
repos.
- The package is not re-exported from `headroom.memory` and not
documented.

Refs #4136

## 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
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/writers/__init__.py`:
- Emit `DeprecationWarning("headroom.memory.writers is deprecated and
will be removed in a future release; it has no replacement …")` when the
package is imported. Importing any submodule, such as
`headroom.memory.writers.base`, runs the package first, so that warns
too.
  - Add `.. deprecated::` to the docstring.
- `tests/test_memory/test_writers.py`: add one test that asserts the
warning fires on import. The existing writer tests stay.
- Unchanged: `import headroom.memory`, `headroom.memory.sync` and the
sync adapters stay quiet. Checked with `-W error::DeprecationWarning`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] 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_memory/test_writers.py tests/test_managed_block_injection.py tests/test_memory/test_budget.py tests/test_memory_sync.py
======================== 92 passed, 1 warning in 1.21s =========================
$ python -W error::DeprecationWarning -c "import headroom.memory, headroom.memory.sync, headroom.memory.sync_adapters.claude_code; print('quiet')"
quiet
$ uvx ruff@0.16.8 check headroom/memory/writers/__init__.py tests/test_memory/test_writers.py
All checks passed!
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, repo .venv, branch checkout at
58e5702d (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 `python -W always`. It imports `headroom.memory` (the live path),
then imports a writer from the deprecated package directly.
  - Ran the full `tests/test_memory` suite.
- Observed result:
- Both proxy requests return HTTP 200 with savings, and the proxy log
has no deprecation warning.
- `headroom.memory` imports quietly. The direct writers import emits the
new warning, and the writer still loads.
  - 615 passed.
- Not tested: No runtime path imports the package.
`headroom/memory/budget.py` imports it, and #4099 deletes that file.

```text
$ bash smoke.sh <worktree>
branch: cleanup/memory-cache-memory-writers @ 58e5702d
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 -W always -c "import headroom.memory; print(...); from headroom.memory.writers import GenericMemoryWriter; print(...)"
headroom.memory imported
<string>:4: DeprecationWarning: headroom.memory.writers is deprecated and will be removed in a future release; it has no replacement (headroom learn writes agent context files through headroom.learn.writer).
writer: GenericMemoryWriter
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; deprecation notice only.
- Stable/default behavior changed: No. The writers behave as before.
Importing them additionally emits a DeprecationWarning, which Python
hides by default outside `__main__` and tests.
- Kill switch / disable path: Standard `warnings` filters.
- 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
- [x] 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.

- The audit first proposed deleting the package. Under the
deprecate-first rule for public API, it is deprecated here. Deletion can
follow in a later release.
- The unused budget manager (`memory/budget.py`), which depends on this
package, is removed in a separate PR.
- "My changes generate no new warnings" refers to code that is used. The
only new warning is the intended DeprecationWarning.
- mypy was not run, because no types changed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:03:14 -07:00
Tejas ChopraandClaude Opus 5 b10dd8db6e fix(memory): pin LF on memory writers and guard the learn-writer newline contract (#3706)
Closes #3698. Follow-up to #3594, which fixed `headroom/learn/writer.py`
correctly but left three gaps.

## 1. The write half had no regression guard

`test_apply_does_not_accumulate_carriage_returns_on_crlf_file` passes on
`main` with the fix reverted — its assertion (`raw.count(b"\r") ==
raw.count(b"\r\n")`) holds for a CRLF-preserving file too. So the
`newline="\n"` pins, which *are* the fix, were unguarded.

This cannot be caught by asserting on file bytes on POSIX: CPython's C
`TextIOWrapper` picks the newline translation target at compile time
(`#ifdef MS_WINDOWS`), so monkeypatching `os.linesep` does not simulate
Windows.

The new test spies on `Path.write_text` and drives the real writer
`.write()` methods. Stripping the kwargs from all seven sites:

```
tests/test_learn/test_writer.py ................................F
E   AssertionError: learn writers wrote without newline='\n': [
E     .../data/memory/MEMORY.md, .../instructions.md, .../myproject/AGENTS.md,
E     .../myproject/CLAUDE.local.md, .../myproject/CLAUDE.md,
E     .../myproject/GEMINI.md, .../myproject/GROK.md]
=================== 1 failed, 32 passed ===================
```

All seven named — and note the other 32 pass, including the old test,
confirming it was never a guard.

## 2. The same bug was still live in the memory writers

Ten call sites, all nine from the issue plus
**`headroom/memory/sync.py:137`** (`_save_sync_state`), which the issue
missed:

`writers/base.py:168` · `writers/claude_writer.py:119` ·
`writers/cursor_writer.py:130` · `bridge.py:126, 394, 650` ·
`sync.py:137` · `sync_adapters/codex_agent.py:124` ·
`sync_adapters/claude_code.py:196, 239`

These write files that **overlap** with the learn writers
(`~/.claude/CLAUDE.md`, `AGENTS.md`), so on Windows a file flipped
between LF and CRLF depending on which subsystem wrote last.

**No live accumulation bug:** every reader of these files uses
`read_text()`, which normalizes — that is the key difference from
`learn/writer.py`'s `read_bytes().decode()`, which is what let `\r` pile
up. Checked all of them (`bridge.py:114, 222, 617`,
`writers/base.py:193`, `writers/cursor_writer.py:103`,
`sync_adapters/claude_code.py:106, 163, 178, 216`,
`sync_adapters/codex_agent.py:48, 83`, `sync.py:127`).

**But the churn is more than cosmetic**, which the issue did not note:
`claude_code.py:252` and `codex_agent.py:135` read via `read_bytes()`
for `fingerprint()` change-detection hashing. An EOL flip changes the
hash, so a CRLF/LF flip reads as a content change and triggers a
spurious re-sync.

Three new tests cover the writer, bridge and sync-adapter paths; all
three fail with the pins stripped.

## 3. No unit test had ever run on Windows

The sharded `test` job is ubuntu-only, and `build-wheel-windows` builds
without testing — which is how a Windows-only bug shipped twice. Added
`test-windows-newline`: consumes the existing `headroom-wheel-windows`
artifact and runs only tests marked `windows_newline`. Marker registered
in `pyproject.toml`.

**Known limitation, documented in the job comment:** it is gated on the
`packaging` paths-filter (that is what builds the wheel), so a
pure-Python PR skips it. The ubuntu shards still run the same marked
tests — they assert the kwarg, which fails on any platform — so this is
the Windows-side backstop, not the only guard. Making it fire on every
writer change would mean gating the Windows Rust wheel build on `code`,
which is too expensive to do unasked.

## Verification

- 4 guards proven to fail before, pass after.
- `tests/test_learn/ tests/test_memory/ tests/test_memory_sync.py` →
**950 passed, 4 skipped**.
- Adjacent suites → 168 passed. `pytest tests -m windows_newline` → 4
passed, no marker warning.
- `actionlint .github/workflows/*.yml` → exit 0. Action versions match
the file's conventions (`checkout@v7`, `setup-python@v7`,
`download-artifact@v8`).

`CONTRIBUTING.md` states the invariant once under Coding standards:
Headroom writes LF and normalizes on read, on every platform.

## Not in this PR

Issue section 3's release-note line about the one-time EOL churn on
Windows (the first `--apply` rewrites the whole file to LF). Harmless
under `autocrlf=true`, but worth a release note; `CHANGELOG.md` edits
are blocked by `changelog-guard.yml`.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 11:18:03 -05:00
Abhay SinghandTejas Chopra 8208a4e759 fix(memory): clamp memory age so a future created_at can't crash or invert ranking (#3139)
## Description

Two paired memory-ranking helpers compute an age from `created_at`
without guarding against a **future** timestamp (clock skew, or a
`created_at` written on another machine than the proxy):

`MemoryEntry.score` (`headroom/memory/writers/base.py`):

```python
age_days = (time.time() - self.created_at) / 86400
recency = 1.0 / (1.0 + age_days * 0.1)   # Decay over ~10 days
```

For a `created_at` about **10 days** in the future, `age_days = -10` and
the denominator is `1.0 + (-10)*0.1 = 0.0` — a `ZeroDivisionError`. Past
10 days, the denominator is negative, so `recency` (and the whole score)
goes negative and the memory sorts *below* everything.

`MemoryBudgetManager._apply_decay` (`headroom/memory/budget.py`) has the
paired defect:

```python
age_days = (now - m.created_at) / 86400
decayed_importance = m.importance * math.exp(-rate * age_days)
```

A negative `age_days` makes `exp(-rate × negative) > 1`, so the decayed
importance rises *above* the original (measured at `10.04` from a
starting `0.5` for a 30-day-future entry). That inflated importance is
written back to `m.importance` and flows into `m.score`, so a single
future-dated memory outranks every genuinely-important one and dominates
budget selection.

The codebase's other recency helper,
`proxy/memory_rank_policy.memory_recency_factor`, already clamps (`if
age_days <= 0: return 1.0`). This change brings both writers/base and
budget into line by clamping `age_days` to `>= 0`, so a future memory is
treated as brand new (no decay, no crash, no inflation).

Reproduction:

```python
import time
from headroom.memory.writers.base import MemoryEntry
MemoryEntry(content="x", created_at=time.time() + 10*86400).score   # ZeroDivisionError
MemoryEntry(content="x", importance=0.9, created_at=time.time() + 30*86400).score   # -0.225
```

## 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/writers/base.py` (`MemoryEntry.score`): `age_days =
max(0.0, (time.time() - self.created_at) / 86400)`.
- `headroom/memory/budget.py` (`MemoryBudgetManager._apply_decay`):
`age_days = max(0.0, (now - m.created_at) / 86400)`.
- `tests/test_memory/test_writers.py`: added
`test_score_handles_future_timestamp` (no ZeroDivisionError at +10 days,
non-negative past it, future scores like brand-new).
- `tests/test_memory/test_budget.py`: added
`test_decay_does_not_inflate_future_timestamps` (a future entry's
decayed importance is never inflated above the original / above 1.0).

## 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_writers.py tests/test_memory/test_budget.py  ->  37 passed
uvx ruff@0.16.2 check <changed files>  ->  All checks passed!
uvx mypy@1.20.2 headroom/memory/writers/base.py headroom/memory/budget.py  ->  Success: no issues found in 2 source files
```

## 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: reverted both clamps and ran the two new tests
-> failed (`MemoryEntry(created_at=now+10d).score` raised
`ZeroDivisionError`; `_apply_decay` returned `importance = 10.04` for a
30-day-future entry); restored the `max(0.0, ...)` clamps and re-ran
both files -> 37 passed.
- Observed result: before, a future `created_at` crashed `score` at +10
days, produced a negative score past that, and inflated budget
importance ~20x; after, a future memory decays like a brand-new one
(recency 1.0, importance unchanged).
- Not tested: a live memory store populated across machines with skewed
clocks; the score/decay functions are exercised directly with future
`created_at` values, which is the exact trigger.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This is ranking math in the memory
writers/budget, not a rollout-channel-gated runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only for future-dated memories, which
previously crashed or ranked pathologically. Past/now timestamps are
unchanged (`max(0.0, positive)` is the positive value).
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: memory ranking is now robust to clock skew
instead of crashing or letting a future-dated memory dominate.
- Rollback path: revert this PR; both sites return to the unclamped age.

## 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 ranking math)
- [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

Both sites are fixed together because they are the same defect on the
two code paths that rank memories (`score` for display/export ranking,
`_apply_decay` for budget selection), and `_apply_decay` writes its
result back into `importance`, which then feeds `score`. Clamping
matches the existing `memory_rank_policy` convention rather than
introducing a new rule.

Co-authored-by: Tejas Chopra <chopratejas@gmail.com>
2026-09-09 22:47:16 -05:00
Tejas Chopra 5ceca13c65 fix: harden learn path handling across platforms 2026-05-09 15:45:26 -07: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