Commit Graph
6 Commits
Author SHA1 Message Date
07d5add5ba fix(memory): keep multimodal user content intact when injecting memories (#4648)
## Description



Item 10 of #4362. `MemoryWrapper._inject_memories`
(`headroom/memory/wrapper.py`, the path behind
`with_memory(client).chat.completions.create`) searched on
`str(user_content)` and prepended the memory context with
`f"{context_block}\n\n{original}"`. For a list-typed (multimodal) user
message, the content sent upstream became one string holding the Python
repr of the parts, so images and files never reached the model, and the
memory search ran on that repr. CONTRIBUTING.md asks that user content
is never dropped.



The search now uses the text parts of a list (and is skipped when there
are none), and the context is added as a leading `{"type": "text"}` part
while the original parts are kept as they are. String content is handled
exactly as before.



Refs #4362



## 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/wrapper.py`: new module helper `_text_of(content)` (a
string as is, or the `text` of the list's `type: "text"` parts joined by
newlines); `_inject_memories` searches on it and returns the messages
unchanged when it is empty; when the first user message's content is a
list, the context is inserted as a new first text part instead of
formatting the list into a string.

- `tests/test_memory_wrapper.py`:
`test_inject_memories_keeps_multimodal_content_parts` (parts kept,
context as a leading text part, search query is the text part) and
`test_inject_memories_skips_search_for_content_without_text` (image-only
content: no search, messages unchanged).



## Testing



- [x] Unit tests pass (`pytest`)

- [x] Linting passes (`ruff check .`)

- [ ] Type checking passes (`mypy headroom`) (run on
`headroom/memory/wrapper.py` only, see below)

- [x] New tests added for new functionality

- [x] Manual testing performed



### Test Output



```text

# fail before (source at e4a60ed7, new tests kept)

FAILED tests/test_memory_wrapper.py::test_inject_memories_keeps_multimodal_content_parts

FAILED tests/test_memory_wrapper.py::test_inject_memories_skips_search_for_content_without_text

2 failed, 7 passed



# pass after: tests/test_memory_wrapper.py

9 passed



# tests/test_memory + tests/test_memory_wrapper.py + tests/test_memory_integration.py

e4a60ed7:     2 failed, 565 passed, 157 skipped   (the failures are the new tests)

this branch:  567 passed, 157 skipped



# ruff check / ruff format --check: All checks passed! / 2 files already formatted

# mypy headroom/memory/wrapper.py: Success: no issues found in 1 source file

```



## Real Behavior Proof

- Environment: Ubuntu (WSL2) on Windows 11, Python 3.12.15, OpenAI
Python SDK 2.54.0, `headroom` Python source at `e4a60ed7` and at this
branch (`d4c70d26`). Nothing leaves `127.0.0.1`.
- Exact command / steps: a local `http.server` on `127.0.0.1` stands in
for the OpenAI API. It answers `/v1/embeddings` with a constant 384-dim
vector and records the exact JSON body the SDK posts to
`/v1/chat/completions`. `OPENAI_BASE_URL` points at it, so the memory
embedder's own `AsyncOpenAI` uses it too. Then: `client =
with_memory(openai.OpenAI(api_key="sk-local", base_url=<local>),
user_id="alice", db_path=<tmp>/mem.db,
embedder_backend=EmbedderBackend.OPENAI, openai_api_key="sk-local")`,
`client.memory.add("Alice prefers answers in one sentence.")`, then
`client.chat.completions.create(model="gpt-4o-mini", messages=[{"role":
"user", "content": [<text part>, {"type": "image_url", "image_url":
{"url": "data:image/png;base64,..."}}, {"type": "file", "file":
{"file_data": "data:application/pdf;base64,...", "filename":
"note.pdf"}}]}])`. The memory stack is the real default one
(`SQLiteMemoryStore`, `SQLiteVectorIndex`, `FTS5TextIndex`,
`OpenAIEmbedder`). Printed the user message as it arrived on the wire.
- Observed result: on `e4a60ed7` the SDK sends the user content as a
`str`, `"<context>\n- Alice prefers answers in one
sentence.\n</context>\n\n[{'type': 'text', ...}, {'type': 'image_url',
...}, {'type': 'file', ...}]"`, so the image and the file reach the API
only as Python repr text. On this branch the SDK sends a `list`:
`[{"type": "text", "text": "<context>\n- Alice prefers answers in one
sentence.\n</context>"}, {"type": "text", "text": "What is in this
picture and this file?"}, {"type": "image_url", ...}, {"type": "file",
...}]`, with the image and file parts byte-identical to what the caller
passed.
- Earlier stub run (kept for the search query): with a stub memory and a
recording client, the memory search received the repr string on
`e4a60ed7` and `'What is in this chart?'` on this branch.
- Not tested: a real provider (the endpoint is local, so this proves
what the SDK serializes, not how a model reads the image or file); real
embeddings (the constant vector makes the stored memory always match);
the Anthropic SDK; `mypy headroom` as a whole. Content that is neither a
string nor a list (for example `None`) still goes through the old
f-string path; this PR does not change it. The maintainer's independent
run with the HNSW backend is in the notes below.

