headroom/tests/test_learn/test_subagent_scanning.py
Abhay Singh eed80dd4ba
fix(learn/claude): don't abort the whole scan on a null message line (#2299)
## Description

A single Claude session-log line with an explicit `{"message": null}`
crashes the entire `headroom learn` run.

`ClaudeCodePlugin._scan_session` reads the message object in four
places:

```python
usage = d.get("message", {}).get("usage", {})   # assistant line
...
msg = d.get("message", {})                        # _extract_tool_uses
msg = d.get("message", {})                        # _extract_tool_results
msg = d.get("message", {})                        # _extract_user_events
```

`dict.get("message", {})` only substitutes `{}` for a **missing** key. A
present-but-null `{"type": "assistant", "message": null}` yields `None`,
and `None.get(...)` raises `AttributeError`.

The per-file guard only catches I/O errors:

```python
try:
    with open(jsonl_path, ...) as f:
        for line in f:
            ...
except (OSError, UnicodeDecodeError) as e:
    ...
    return None
```

so the `AttributeError` propagates out of `_scan_session`, past
`scan_project` (which has no try/except around the scan), and aborts the
whole `learn` invocation — every project, not just the one bad line. One
malformed line takes down the entire run.

## Fix

Coalesce the message with `or {}` at all four sites, so a null (or any
falsy) value collapses to `{}`:

```python
usage = (d.get("message") or {}).get("usage", {})
msg = d.get("message") or {}
```

The malformed line is now skipped and scanning continues; valid lines
are parsed exactly as before.

Closes #

## 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/learn/plugins/claude.py`: coalesce `d.get("message")` with
`or {}` in `_scan_session` and the three `_extract_*` helpers.
- `tests/test_learn/test_subagent_scanning.py`: new test that a session
containing `{"message": null}` lines scans without crashing and still
parses the valid tool call.
- `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/learn/plugins/claude.py tests/test_learn/test_subagent_scanning.py
All checks passed!
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/learn/plugins/claude.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, `uvx ruff@0.15.17` / `uvx
mypy@1.20.2`. A full `pytest` OOM-kills this box (ML stack import), so I
reproduced the per-line handling with a dependency-free script and left
the full pytest to CI.
- Exact command / steps: ran an assistant line `{"message": null}` (plus
a real assistant line and a missing-message line) through the OLD
`get("message", {})` and NEW `get("message") or {}` logic.
- Observed result: OLD raises `AttributeError` on the null message; NEW
returns `0` for it and still counts `42` input tokens for the real line
and `0` for a missing-message line.
- Not tested: a full `learn` run over a real history containing such a
line; full local `pytest` deferred to CI (OOM).

## 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 the full suite
imports the ML stack, which I can't run here. The new test reuses the
existing `ClaudeCodePlugin` scanner harness in
`tests/test_learn/test_subagent_scanning.py`, so it runs under the
normal CI pytest job; behaviour is additionally verified by the
standalone proof above.

---------

Co-authored-by: Tejas Chopra <chopratejas@gmail.com>
2026-07-16 14:36:11 -07:00

121 lines
4.4 KiB
Python

"""The Claude scanner must descend into subagent and workflow transcripts.
Claude Code writes a main session at ``<project>/<uuid>.jsonl`` and nests the
transcripts it spawns under ``<project>/<uuid>/subagents/**`` (subagents) and
``.../subagents/workflows/**`` (workflow agents). Each nested transcript is a
separate context window with its own token spend and its own tool-call
failures, so ``headroom learn`` must see them — not just the top-level session.
"""
from __future__ import annotations
import json
from pathlib import Path
from headroom.learn.models import ProjectInfo
from headroom.learn.plugins.claude import ClaudeCodePlugin
def _write_session(path: Path, out: str = "x" * 400) -> None:
"""Write a minimal Claude Code session: one tool_use paired with a result."""
lines = [
{
"type": "assistant",
"message": {
"usage": {"input_tokens": 100, "output_tokens": 10},
"content": [
{
"type": "tool_use",
"id": "u1",
"name": "Read",
"input": {"file_path": "/a.py"},
}
],
},
},
{
"type": "user",
"message": {"content": [{"type": "tool_result", "tool_use_id": "u1", "content": out}]},
},
]
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(json.dumps(line) for line in lines))
def test_scan_survives_null_message_line(tmp_path: Path) -> None:
# A single line with an explicit {"message": null} must not crash the scan
# (the per-file guard only catches OSError/UnicodeDecodeError, so an
# AttributeError here would abort the whole `learn` run). The valid tool_use
# pair around it must still be parsed.
path = tmp_path / "main-uuid.jsonl"
lines = [
{"type": "assistant", "message": None},
{
"type": "assistant",
"message": {
"usage": {"input_tokens": 100, "output_tokens": 10},
"content": [
{
"type": "tool_use",
"id": "u1",
"name": "Read",
"input": {"file_path": "/a.py"},
}
],
},
},
{"type": "user", "message": None},
{
"type": "user",
"message": {
"content": [{"type": "tool_result", "tool_use_id": "u1", "content": "x" * 400}]
},
},
]
path.write_text("\n".join(json.dumps(line) for line in lines))
plugin = ClaudeCodePlugin()
session = plugin._scan_session(path)
assert session is not None
assert len(session.tool_calls) == 1
assert session.total_input_tokens == 100
def test_scan_project_discovers_subagent_and_workflow_transcripts(tmp_path: Path) -> None:
_write_session(tmp_path / "main-uuid.jsonl")
_write_session(tmp_path / "main-uuid" / "subagents" / "agent-1.jsonl")
_write_session(tmp_path / "main-uuid" / "subagents" / "workflows" / "wf_1" / "agent-2.jsonl")
plugin = ClaudeCodePlugin()
project = ProjectInfo(name="p", project_path=tmp_path, data_path=tmp_path)
sessions = plugin.scan_project(project, max_workers=1)
assert len(sessions) == 3
assert sorted(s.source for s in sessions) == ["main", "subagent", "workflow"]
def test_main_only_restricts_to_top_level(tmp_path: Path) -> None:
_write_session(tmp_path / "main-uuid.jsonl")
_write_session(tmp_path / "main-uuid" / "subagents" / "agent-1.jsonl")
plugin = ClaudeCodePlugin()
project = ProjectInfo(name="p", project_path=tmp_path, data_path=tmp_path)
sessions = plugin.scan_project(project, max_workers=1, include_subagents=False)
assert len(sessions) == 1
assert sessions[0].source == "main"
def test_subagents_found_in_parallel_scan(tmp_path: Path) -> None:
# Multiple files force the ThreadPool path; nested transcripts must still appear.
_write_session(tmp_path / "main-a.jsonl")
_write_session(tmp_path / "main-b.jsonl")
_write_session(tmp_path / "main-a" / "subagents" / "agent-1.jsonl")
plugin = ClaudeCodePlugin()
project = ProjectInfo(name="p", project_path=tmp_path, data_path=tmp_path)
sessions = plugin.scan_project(project, max_workers=4)
assert len(sessions) == 3
assert sum(1 for s in sessions if s.source == "subagent") == 1