fix(wrap): overwrite drifted selfheal hook command instead of skipping it (#2723)

## Description

<!-- Briefly explain the change and why it is needed. -->

Retain two originally published self-heal regression tests. Current
`main` already contains the stronger runtime repair, so this refreshed
proposal is test-only and does not replace or reintroduce the superseded
runtime implementation.

Related issue: headroomlabs-ai/headroom#2221.

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

Existing regression coverage only; the template has no test-only
category.

## Changes Made

- Preserve coverage for removing an empty Headroom-owned environment
section and retaining unrelated user environment values.
- Pin the retained fixture writes to LF.
- Leave the current upstream self-heal runtime implementation unchanged.

## Testing

<!-- Check what you actually ran, then paste the real command output
below. -->

- [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
env -u OPENAI_API_KEY -u ANTHROPIC_API_KEY -u GEMINI_API_KEY -u GOOGLE_API_KEY HF_HUB_OFFLINE=1 uv run --no-sync pytest tests/test_cli/test_wrap_dead_marker_selfheal.py -q
22 passed

uv run --no-sync ruff check .
All checks passed!
uv run --no-sync ruff format --check .
1869 files already formatted

uv run --no-sync mypy headroom
2 existing errors: memory/adapters/embedders.py:389 and integrations/langchain/chat_model.py:380
```

The test-related checkboxes refer to retained regression coverage, not
new runtime functionality or a claim that the global baseline is green.

## Real Behavior Proof

- Environment: macOS arm64, Python 3.14.5, actual temporary settings
files and an actual bound TCP listener; no mocked liveness function.
- Exact command / steps: ran `uv run --no-sync python` with the
following script, then let its temporary directory clean itself up.

```python
import json
import socket
import tempfile
from pathlib import Path
from headroom.cli import wrap

with tempfile.TemporaryDirectory(prefix="headroom-selfheal-runtime-") as home:
    settings = Path(home) / ".claude" / "settings.local.json"
    settings.parent.mkdir()
    settings.write_text(json.dumps({"env": {"KEEP": "preserved"}}), encoding="utf-8", newline="\n")
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        listener.listen()
        port = listener.getsockname()[1]
        wrap._write_claude_wrap_base_url(f"http://127.0.0.1:{port}", settings_path=settings)
        wrap._write_wrap_marker(settings, port=port, key="ANTHROPIC_BASE_URL", previous="https://previous.example")
        before = settings.read_bytes()
        wrap._check_and_clear_dead_wrap_marker(settings, key="ANTHROPIC_BASE_URL")
        assert settings.read_bytes() == before
    wrap._check_and_clear_dead_wrap_marker(settings, key="ANTHROPIC_BASE_URL")
    payload = json.loads(settings.read_text())
    assert payload["env"] == {"KEEP": "preserved", "ANTHROPIC_BASE_URL": "https://previous.example"}
    assert not wrap._wrap_marker_path(settings).exists()
    repaired = settings.read_bytes()
    wrap._check_and_clear_dead_wrap_marker(settings, key="ANTHROPIC_BASE_URL")
    assert settings.read_bytes() == repaired
```

- Observed result: live-listener settings and ownership marker were
preserved. After closing that listener, the previous URL was restored,
the unrelated value survived, and the marker disappeared. Repeating
repair was a byte-identical no-op.
- Not tested: a real Claude session, paid inference, Windows runtime
execution, or a fresh complete repository suite. This demonstrates
current upstream runtime behavior with the retained coverage, not a new
runtime fix in this PR.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; tests only.
- Minimum rollout channel: not applicable.
- Stable/default behavior changed: no.
- Kill switch / disable path: no runtime feature is introduced.
- Unsafe override required: no.
- Qualification impact: retained regressions and actual
filesystem/liveness behavior were checked.
- Rollback path: revert the test-only delta; runtime remains unchanged.

## 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)

Not applicable; filesystem/runtime evidence is recorded above.

## Additional Notes

<!-- Mention any N/A checklist items, tradeoffs, follow-ups, or
maintainer context. -->

The supersession feedback is correct. There is no request to replace the
stronger implementation already in `main`, and no new test-only PR was
opened to chase a known main failure. The unchecked documentation item
is not applicable to retaining these two tests. Maintainers can decide
whether this remaining coverage is useful or redundant.
This commit is contained in:
rNoz
2026-11-03 18:01:01 -06:00
committed by GitHub
parent 312ffec8ea
commit 2643f34a54
@@ -317,3 +317,74 @@ def test_selfheal_command_preserves_live_marker(tmp_path: Path, monkeypatch) ->
def test_selfheal_never_raises_without_settings(tmp_path: Path, monkeypatch) -> None:
monkeypatch.chdir(tmp_path)
wrap_cli._selfheal_dead_wrap_base_url() # no .claude dir at all — silent no-op
def test_wrap_selfheal_hook_overwrites_drifted_command(tmp_path: Path) -> None:
path = _settings(tmp_path)
path.parent.mkdir(parents=True)
path.write_text(
json.dumps(
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{
"type": "command",
"command": f"/usr/bin/claude wrap selfheal --marker {_HOOK_MARKER}",
"timeout": 10,
}
],
}
]
}
}
),
encoding="utf-8",
newline="\n",
)
wrap_cli._ensure_claude_wrap_selfheal_hook(path)
payload = json.loads(path.read_text(encoding="utf-8"))
entries = payload["hooks"]["SessionStart"]
assert len(entries) == 1
command = entries[0]["hooks"][0]["command"]
assert "/usr/bin/claude" not in command
assert "wrap selfheal" in command
assert _HOOK_MARKER in command
def test_wrap_selfheal_hook_skips_malformed_sessionstart_entries(tmp_path: Path) -> None:
path = _settings(tmp_path)
path.parent.mkdir(parents=True)
path.write_text(
json.dumps(
{
"hooks": {
"SessionStart": [
"not-a-dict",
{"matcher": "startup", "hooks": "not-a-list"},
]
}
}
),
encoding="utf-8",
newline="\n",
)
wrap_cli._ensure_claude_wrap_selfheal_hook(path)
payload = json.loads(path.read_text(encoding="utf-8"))
entries = payload["hooks"]["SessionStart"]
assert entries[0] == "not-a-dict"
assert entries[1] == {"matcher": "startup", "hooks": "not-a-list"}
marked = [
entry
for entry in entries
if isinstance(entry, dict)
and isinstance(entry.get("hooks"), list)
and any(_HOOK_MARKER in h.get("command", "") for h in entry["hooks"])
]
assert len(marked) == 1