## Runtime Rollout Safety



- Rollout-managed feature(s): None.

- Minimum rollout channel: N/A

- Stable/default behavior changed: Yes, narrowly: for list-typed user
content, `with_memory` now sends the parts unchanged plus one leading
text part, and searches on the text parts; image-only content gets no
memory search. String content is unchanged.

- Kill switch / disable path: None added; revert.

- Unsafe override required: No

- Qualification impact: None expected

- 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



One logical change per PR, as CONTRIBUTING asks: this covers item 10 of
#4362 only (item 7 is #4647).



Produced with AI assistance (Claude Code) operated by me (HetCreep); the
reproduction was run on my machine against a clone of the repository.



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





### Maintainer qualification against current main



Qualified source head `e765c7e1710cee9a9be6dfa87d6443cc39107627` against
upstream main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 19 focused
tests passed. Independent MemoryWrapper +
HierarchicalMemory/SQLite/HNSW/FTS runtime used the real OpenAI SDK
against a localhost HTTP fixture. Text+image requests preserved image
parts and prepended context text; search received only text. Image-only
input remained unchanged and skipped search. String behavior and
original caller messages were preserved. Actual main sent repr strings
for list content and searched those representations. This verifies
request wiring, not cloud image-model processing.



The maintainer cherry-picked only the shared Gemini test-fixture repair
from #4644: real Starlette Request with two ASGI receive chunks,
preserving the existing test assertions. This addresses the same four
independently verified failures on main; contributor production logic is
unchanged. Ruff, formatting, and whitespace checks passed. Exact-head
hosted CI is being checked before formal approval.



### Reproducing the independent SDK wire proof

This supplements the original stub-only proof and addresses the
SDK-evidence review comment. On Windows with Python 3.12, the project
runtime dependencies, native hnswlib 0.8.0, and the OpenAI SDK
installed, save the program below as `memory_runtime.py`. Check out this
exact PR head into an isolated directory and run `python
memory_runtime.py ABSOLUTE_CHECKOUT_PATH wrapper`. The program currently
uses `G:/git/headroom/.codex` as its owned temporary-directory root;
replace that root with an existing local scratch directory on another
machine. It creates a real localhost TCP HTTP server and captures the
actual SDK request. No provider credentials or cloud calls are required.
The same command against upstream main e4a60ed7 turns list content into
repr strings. This does not qualify live cloud/image-model behavior.

<details><summary>Reproduction program (also supports HNSW and relation
controls)</summary>

```python
import asyncio
import copy
import importlib.metadata
import json
import os
from pathlib import Path
import queue
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

os.environ.update(HEADROOM_OFFLINE='1', DO_NOT_TRACK='1', HEADROOM_BEACON_ENABLED='0')
sys.path.insert(0, sys.argv[1])
import numpy as np
from headroom.memory.adapters.fts5 import FTS5TextIndex
from headroom.memory.adapters.hnsw import HNSWVectorIndex
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
from headroom.memory.core import HierarchicalMemory
from headroom.memory.ports import VectorFilter

class DeterministicEmbedder:
    dimension = 8
    model_name = 'offline-review-unit-vectors'

    def __init__(self):
        self.queries = []

    async def embed(self, text):
        self.queries.append(text)
        slot = next((i for word, i in [('spaces', 1), ('fridays', 2), ('postgres', 3)] if word in text), 0)
        return np.eye(8, dtype=np.float32)[slot]

    async def embed_batch(self, texts):
        return [await self.embed(text) for text in texts]

def components(root):
    embedder = DeterministicEmbedder()
    vector = HNSWVectorIndex(dimension=8, max_elements=16)
    memory = HierarchicalMemory(SQLiteMemoryStore(root / 'memory.db'), vector,
                                FTS5TextIndex(root / 'memory.db'), embedder)
    return memory, vector, embedder

async def hnsw_probe(root):
    memory, vector, _ = components(root)
    first = await memory.add('user prefers tabs', 'alice', auto_bubble=False)
    await memory.add('deploys on fridays', 'alice', auto_bubble=False)
    await memory.add('uses postgres', 'alice', auto_bubble=False)
    labels = dict(vector._memory_to_hnsw)
    await memory.update(first.id, content='user prefers spaces')
    observed = {}
    for phrase in ['user prefers spaces', 'user prefers tabs']:
        results = await memory.search(phrase, user_id='alice', top_k=3)
        observed[phrase] = next(r.similarity for r in results if r.memory.id == first.id)
    assert vector._memory_to_hnsw == labels and vector.size == 3
    vector.save_index(root / 'index')
    restored = HNSWVectorIndex(dimension=8, max_elements=16)
    restored.load_index(root / 'index')
    after_restart = await restored.search(VectorFilter(
        query_vector=np.eye(8, dtype=np.float32)[1], top_k=3, user_id='alice'))
    observed['restart_new_similarity'] = next(r.similarity for r in after_restart if r.memory.id == first.id)
    observed['size'] = restored.size
    observed['labels_unchanged'] = restored._memory_to_hnsw == labels
    observed['hnswlib_version'] = importlib.metadata.version('hnswlib')
    return observed

async def relation_probe(root):
    from headroom.memory.adapters.sqlite_graph import SQLiteGraphStore
    from headroom.memory.backends.local import LocalBackend
    from headroom.memory.system import MemorySystem
    memory, _, _ = components(root)
    backend = LocalBackend()
    backend._initialized = True
    backend._hierarchical_memory = memory
    backend._graph = SQLiteGraphStore(root / 'graph.db')
    system = MemorySystem(backend, user_id='alice')
    result = await system.process_tool_call('memory_save', {
        'content': 'Alice works with Bob on billing', 'importance': .7,
        'entities': ['Alice', 'Bob'],
        'relationships': [{'source': 'Alice', 'relation': 'works_with', 'target': 'Bob'}],
    })
    alice = await backend._graph.get_entity_by_name('alice', 'Alice')
    assert alice is not None
    graph = SQLiteGraphStore(root / 'graph.db')
    relations = await graph.get_relationships(alice.id)
    return {'tool_result': result, 'stored_after_reopen': [r.relation_type for r in relations]}

def wrapper_probe(root):
    from openai import OpenAI
    from headroom.memory.wrapper import MemoryWrapper
    memory, _, embedder = components(root)
    asyncio.run(memory.add('Prefers bar charts', 'alice', auto_bubble=False))
    received = queue.Queue()

    class Provider(BaseHTTPRequestHandler):
        def do_POST(self):
            received.put(json.loads(self.rfile.read(int(self.headers['Content-Length']))))
            payload = json.dumps({'id': 'review', 'object': 'chat.completion', 'created': 0,
                'model': 'gpt-4o', 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'OK'}, 'finish_reason': 'stop'}],
                'usage': {'prompt_tokens': 10, 'completion_tokens': 1, 'total_tokens': 11}}).encode()
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)

        def log_message(self, *_args):
            pass

    server = ThreadingHTTPServer(('127.0.0.1', 0), Provider)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    client = OpenAI(api_key='local-review-fixture', base_url=f'http://127.0.0.1:{server.server_port}/v1', max_retries=0)
    wrapped = MemoryWrapper(client, user_id='alice', _memory=memory, db_path=root / 'memory.db')
    image = {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKx0AAAAASUVORK5CYII='}}
    outcomes = []
    try:
        for content in [[{'type': 'text', 'text': 'What is in this chart?'}, image], [image], 'What is in this chart?']:
            messages = [{'role': 'user', 'content': copy.deepcopy(content)}]
            original = copy.deepcopy(messages)
            before = len(embedder.queries)
            response = wrapped.chat.completions.create(model='gpt-4o', messages=messages)
            assert response.choices[0].message.content == 'OK'
            payload = received.get(timeout=5)
            user = next(m['content'] for m in payload['messages'] if m['role'] == 'user')
            assert messages == original
            outcomes.append({'original_kind': type(content).__name__, 'wire_kind': type(user).__name__,
                'wire_content': user, 'search_queries': embedder.queries[before:]})
    finally:
        client.close()
        server.shutdown()
        server.server_close()
    return outcomes

owned = Path('G:/git/headroom/.codex').resolve()
with tempfile.TemporaryDirectory(prefix='memory-runtime-review-', dir=owned) as directory:
    root = Path(directory).resolve()
    assert root.is_relative_to(owned)
    mode = sys.argv[2]
    if mode == 'hnsw':
        observed = asyncio.run(hnsw_probe(root))
    elif mode == 'relation':
        observed = asyncio.run(relation_probe(root))
    else:
        observed = wrapper_probe(root)
    sys.stdout.reconfigure(encoding='utf-8')
    print(json.dumps({'source': sys.argv[1], 'mode': mode, 'observed': observed}, ensure_ascii=False, indent=2))

```
</details>

<details><summary>Observed serialized requests and search inputs on this
PR</summary>

```json
{
  "source": "G:/git/headroom-review4648",
  "mode": "wrapper",
  "observed": [
    {
      "original_kind": "list",
      "wire_kind": "list",
      "wire_content": [
        {
          "type": "text",
          "text": "<context>\n- Prefers bar charts\n</context>"
        },
        {
          "type": "text",
          "text": "What is in this chart?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKx0AAAAASUVORK5CYII="
          }
        }
      ],
      "search_queries": [
        "What is in this chart?"
      ]
    },
    {
      "original_kind": "list",
      "wire_kind": "list",
      "wire_content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aKx0AAAAASUVORK5CYII="
          }
        }
      ],
      "search_queries": []
    },
    {
      "original_kind": "str",
      "wire_kind": "str",
      "wire_content": "<context>\n- Prefers bar charts\n</context>\n\nWhat is in this chart?",
      "search_queries": [
        "What is in this chart?"
      ]
    }
  ]
}

```
</details>



### Maintainer current-main requalification

Exact head `167f281d57fcaddb9b934a3ea42804ecb428461d`, upstream main
`ea59ac3eef3a3dc02076e9fe4bb30d572ca9c1a9`.

Cleanly integrated upstream/main
ea59ac3eef and re-reviewed the remaining
wrapper/test-only diff against intervening memory relationship/HNSW
fixes.17 wrapper/HNSW-update/relation-key tests pass using actual
isolated Click8.5.0; Ruff and whitespace pass. Multimodal search remains
text-only, context prepends a text part, original non-text parts/caller
content remain preserved, and image-only input skips search. Earlier
actual OpenAI-SDK localhost serialization evidence remains scoped to
unchanged wrapper inputs; no cloud image-model or fresh native build
claim. No new source finding; final approval awaits exact-head hosted
qualification. Nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.


### Maintainer current-main requalification

Exact head `06f67f44127e111916ec4f47bc275cd50f35426d`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final post-Dependabot requalification against upstream/main
c01cf07d94. All six Dependabot updates are
now merged. Relative to this branch's freshly tested prepared tree, the
final main sync changes only the three intended Cargo.lock records;
Python/source/test inputs are unchanged. Re-reviewed the integration and
confirmed complete native source/lock/toolchain objects match the tested
combined build and exact fresh native DLL used for this branch's local
tests.

Focused fresh-native qualification: 17 passed, 45 warnings in 1.98s.
Selected real dependency overlays and native DLL paths are recorded in
final4648-fresh-native-tests.log; the DLL provenance/input hashes are in
final-native-artifact-proof.json. No redundant rerun is implied after
this Cargo-only merge. Whitespace passes. Prior source review and scoped
real-behavior evidence remain applicable to unchanged contributor
inputs.

No new source finding in the reviewed scope. Final formal approval
awaits exact-head hosted qualification.

Maintainers handle hosted checks; no external-provider claim,
contributor semantic rewrite or non-Dependabot merge.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:19:40 -06:00
Abhay Singh 5ccec67f0c fix(memory): tolerate None message content in inline memory parser (#3211)
## Description

`InlineMemoryWrapper.chat` / `.chat_with_response` read
`response.choices[0].message.content` and hand it straight to
`parse_response_with_memory`, which immediately does `re.search(pattern,
response_text, ...)`:

```python
raw_content = response.choices[0].message.content   # str | None
parsed = parse_response_with_memory(raw_content)
...
match = re.search(memory_pattern, response_text, re.DOTALL | re.IGNORECASE)
```

A chat completion's `message.content` is `None` whenever the model
answers with tool/function calls instead of text. `re.search` on `None`
raises `TypeError: expected string or bytes-like object, got
'NoneType'`, crashing the whole request. So enabling tools on any
request routed through the inline memory wrapper turns the first
tool-call turn into an unhandled exception.

This is the same robustness class the function already guards for the
`<memory>` block payload (a non-object / non-list JSON is tolerated at
`inline_extractor.py:132`-`:143`); `None` content was the remaining gap,
one level up.

## 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/inline_extractor.py`: `parse_response_with_memory`
now returns early when `response_text` is not a `str`, preserving the
payload unchanged (so a `None` tool-call turn is not coerced to text)
with no memories extracted. Widened its parameter to `str | None` and
`ParsedResponse.content` / `.raw` and the two `chat*` return types to
`str | None` to match what a chat completion actually yields.
- `tests/test_memory_wrapper.py`: added
`test_parse_response_with_memory_tolerates_none_content` next to the
existing non-object-block regression.

## 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_wrapper.py  ->  7 passed in 0.78s
uvx ruff@0.16.2 check headroom/memory/inline_extractor.py tests/test_memory_wrapper.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/memory/inline_extractor.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: before the fix,
`parse_response_with_memory(None)` raised `TypeError: expected string or
bytes-like object, got 'NoneType'`. After the fix, the same call returns
`ParsedResponse(content=None, memories=[], raw=None)`, and a normal text
response with a `<memory>` block still parses (`content == "hello
world"`, memories extracted).
- Observed result: `None` content degrades gracefully and stays `None`;
the string path is byte-for-byte unchanged.
- Not tested: no live `chat.completions.create` tool-call round trip
(the wrapper takes an injected client); the `None` content a tool-call
turn produces is reproduced directly.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. `InlineMemoryWrapper` is an SDK-side
convenience wrapper (`headroom.memory`), not a rollout-channel-gated
runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: no. Non-`None` string inputs take
exactly the previous path; only the previously-crashing `None` case
changes, from `TypeError` to a graceful no-op parse.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none; text responses are handled identically.
- Rollback path: revert this PR; the parser returns to assuming a `str`.

## 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 behavior, unchanged semantics)
- [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`
2026-09-25 11:03:54 -05:00
Abhay Singh e00c6ff81c fix(memory): don't crash inline memory extraction on a non-object <memory> block (#2470)
## Description

`parse_response_with_memory` extracts an inline `<memory>...</memory>`
block from a model response and parses its JSON:

```python
try:
    data = json.loads(memory_json)
    memories = data.get("memories", [])
except json.JSONDecodeError as e:
    logger.warning(f"Failed to parse memory JSON: {e}")
```

The block content is fully model-controlled. `json.loads` succeeds on
any valid JSON, including a non-object such as a bare array
(`<memory>["x"]</memory>`), a string, or a number. `data.get("memories",
[])` then raises `AttributeError: 'list' object has no attribute 'get'`,
which the `except json.JSONDecodeError` does not catch, so the inline
memory path crashes on output a model can realistically produce.

## Fix

Guard the parsed value: read `memories` only when the block is a JSON
object, and accept it only when it is a list (logging and ignoring
otherwise). Malformed JSON is still handled by the existing decode
guard, and a well-formed object is unchanged. This mirrors the
non-object hardening already applied to the batch JSONL path.

## 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/inline_extractor.py`: only read `memories` from a
dict-typed parsed block, and only when the field is a list; log and
ignore other shapes.
- `tests/test_memory_wrapper.py`: regression covering a non-object
memory block, a non-list `memories` field, malformed JSON, and a
well-formed block.

## 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_wrapper.py -q
6 passed

# with the fix reverted, the new test fails with
# AttributeError: 'list' object has no attribute 'get'

$ uvx ruff@0.15.17 check headroom/memory/inline_extractor.py tests/test_memory_wrapper.py
All checks passed!
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/memory/inline_extractor.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: called the real `parse_response_with_memory`
with a `<memory>["x"]</memory>` block, a `{"memories": "nope"}` block, a
malformed block, and a valid block; then reverted `inline_extractor.py`
and re-ran.
- Observed result: with the fix all four return cleanly (empty memories
for the bad shapes, the parsed list for the valid one) and the memory
block is still stripped from the content; with the fix reverted the
non-object block raises `AttributeError: 'list' object has no attribute
'get'`. Ran against the actual module.
- Not tested: a live end-to-end chat where a model emits a non-object
memory block.

## 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-12 00:12:50 -05:00
JerrettDavisandCopilot a5a4486a30 test: apply linux ruff formatting
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 08:49:50 -05:00
JerrettDavisandCopilot 6e9ea54a04 test: fix PR formatting and cover log compressor
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 07:49:27 -05:00
JerrettDavisandCopilot 38bf3e639c test: expand coverage across helper slices
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-23 07:39:52 -05:00