Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(sessions): make the transcript layer harness-agnostic (#1316)

Raghav Chamadiyaacd24602cf51
diff --git a/packages/core/src/repowise/core/distill/corrections.py b/packages/core/src/repowise/core/distill/corrections.py
index 838fb481b..9c6adf8ea 100644
--- a/packages/core/src/repowise/core/distill/corrections.py
+++ b/packages/core/src/repowise/core/distill/corrections.py
@@ -27,7 +27,7 @@ import time
from pathlib import Path
from typing import Any
-from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
+from repowise.core.sessions import INTENT_SHELL_CALLS, Event, HarnessAdapter, get_adapter
#: Default scan window, in days. Corrections are rarer than missed savings,
#: so the default window is wider.
@@ -44,8 +44,6 @@ WRITE_MAX_RULES = 10
_SHELL_TOOLS = ("Bash", "PowerShell")
-_ADAPTER = ClaudeCodeAdapter()
-
#: The one true command-failure shape in real transcripts. Everything else
#: stringly (cancellations, rejections, permission denials, harness errors)
#: is not a command failure.
@@ -142,9 +140,10 @@ def scan_corrections(
def _scan(
repo_root: Path, days: float, now: float | None, projects_root: Path | None
) -> dict[str, Any]:
- transcripts = transcript_dir_for(repo_root, projects_root)
+ adapter = get_adapter()
report = empty_report(days)
- if not transcripts.is_dir():
+ transcripts = adapter.discover(repo_root, projects_root=projects_root)
+ if not transcripts:
return report
cutoff = (now if now is not None else time.time()) - days * 86400.0
@@ -152,11 +151,11 @@ def _scan(
rules: dict[tuple[str, str, str], dict[str, Any]] = {}
pairs = 0
- for path in sorted(transcripts.glob("*.jsonl")):
+ for path in transcripts:
try:
if path.stat().st_mtime < cutoff:
continue
- events = _session_events(path, cutoff, repo_prefix)
+ events = _session_events(adapter, path, cutoff, repo_prefix)
except OSError:
continue
pairs += _pair_events(events, rules)
@@ -173,16 +172,14 @@ def _scan(
# ---------------------------------------------------------------------------
-def _prefilter(raw: str) -> bool:
- """Only shell tool_use lines and result lines are worth parsing."""
- return ('"tool_use"' in raw and '"command"' in raw) or '"toolUseResult"' in raw
-
-
-def _session_events(path: Path, cutoff: float, repo_prefix: str) -> list[dict[str, Any]]:
+def _session_events(
+ adapter: HarnessAdapter, path: Path, cutoff: float, repo_prefix: str
+) -> list[dict[str, Any]]:
"""Ordered shell events: ``{"command", "failed", "error"}`` per call."""
events: list[dict[str, Any]] = []
pending: dict[str, str] = {}
- for event in _ADAPTER.iter_events(path, prefilter=_prefilter):
+ prefilter = adapter.prefilter(INTENT_SHELL_CALLS)
+ for event in adapter.iter_events(path, prefilter=prefilter):
if event.kind == "assistant" and event.tool_uses:
_collect_tool_use(event, cutoff, repo_prefix, pending)
elif pending and event.tool_results:
diff --git a/packages/core/src/repowise/core/distill/missed.py b/packages/core/src/repowise/core/distill/missed.py
index 6306a1834..1cda40781 100644
--- a/packages/core/src/repowise/core/distill/missed.py
+++ b/packages/core/src/repowise/core/distill/missed.py
@@ -30,9 +30,9 @@ from typing import Any
from repowise.core.distill.budget import estimate_tokens
from repowise.core.distill.markers import MARKER_RE
from repowise.core.distill.router import normalize_command, select_filter
-from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
+from repowise.core.sessions import INTENT_SHELL_CALLS, Event, HarnessAdapter, get_adapter
-__all__ = ["scan_missed_savings", "transcript_dir_for"]
+__all__ = ["scan_missed_savings"]
#: Default scan window, in days.
DEFAULT_WINDOW_DAYS = 7.0
@@ -65,8 +65,6 @@ _MIN_EST_TOKENS = 40
_SHELL_TOOLS = ("Bash", "PowerShell")
-_ADAPTER = ClaudeCodeAdapter()
-
def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
return {
@@ -102,20 +100,21 @@ def scan_missed_savings(
def _scan(
repo_root: Path, days: float, now: float | None, projects_root: Path | None
) -> dict[str, Any]:
- transcripts = transcript_dir_for(repo_root, projects_root)
+ adapter = get_adapter()
report = empty_report(days)
- if not transcripts.is_dir():
+ transcripts = adapter.discover(repo_root, projects_root=projects_root)
+ if not transcripts:
return report
cutoff = (now if now is not None else time.time()) - days * 86400.0
repo_prefix = str(repo_root).lower().rstrip("\\/")
per_filter: dict[str, dict[str, int]] = {}
- for path in sorted(transcripts.glob("*.jsonl")):
+ for path in transcripts:
try:
if path.stat().st_mtime < cutoff:
continue # untouched since the window opened
- _scan_file(path, cutoff, repo_prefix, per_filter)
+ _scan_file(adapter, path, cutoff, repo_prefix, per_filter)
except OSError:
continue
@@ -129,17 +128,17 @@ def _scan(
return report
-def _prefilter(raw: str) -> bool:
- """Only shell tool_use lines and result lines are worth parsing."""
- return ('"tool_use"' in raw and '"command"' in raw) or '"toolUseResult"' in raw
-
-
def _scan_file(
- path: Path, cutoff: float, repo_prefix: str, per_filter: dict[str, dict[str, int]]
+ adapter: HarnessAdapter,
+ path: Path,
+ cutoff: float,
+ repo_prefix: str,
+ per_filter: dict[str, dict[str, int]],
) -> None:
#: tool_use id -> command, for shell calls that passed every command gate.
pending: dict[str, str] = {}
- for event in _ADAPTER.iter_events(path, prefilter=_prefilter):
+ prefilter = adapter.prefilter(INTENT_SHELL_CALLS)
+ for event in adapter.iter_events(path, prefilter=prefilter):
if event.kind == "assistant" and event.tool_uses:
_collect_tool_use(event, cutoff, repo_prefix, pending)
elif pending and event.tool_results:
diff --git a/packages/core/src/repowise/core/distill/missed_mcp.py b/packages/core/src/repowise/core/distill/missed_mcp.py
index 06d660200..48a1c7338 100644
--- a/packages/core/src/repowise/core/distill/missed_mcp.py
+++ b/packages/core/src/repowise/core/distill/missed_mcp.py
@@ -36,7 +36,7 @@ from pathlib import Path
from typing import Any
from repowise.core.distill.budget import estimate_tokens
-from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
+from repowise.core.sessions import INTENT_TOOL_CALLS, Event, HarnessAdapter, get_adapter
#: Default scan window, in days. Matches the missed-savings scan.
DEFAULT_WINDOW_DAYS = 7.0
@@ -53,8 +53,6 @@ _MIN_EST_TOKENS = 40
_MUTATING_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
-_ADAPTER = ClaudeCodeAdapter()
-
def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
return {
@@ -87,20 +85,21 @@ def scan_missed_mcp_savings(
def _scan(
repo_root: Path, days: float, now: float | None, projects_root: Path | None
) -> dict[str, Any]:
- transcripts = transcript_dir_for(repo_root, projects_root)
+ adapter = get_adapter()
report = empty_report(days)
- if not transcripts.is_dir():
+ transcripts = adapter.discover(repo_root, projects_root=projects_root)
+ if not transcripts:
return report
cutoff = (now if now is not None else time.time()) - days * 86400.0
repo_prefix = str(repo_root).lower().rstrip("\\/")
per_file: dict[str, dict[str, int]] = {}
- for path in sorted(transcripts.glob("*.jsonl")):
+ for path in transcripts:
try:
if path.stat().st_mtime < cutoff:
continue # untouched since the window opened
- _scan_file(path, cutoff, repo_prefix, repo_root, per_file)
+ _scan_file(adapter, path, cutoff, repo_prefix, repo_root, per_file)
except OSError:
continue
@@ -123,12 +122,8 @@ def _rel(file_path: str, repo_root: Path) -> str:
return rel.replace("\\", "/")
-def _prefilter(raw: str) -> bool:
- """Only tool_use lines and result lines are worth parsing."""
- return '"tool_use"' in raw or '"tool_result"' in raw
-
-
def _scan_file(
+ adapter: HarnessAdapter,
path: Path,
cutoff: float,
repo_prefix: str,
@@ -146,7 +141,8 @@ def _scan_file(
last_read_seq: dict[str, int] = {}
last_edit_seq: dict[str, int] = {}
- for event in _ADAPTER.iter_events(path, prefilter=_prefilter):
+ prefilter = adapter.prefilter(INTENT_TOOL_CALLS)
+ for event in adapter.iter_events(path, prefilter=prefilter):
if event.kind == "assistant":
seq = _collect_tool_use(event, cutoff, repo_prefix, seq, pending, last_edit_seq)
elif pending and event.tool_results:
diff --git a/packages/core/src/repowise/core/sessions/__init__.py b/packages/core/src/repowise/core/sessions/__init__.py
index d7ef78f3e..9747fecef 100644
--- a/packages/core/src/repowise/core/sessions/__init__.py
+++ b/packages/core/src/repowise/core/sessions/__init__.py
@@ -13,12 +13,18 @@ Everything here is read-only and local: transcripts are read from the user's
own machine and never leave it.
"""
-from repowise.core.sessions.adapters.base import HarnessAdapter
-from repowise.core.sessions.adapters.claude_code import (
+from repowise.core.sessions.adapters import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
ClaudeCodeAdapter,
- parse_timestamp,
- transcript_dir_for,
+ HarnessAdapter,
+ RawPrefilter,
+ get_adapter,
+ register_adapter,
+ registered_adapters,
)
+from repowise.core.sessions.adapters.claude_code import transcript_dir_for
from repowise.core.sessions.cursor import CursorStore, iter_new_events
from repowise.core.sessions.events import (
INTERRUPT_MARKER,
@@ -26,18 +32,26 @@ from repowise.core.sessions.events import (
ToolResult,
ToolUse,
iter_deduped_usage,
+ parse_timestamp,
)
__all__ = [
+ "INTENT_SHELL_CALLS",
+ "INTENT_TOOL_CALLS",
+ "INTENT_TURNS",
"INTERRUPT_MARKER",
"ClaudeCodeAdapter",
"CursorStore",
"Event",
"HarnessAdapter",
+ "RawPrefilter",
"ToolResult",
"ToolUse",
+ "get_adapter",
"iter_deduped_usage",
"iter_new_events",
"parse_timestamp",
+ "register_adapter",
+ "registered_adapters",
"transcript_dir_for",
]
diff --git a/packages/core/src/repowise/core/sessions/adapters/__init__.py b/packages/core/src/repowise/core/sessions/adapters/__init__.py
index 7cc93289e..5da64a2e1 100644
--- a/packages/core/src/repowise/core/sessions/adapters/__init__.py
+++ b/packages/core/src/repowise/core/sessions/adapters/__init__.py
@@ -1,6 +1,31 @@
-"""Harness adapters: one per coding agent whose transcripts we can read."""
+"""Harness adapters: one per coding agent whose transcripts we can read.
-from repowise.core.sessions.adapters.base import HarnessAdapter
+Importing this package is what registers the built-in adapters; a new
+harness adds its import here and nothing else changes.
+"""
+
+from repowise.core.sessions.adapters.base import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
+ HarnessAdapter,
+ RawPrefilter,
+)
from repowise.core.sessions.adapters.claude_code import ClaudeCodeAdapter
+from repowise.core.sessions.adapters.registry import (
+ get_adapter,
+ register_adapter,
+ registered_adapters,
+)
-__all__ = ["ClaudeCodeAdapter", "HarnessAdapter"]
+__all__ = [
+ "INTENT_SHELL_CALLS",
+ "INTENT_TOOL_CALLS",
+ "INTENT_TURNS",
+ "ClaudeCodeAdapter",
+ "HarnessAdapter",
+ "RawPrefilter",
+ "get_adapter",
+ "register_adapter",
+ "registered_adapters",
+]
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
index 6f644e788..b5093747c 100644
--- a/packages/core/src/repowise/core/sessions/adapters/base.py
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -15,7 +15,7 @@ apply their own skip policy per file.
from __future__ import annotations
from abc import ABC, abstractmethod
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterable, Iterator
from pathlib import Path
from typing import ClassVar
@@ -27,6 +27,18 @@ from repowise.core.sessions.events import Event
#: so consumers that only want tool events pass one of these.
RawPrefilter = Callable[[str], bool]
+#: What a consumer wants out of a transcript, named rather than spelled.
+#: A consumer asks for an intent; the adapter owns which of its harness's
+#: key names spot it, so harness vocabulary never leaks into a miner.
+#:
+#: Shell tool calls together with their results (command-level mining).
+INTENT_SHELL_CALLS = "shell_calls"
+#: Any tool call or tool result, shell or otherwise.
+INTENT_TOOL_CALLS = "tool_calls"
+#: Conversation turns: user prose, assistant prose, and the tool traffic
+#: carried on them.
+INTENT_TURNS = "turns"
+
class HarnessAdapter(ABC):
"""Reads one agent's transcripts into the shared Event stream."""
@@ -46,16 +58,78 @@ class HarnessAdapter(ABC):
def normalize(self, raw_line: str) -> Event | None:
"""One raw transcript line as an Event, or None when unparseable."""
- def iter_events(self, path: Path, *, prefilter: RawPrefilter | None = None) -> Iterator[Event]:
- """Events from one transcript file, in order.
+ def prefilter(self, intent: str) -> RawPrefilter | None:
+ """A cheap raw-line gate for *intent*, or None for no gate.
- Lines failing *prefilter* are skipped without being parsed. Decoding
- is tolerant (``errors="replace"``); ``OSError`` propagates.
+ The returned predicate reads the **raw string** and runs before any
+ parsing: lines routinely run to hundreds of kilobytes, and this gate
+ is most of the layer's speed. An adapter that normalizes the line to
+ decide would give all of it back, so overrides return a predicate
+ over the text and nothing else.
+
+ None means "no cheap gate for this intent", so every line is parsed.
+ Correct but slow, which is the right default for an intent an
+ adapter has not thought about.
"""
- with path.open(encoding="utf-8", errors="replace") as fh:
- for raw in fh:
+ return None
+
+ def begin_file(self, path: Path | None = None) -> None: # noqa: B027 — opt-in hook
+ """Called once before the first line of a transcript.
+
+ The hook exists so an adapter whose harness splits one logical event
+ across lines can hold correlation state for the duration of a file.
+ Stateless adapters ignore it. Events are still emitted by
+ :meth:`normalize`, one line at a time; this scopes state, it is not
+ a flush protocol.
+
+ *path* is the transcript being opened when the drive path knows it,
+ and None when the caller supplied bare lines.
+ """
+
+ def end_file(self) -> None: # noqa: B027 — opt-in hook
+ """Called after the last line of a transcript, including on error."""
+
+ def events_from_lines(
+ self,
+ lines: Iterable[str],
+ *,
+ prefilter: RawPrefilter | None = None,
+ path: Path | None = None,
+ ) -> Iterator[Event]:
+ """Normalized events from already-decoded transcript *lines*.
+
+ The one read loop: gate, normalize, skip unparseable, bracketed by
+ the per-file lifecycle. Every drive path routes through here; only
+ the source of lines differs (a whole file, a cursored tail, or a
+ handle the caller already holds).
+
+ The gate runs on the raw string and decides *before* :meth:`normalize`
+ is paid for. That ordering is the layer's performance contract, not an
+ implementation detail; a line that fails the gate is never parsed.
+
+ One adapter drives one transcript at a time. This is a generator, so
+ the lifecycle brackets iteration rather than the call: ``begin_file``
+ runs on the first ``next()`` and ``end_file`` when the iterator is
+ exhausted, closed, or collected. A caller that opens a second iterator
+ on the same adapter before draining the first would interleave two
+ files into one adapter's state, so callers iterate one at a time.
+ """
+ self.begin_file(path)
+ try:
+ for raw in lines:
if prefilter is not None and not prefilter(raw):
continue
event = self.normalize(raw)
if event is not None:
yield event
+ finally:
+ self.end_file()
+
+ def iter_events(self, path: Path, *, prefilter: RawPrefilter | None = None) -> Iterator[Event]:
+ """Events from one transcript file, in order.
+
+ Lines failing *prefilter* are skipped without being parsed. Decoding
+ is tolerant (``errors="replace"``); ``OSError`` propagates.
+ """
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ yield from self.events_from_lines(fh, prefilter=prefilter, path=path)
diff --git a/packages/core/src/repowise/core/sessions/adapters/claude_code.py b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
index 4eb5a3f85..ad28451c6 100644
--- a/packages/core/src/repowise/core/sessions/adapters/claude_code.py
+++ b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
@@ -22,15 +22,27 @@ from __future__ import annotations
import json
import re
-from datetime import datetime
from pathlib import Path
from typing import Any, ClassVar
-from repowise.core.sessions.adapters.base import HarnessAdapter
-from repowise.core.sessions.events import Event, ToolResult, ToolUse
+from repowise.core.sessions.adapters.base import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
+ HarnessAdapter,
+ RawPrefilter,
+)
+from repowise.core.sessions.adapters.registry import register_adapter
+from repowise.core.sessions.events import Event, ToolResult, ToolUse, parse_timestamp
_NON_SLUG_RE = re.compile(r"[^A-Za-z0-9-]")
+#: Conversation turns in Claude Code's JSONL. One alternation rather than a
+#: tuple of both JSON spellings: a tuple scans the whole (often huge) line
+#: once per token and silently stops matching the day a writer pretty-prints
+#: with two spaces. Same trade the security scan already makes.
+_TURN_RE = re.compile(r'"type":\s*"(?:user|assistant)"')
+
def transcript_dir_for(repo_root: Path, projects_root: Path | None = None) -> Path:
"""The Claude Code transcript directory for sessions started at *repo_root*.
@@ -41,16 +53,7 @@ def transcript_dir_for(repo_root: Path, projects_root: Path | None = None) -> Pa
return root / _NON_SLUG_RE.sub("-", str(repo_root))
-def parse_timestamp(value: Any) -> float | None:
- """Epoch seconds from an ISO-8601 transcript timestamp, or None."""
- if not isinstance(value, str):
- return None
- try:
- return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
- except ValueError:
- return None
-
-
+@register_adapter
class ClaudeCodeAdapter(HarnessAdapter):
"""Normalizes Claude Code session JSONL into the shared Event stream."""
@@ -62,6 +65,20 @@ class ClaudeCodeAdapter(HarnessAdapter):
return []
return sorted(directory.glob("*.jsonl"))
+ def prefilter(self, intent: str) -> RawPrefilter | None:
+ """Claude Code's raw-line gates, keyed by what the consumer wants.
+
+ ``toolUseResult`` is a Claude-Code-only key and appears here rather
+ than in any miner. Every predicate reads the raw string only.
+ """
+ if intent == INTENT_SHELL_CALLS:
+ return _shell_calls_prefilter
+ if intent == INTENT_TOOL_CALLS:
+ return _tool_calls_prefilter
+ if intent == INTENT_TURNS:
+ return _turns_prefilter
+ return None
+
def normalize(self, raw_line: str) -> Event | None:
try:
entry = json.loads(raw_line)
@@ -139,5 +156,25 @@ class ClaudeCodeAdapter(HarnessAdapter):
event.text = "\n".join(texts)
+def _shell_calls_prefilter(raw: str) -> bool:
+ """Only shell tool_use lines and result lines are worth parsing."""
+ return ('"tool_use"' in raw and '"command"' in raw) or '"toolUseResult"' in raw
+
+
+def _tool_calls_prefilter(raw: str) -> bool:
+ """Only tool_use lines and result lines are worth parsing."""
+ return '"tool_use"' in raw or '"tool_result"' in raw
+
+
+def _turns_prefilter(raw: str) -> bool:
+ """Dialog lines only; skips the fat non-dialog entries.
+
+ User prose, assistant prose, tool uses and results all ride "user" and
+ "assistant" entries; what this drops is file-history snapshots, queue
+ operations and system hooks.
+ """
+ return _TURN_RE.search(raw) is not None
+
+
def _str_or_none(value: Any) -> str | None:
return value if isinstance(value, str) and value else None
diff --git a/packages/core/src/repowise/core/sessions/adapters/registry.py b/packages/core/src/repowise/core/sessions/adapters/registry.py
new file mode 100644
index 000000000..2bd2afd15
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/adapters/registry.py
@@ -0,0 +1,49 @@
+"""Which transcript adapter a consumer gets, by name.
+
+Governs the transcript-reading adapters in this package
+(:class:`~repowise.core.sessions.adapters.base.HarnessAdapter`) — the ones
+that turn a session file into an Event stream. Not to be confused with the
+similarly named ``repowise.cli.agent_adapters`` family, which installs and
+checks editor hooks and shares nothing with this one but a word.
+
+One entry today (Claude Code). The point is not extensibility for its own
+sake: it is that a second harness becomes a registration in its own module
+rather than a search-and-replace across every module that reads transcripts.
+
+Lookup happens per call, never at import. Adapters may hold per-file state
+(see :meth:`~repowise.core.sessions.adapters.base.HarnessAdapter.begin_file`),
+so a shared module-level instance would be a bug the day one does; and a
+module-level construction is weight on the hook import path, which has been
+fought down once already.
+"""
+
+from __future__ import annotations
+
+from repowise.core.sessions.adapters.base import HarnessAdapter
+
+#: Registered adapter classes, keyed by their ``name``.
+_ADAPTERS: dict[str, type[HarnessAdapter]] = {}
+
+#: The harness assumed when a caller names none.
+DEFAULT_ADAPTER = "claude_code"
+
+
+def register_adapter(adapter_cls: type[HarnessAdapter]) -> type[HarnessAdapter]:
+ """Register *adapter_cls* under its ``name``. Returns it, so it decorates."""
+ _ADAPTERS[adapter_cls.name] = adapter_cls
+ return adapter_cls
+
+
+def get_adapter(name: str | None = None) -> HarnessAdapter:
+ """A fresh adapter instance for *name*, defaulting to Claude Code."""
+ key = name or DEFAULT_ADAPTER
+ try:
+ adapter_cls = _ADAPTERS[key]
+ except KeyError:
+ raise LookupError(f"no transcript adapter registered for {key!r}") from None
+ return adapter_cls()
+
+
+def registered_adapters() -> list[str]:
+ """Names of every registered harness, sorted."""
+ return sorted(_ADAPTERS)
diff --git a/packages/core/src/repowise/core/sessions/cursor.py b/packages/core/src/repowise/core/sessions/cursor.py
index a9d822b3e..d8ec99075 100644
--- a/packages/core/src/repowise/core/sessions/cursor.py
+++ b/packages/core/src/repowise/core/sessions/cursor.py
@@ -73,8 +73,8 @@ def iter_new_events(
"""Events appended to *path* since the stored cursor, advancing it.
The file is read in binary so offsets are exact bytes; each line decodes
- tolerantly before hitting the adapter. ``OSError`` propagates, matching
- :meth:`HarnessAdapter.iter_events`.
+ tolerantly before hitting the adapter's shared read loop. ``OSError``
+ propagates, matching :meth:`HarnessAdapter.iter_events`.
"""
stat = path.stat()
cursor = store.get(path)
@@ -84,18 +84,27 @@ def iter_new_events(
if start == stat.st_size and cursor is not None and cursor.get("mtime") == stat.st_mtime:
return # nothing appended since the last pass
- offset = start
with path.open("rb") as fh:
if start:
fh.seek(start)
- for raw_bytes in fh:
- if not raw_bytes.endswith(b"\n"):
- break # write in progress; next pass picks it up
- offset += len(raw_bytes)
- store.advance(path, offset=offset, mtime=stat.st_mtime)
- raw = raw_bytes.decode("utf-8", errors="replace")
- if prefilter is not None and not prefilter(raw):
- continue
- event = adapter.normalize(raw)
- if event is not None:
- yield event
+ lines = _cursored_lines(fh, path, store, start=start, mtime=stat.st_mtime)
+ yield from adapter.events_from_lines(lines, prefilter=prefilter, path=path)
+
+
+def _cursored_lines(
+ fh: Iterator[bytes], path: Path, store: CursorStore, *, start: int, mtime: float
+) -> Iterator[str]:
+ """Decoded lines from *fh*, advancing the cursor as each is handed over.
+
+ The cursor moves when a complete line is read, not when an event is
+ yielded for it, so a line the prefilter drops is still consumed exactly
+ once. A partially consumed iterator therefore leaves the cursor at the
+ last line it actually read.
+ """
+ offset = start
+ for raw_bytes in fh:
+ if not raw_bytes.endswith(b"\n"):
+ break # write in progress; next pass picks it up
+ offset += len(raw_bytes)
+ store.advance(path, offset=offset, mtime=mtime)
+ yield raw_bytes.decode("utf-8", errors="replace")
diff --git a/packages/core/src/repowise/core/sessions/efficacy.py b/packages/core/src/repowise/core/sessions/efficacy.py
index d12c11c17..85ab05007 100644
--- a/packages/core/src/repowise/core/sessions/efficacy.py
+++ b/packages/core/src/repowise/core/sessions/efficacy.py
@@ -526,7 +526,7 @@ def _tool_uses(line: str, index: int) -> list[tuple[int, str, str]]:
def _parse_ts(value: Any) -> float | None:
- from repowise.core.sessions.adapters.claude_code import parse_timestamp
+ from repowise.core.sessions.events import parse_timestamp
return parse_timestamp(value)
diff --git a/packages/core/src/repowise/core/sessions/events.py b/packages/core/src/repowise/core/sessions/events.py
index 2f53d1300..0a4dd49e4 100644
--- a/packages/core/src/repowise/core/sessions/events.py
+++ b/packages/core/src/repowise/core/sessions/events.py
@@ -11,6 +11,7 @@ from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass, field
+from datetime import datetime
from typing import Any
#: Claude Code injects this text into the conversation when the user
@@ -19,6 +20,20 @@ from typing import Any
INTERRUPT_MARKER = "[Request interrupted by user"
+def parse_timestamp(value: Any) -> float | None:
+ """Epoch seconds from an ISO-8601 transcript timestamp, or None.
+
+ Lives here rather than in an adapter because ISO-8601 is not a property
+ of any one harness; adapters and consumers both read it.
+ """
+ if not isinstance(value, str):
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ return None
+
+
@dataclass(slots=True)
class ToolUse:
"""One tool invocation block inside an assistant event."""
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 54fca31b6..2aedbc049 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -62,7 +62,7 @@ from repowise.core.analysis.decisions.provenance import (
)
from repowise.core.analysis.decisions.rationale_comments import CAUSAL_MARKERS
from repowise.core.distill.corrections import command_anchor
-from repowise.core.sessions import ClaudeCodeAdapter, Event
+from repowise.core.sessions import INTENT_TURNS, Event, get_adapter
from repowise.core.sessions.cursor import iter_new_events
from repowise.core.sessions.staging import SessionStagingStore
@@ -420,21 +420,6 @@ guidance, questions, or venting. Return a JSON array; [] if none qualify.
MAX_STRUCTURED_PER_UPDATE = 60
_LLM_CHUNK = 12
-# This miner needs user prose, assistant prose, tool uses, and results; in
-# Claude Code all of them are "user"/"assistant" entries. Both compact and
-# spaced JSON spellings are matched; what this skips is the fat non-dialog
-# lines (file-history snapshots, queue operations, system hooks).
-_PREFILTER_TOKENS = (
- '"type":"user"',
- '"type": "user"',
- '"type":"assistant"',
- '"type": "assistant"',
-)
-
-
-def _prefilter(raw: str) -> bool:
- return any(tok in raw for tok in _PREFILTER_TOKENS)
-
def session_mining_enabled(repo_config: dict[str, Any] | None) -> bool:
"""Resolve the ``decisions.session_mining`` config gate (default on)."""
@@ -722,7 +707,10 @@ async def mine_session_decisions(
"""
repo_root = Path(repo_path).resolve()
repo_prefix = str(repo_root).lower().rstrip("\\/")
- adapter = ClaudeCodeAdapter()
+ adapter = get_adapter()
+ # This miner needs user prose, assistant prose, tool uses and results:
+ # everything the conversation carries, minus the fat non-dialog lines.
+ prefilter = adapter.prefilter(INTENT_TURNS)
store = SessionStagingStore.open_default(repo_root)
try:
@@ -730,7 +718,7 @@ async def mine_session_decisions(
staged = 0
for path in adapter.discover(repo_root, projects_root=projects_root):
try:
- events = iter_new_events(adapter, path, store.cursors, prefilter=_prefilter)
+ events = iter_new_events(adapter, path, store.cursors, prefilter=prefilter)
for candidate in mine_events(events, repo_prefix):
if store.add_raw(
hash_=candidate.hash,
diff --git a/packages/core/src/repowise/core/sessions/miners/demand.py b/packages/core/src/repowise/core/sessions/miners/demand.py
index bcbdbc1fe..e195d8e89 100644
--- a/packages/core/src/repowise/core/sessions/miners/demand.py
+++ b/packages/core/src/repowise/core/sessions/miners/demand.py
@@ -38,7 +38,7 @@ from typing import Any
import structlog
from repowise.core.ids import file_path_of
-from repowise.core.sessions import ClaudeCodeAdapter, Event
+from repowise.core.sessions import INTENT_TURNS, Event, HarnessAdapter, get_adapter
logger = structlog.get_logger(__name__)
@@ -60,15 +60,6 @@ _SEARCH_TOOL = "search_codebase"
_MAX_ANSWER_FILES = 5
_MAX_SEARCH_FILES = 10
-#: Only these transcript lines can carry a question or its result; skipping the
-#: rest keeps the full-history sweep cheap.
-_PREFILTER_TOKENS = (
- '"type":"user"',
- '"type": "user"',
- '"type":"assistant"',
- '"type": "assistant"',
-)
-
def faq_weighting_enabled(repo_config: dict[str, Any] | None) -> bool:
"""Resolve the ``generation.faq_weighting`` config gate (default on)."""
@@ -213,20 +204,16 @@ def mine_events_demand(events: Iterable[Event], repo_prefix: str) -> Counter:
return demand
-def _prefilter(raw: str) -> bool:
- return any(tok in raw for tok in _PREFILTER_TOKENS)
-
-
def aggregate_file_demand(
repo_path: Path | str,
*,
- adapter: ClaudeCodeAdapter | None = None,
+ adapter: HarnessAdapter | None = None,
projects_root: Path | None = None,
repo_config: dict[str, Any] | None = None,
) -> dict[str, int]:
"""Per-file question demand for *repo_path* from its transcript history.
- Full best-effort sweep over the repo's Claude Code transcripts. Returns
+ Full best-effort sweep over the repo's agent transcripts. Returns
``{repo_relative_path: question_count}``; an empty dict when FAQ weighting
is disabled, no transcripts exist, or anything goes wrong (the planner then
falls back to its uniform behaviour). Never raises.
@@ -235,18 +222,27 @@ def aggregate_file_demand(
return {}
repo_root = Path(repo_path).resolve()
repo_prefix = str(repo_root).lower().rstrip("\\/")
- adapter = adapter or ClaudeCodeAdapter()
demand: Counter = Counter()
try:
+ adapter = adapter or get_adapter()
+ # Only dialog lines can carry a question or its result; skipping the
+ # rest keeps the full-history sweep cheap.
+ prefilter = adapter.prefilter(INTENT_TURNS)
transcripts = adapter.discover(repo_root, projects_root=projects_root)
- except OSError:
+ except Exception:
+ # Never raises, by contract: the planner falls back to uniform
+ # budgets. Broad on purpose now that the adapter is substitutable —
+ # a second harness's discovery may fail in ways OSError does not name.
return {}
+ # The handle stays here: this sweep reads whole history in binary and
+ # decodes per line, rather than driving from a path like the other two.
for path in transcripts:
try:
with path.open("rb") as fh:
- events = _iter_events(adapter, fh)
+ lines = (raw.decode("utf-8", errors="replace") for raw in fh)
+ events = adapter.events_from_lines(lines, prefilter=prefilter, path=path)
demand.update(mine_events_demand(events, repo_prefix))
except OSError:
continue
@@ -261,17 +257,6 @@ def aggregate_file_demand(
return dict(demand)
-def _iter_events(adapter: ClaudeCodeAdapter, fh: Iterable[bytes]) -> Iterable[Event]:
- """Normalized events from prefiltered transcript lines."""
- for raw in fh:
- line = raw.decode("utf-8", errors="replace")
- if not _prefilter(line):
- continue
- event = adapter.normalize(line)
- if event is not None:
- yield event
-
-
def demand_summary_line(file_demand: dict[str, int]) -> str | None:
"""A one-line, human summary of the demand behind the budget tilt.
diff --git a/tests/unit/distill/test_corrections.py b/tests/unit/distill/test_corrections.py
index f1f4dd232..df1443461 100644
--- a/tests/unit/distill/test_corrections.py
+++ b/tests/unit/distill/test_corrections.py
@@ -27,7 +27,7 @@ from repowise.core.distill.corrections import (
strip_preamble,
update_corrections_block,
)
-from repowise.core.distill.missed import transcript_dir_for
+from repowise.core.sessions import transcript_dir_for
NOW = time.time()
@@ -444,10 +444,11 @@ class TestManagedBlock:
class TestCli:
@pytest.fixture(autouse=True)
def _redirect_transcripts(self, projects: Path, monkeypatch) -> None:
- from repowise.core.distill import corrections as core
-
+ # The CLI has no --projects-root, so redirect discovery at the
+ # adapter: ClaudeCodeAdapter.discover reads this as a module global.
monkeypatch.setattr(
- core, "transcript_dir_for", lambda root, _=None: transcript_dir_for(root, projects)
+ "repowise.core.sessions.adapters.claude_code.transcript_dir_for",
+ lambda root, projects_root=None: transcript_dir_for(root, projects),
)
def test_report_only_by_default(self, repo: Path, projects: Path, monkeypatch) -> None:
diff --git a/tests/unit/distill/test_missed_mcp.py b/tests/unit/distill/test_missed_mcp.py
index 3b4501422..f8846a12e 100644
--- a/tests/unit/distill/test_missed_mcp.py
+++ b/tests/unit/distill/test_missed_mcp.py
@@ -18,8 +18,8 @@ from click.testing import CliRunner
from repowise.cli.commands.saved_cmd import saved_command
from repowise.core.distill.budget import estimate_tokens
-from repowise.core.distill.missed import transcript_dir_for
from repowise.core.distill.missed_mcp import REREAD_FLOOR, scan_missed_mcp_savings
+from repowise.core.sessions import transcript_dir_for
NOW = time.time()
@@ -295,8 +295,10 @@ def test_saved_missed_shows_reread_table(repo: Path, projects: Path, monkeypatch
f, BIG_CONTENT, cwd=str(repo), block_id="r2"
)
_write_session(projects, repo, entries)
+ # The CLI has no --projects-root, so redirect discovery at the adapter:
+ # ClaudeCodeAdapter.discover reads this as a module global.
monkeypatch.setattr(
- "repowise.core.distill.missed_mcp.transcript_dir_for",
+ "repowise.core.sessions.adapters.claude_code.transcript_dir_for",
lambda root, projects_root=None: transcript_dir_for(root, projects),
)
result = CliRunner().invoke(saved_command, ["--missed", str(repo)])
diff --git a/tests/unit/distill/test_missed_savings.py b/tests/unit/distill/test_missed_savings.py
index 0eb3ebce8..f2efd67b1 100644
--- a/tests/unit/distill/test_missed_savings.py
+++ b/tests/unit/distill/test_missed_savings.py
@@ -18,11 +18,8 @@ import pytest
from click.testing import CliRunner
from repowise.cli.commands.saved_cmd import saved_command
-from repowise.core.distill.missed import (
- RATIO_FLOOR,
- scan_missed_savings,
- transcript_dir_for,
-)
+from repowise.core.distill.missed import RATIO_FLOOR, scan_missed_savings
+from repowise.core.sessions import transcript_dir_for
NOW = time.time()
@@ -222,8 +219,10 @@ def test_saved_missed_empty_report_message(tmp_path: Path, monkeypatch) -> None:
def test_saved_missed_table(repo: Path, projects: Path, monkeypatch) -> None:
_write_session(projects, repo, _tool_pair("pytest -q", PYTEST_OUT, cwd=str(repo)))
+ # The CLI has no --projects-root, so redirect discovery at the adapter:
+ # ClaudeCodeAdapter.discover reads this as a module global.
monkeypatch.setattr(
- "repowise.core.distill.missed.transcript_dir_for",
+ "repowise.core.sessions.adapters.claude_code.transcript_dir_for",
lambda root, projects_root=None: transcript_dir_for(root, projects),
)
result = CliRunner().invoke(saved_command, ["--missed", str(repo)])
diff --git a/tests/unit/distill/test_session_model.py b/tests/unit/distill/test_session_model.py
index c946f940e..20a949b97 100644
--- a/tests/unit/distill/test_session_model.py
+++ b/tests/unit/distill/test_session_model.py
@@ -11,12 +11,12 @@ import json
import os
from pathlib import Path
-from repowise.core.distill.missed import transcript_dir_for
from repowise.core.distill.session_model import (
DEFAULT_MODEL,
normalize_model_id,
resolve_session_model,
)
+from repowise.core.sessions import transcript_dir_for
def _write_claude(projects_root: Path, repo_root: Path, model: str, *, mtime: float) -> Path:
diff --git a/tests/unit/sessions/test_adapter_seam.py b/tests/unit/sessions/test_adapter_seam.py
new file mode 100644
index 000000000..e2e986e6d
--- /dev/null
+++ b/tests/unit/sessions/test_adapter_seam.py
@@ -0,0 +1,294 @@
+"""The harness seam: a second adapter needs no consumer to change.
+
+The toy harness below is deliberately nothing like Claude Code — a pipe
+delimited text format, its own file extension, its own gate tokens, and one
+logical event split across two lines so it needs state that outlives a
+single ``normalize`` call. If it can register, discover, gate and normalize
+through the shared drive paths, the seam is real rather than relocated.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import ClassVar
+
+import pytest
+
+from repowise.core.sessions import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
+ ClaudeCodeAdapter,
+ CursorStore,
+ Event,
+ HarnessAdapter,
+ ToolUse,
+ get_adapter,
+ iter_new_events,
+ register_adapter,
+ registered_adapters,
+)
+from repowise.core.sessions.adapters import registry
+
+
+class ToyAdapter(HarnessAdapter):
+ """A second harness: ``kind|text`` lines, tool calls split across two."""
+
+ name: ClassVar[str] = "toy"
+
+ def __init__(self) -> None:
+ self.files_opened = 0
+ self.files_closed = 0
+ #: Name of a tool announced on a previous line, awaiting its args.
+ self._pending_tool: str | None = None
+
+ def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
+ if projects_root is None or not projects_root.is_dir():
+ return []
+ return sorted(projects_root.glob("*.toy"))
+
+ def prefilter(self, intent: str):
+ if intent == INTENT_TURNS:
+ return lambda raw: raw.startswith(("say|", "call|", "args|"))
+ if intent in (INTENT_SHELL_CALLS, INTENT_TOOL_CALLS):
+ return lambda raw: raw.startswith(("call|", "args|"))
+ return None
+
+ def begin_file(self, path: Path | None = None) -> None:
+ self.files_opened += 1
+ self._pending_tool = None
+
+ def end_file(self) -> None:
+ self.files_closed += 1
+ self._pending_tool = None
+
+ def normalize(self, raw_line: str) -> Event | None:
+ kind, _, rest = raw_line.strip().partition("|")
+ if kind == "say":
+ return Event(kind="user", text=rest)
+ if kind == "call":
+ # Half an event: hold it until the args line arrives.
+ self._pending_tool = rest
+ return None
+ if kind == "args" and self._pending_tool is not None:
+ event = Event(kind="assistant")
+ event.tool_uses.append(ToolUse(id="t1", name=self._pending_tool, input={"raw": rest}))
+ self._pending_tool = None
+ return event
+ return None
+
+
+def toy() -> ToyAdapter:
+ """Register ToyAdapter for one test, then put the registry back."""
+ before = dict(registry._ADAPTERS)
+ register_adapter(ToyAdapter)
+ try:
+ yield ToyAdapter()
+ finally:
+ registry._ADAPTERS.clear()
+ registry._ADAPTERS.update(before)
+
+
+# ---------------------------------------------------------------------------
+# Registry
+# ---------------------------------------------------------------------------
+
+
+def test_default_adapter_is_claude_code_and_is_a_fresh_instance() -> None:
+ first, second = get_adapter(), get_adapter()
+ assert first.name == "claude_code"
+ assert isinstance(first, ClaudeCodeAdapter)
+ # Per call, not a shared singleton: adapters may hold per-file state.
+ assert first is not second
+
+
+def test_registration_adds_exactly_one_name(toy: ToyAdapter) -> None:
+ assert registered_adapters() == ["claude_code", "toy"]
+ assert get_adapter("toy").name == "toy"
+
+
+def test_unknown_harness_is_a_lookup_error() -> None:
+ with pytest.raises(LookupError):
+ get_adapter("no_such_harness")
+
+
+# ---------------------------------------------------------------------------
+# The three drive paths, all reached by a second harness
+# ---------------------------------------------------------------------------
+
+
+def _write_toy(directory: Path, name: str = "s.toy") -> Path:
+ path = directory / name
+ path.write_text(
+ "say|hello\nnoise|ignored\ncall|Bash\nargs|ls -la\n",
+ encoding="utf-8",
+ newline="",
+ )
+ return path
+
+
+def test_discover_then_iter_events(tmp_path: Path, toy: ToyAdapter) -> None:
+ _write_toy(tmp_path)
+ found = get_adapter("toy").discover(tmp_path, projects_root=tmp_path)
+ assert [p.name for p in found] == ["s.toy"]
+
+ events = list(toy.iter_events(found[0], prefilter=toy.prefilter(INTENT_TURNS)))
+ assert [e.kind for e in events] == ["user", "assistant"]
+ assert events[0].text == "hello"
+ # The tool call was assembled from two lines, so cross-line state survived.
+ assert events[1].tool_uses[0].name == "Bash"
+ assert events[1].tool_uses[0].input == {"raw": "ls -la"}
+
+
+def test_cursored_path_drives_a_second_harness(tmp_path: Path, toy: ToyAdapter) -> None:
+ path = _write_toy(tmp_path)
+ store = CursorStore(tmp_path / "cursors.json")
+
+ first = list(iter_new_events(toy, path, store, prefilter=toy.prefilter(INTENT_TOOL_CALLS)))
+ assert [e.tool_uses[0].name for e in first] == ["Bash"]
+
+ with path.open("a", encoding="utf-8", newline="") as fh:
+ fh.write("call|PowerShell\nargs|Get-ChildItem\n")
+ second = list(iter_new_events(toy, path, store, prefilter=toy.prefilter(INTENT_TOOL_CALLS)))
+ assert [e.tool_uses[0].name for e in second] == ["PowerShell"]
+
+
+def test_caller_held_handle_drives_a_second_harness(tmp_path: Path, toy: ToyAdapter) -> None:
+ path = _write_toy(tmp_path)
+ with path.open("rb") as fh:
+ lines = (raw.decode("utf-8", errors="replace") for raw in fh)
+ events = list(toy.events_from_lines(lines, prefilter=toy.prefilter(INTENT_TURNS)))
+ assert [e.kind for e in events] == ["user", "assistant"]
+
+
+# ---------------------------------------------------------------------------
+# Per-file lifecycle
+# ---------------------------------------------------------------------------
+
+
+def test_lifecycle_brackets_every_file(tmp_path: Path, toy: ToyAdapter) -> None:
+ _write_toy(tmp_path, "a.toy")
+ _write_toy(tmp_path, "b.toy")
+ for path in toy.discover(tmp_path, projects_root=tmp_path):
+ list(toy.iter_events(path))
+ assert (toy.files_opened, toy.files_closed) == (2, 2)
+
+
+def test_lifecycle_closes_when_a_consumer_stops_early(tmp_path: Path, toy: ToyAdapter) -> None:
+ path = _write_toy(tmp_path)
+ iterator = toy.iter_events(path, prefilter=toy.prefilter(INTENT_TURNS))
+ assert next(iterator).text == "hello"
+ iterator.close()
+ assert (toy.files_opened, toy.files_closed) == (1, 1)
+
+
+def test_state_does_not_leak_between_files(tmp_path: Path, toy: ToyAdapter) -> None:
+ """A tool call left dangling at EOF must not pair with the next file."""
+ dangling = tmp_path / "a.toy"
+ dangling.write_text("call|Bash\n", encoding="utf-8", newline="")
+ orphan_args = tmp_path / "b.toy"
+ orphan_args.write_text("args|rm -rf /\n", encoding="utf-8", newline="")
+
+ events = [e for p in (dangling, orphan_args) for e in toy.iter_events(p)]
+ assert events == []
+
+
+class TracingAdapter(ToyAdapter):
+ """Records the order of every lifecycle and parse callback."""
+
+ name: ClassVar[str] = "tracing"
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.trace: list[str] = []
+
+ def begin_file(self, path: Path | None = None) -> None:
+ super().begin_file(path)
+ self.trace.append(f"begin:{path.name if path is not None else None}")
+
+ def end_file(self) -> None:
+ super().end_file()
+ self.trace.append("end")
+
+ def normalize(self, raw_line: str) -> Event | None:
+ self.trace.append(f"normalize:{raw_line.strip()}")
+ return super().normalize(raw_line)
+
+
+def test_gate_decides_before_normalize_is_paid_for(tmp_path: Path) -> None:
+ """The performance contract: a gated-out line is never parsed.
+
+ Transcript lines run to hundreds of kilobytes, so the whole layer rests
+ on deciding from the raw string. Normalize-then-discard would leave every
+ other test in this file green while giving all of that back.
+ """
+ adapter = TracingAdapter()
+ path = _write_toy(tmp_path) # 4 lines, of which 1 is a "say|"
+ list(adapter.iter_events(path, prefilter=lambda raw: raw.startswith("say|")))
+
+ parsed = [step for step in adapter.trace if step.startswith("normalize:")]
+ assert parsed == ["normalize:say|hello"]
+
+
+def test_lifecycle_opens_before_the_first_parse_and_closes_after_the_last(
+ tmp_path: Path,
+) -> None:
+ """begin_file must bracket normalize, not merely happen at some point."""
+ adapter = TracingAdapter()
+ path = _write_toy(tmp_path, "session.toy")
+ list(adapter.iter_events(path, prefilter=adapter.prefilter(INTENT_TURNS)))
+
+ assert adapter.trace[0] == "begin:session.toy"
+ assert adapter.trace[-1] == "end"
+ assert all(step.startswith("normalize:") for step in adapter.trace[1:-1])
+
+
+def test_bare_lines_report_no_path(tmp_path: Path) -> None:
+ """A caller that supplies lines rather than a file says so honestly."""
+ adapter = TracingAdapter()
+ list(adapter.events_from_lines(["say|hi\n"]))
+ assert adapter.trace[0] == "begin:None"
+
+
+# ---------------------------------------------------------------------------
+# Intents: the harness's key names live on the adapter, not in a consumer
+# ---------------------------------------------------------------------------
+
+
+ ("intent", "line", "expected"),
+ [
+ # Shell calls: a command tool_use, or Claude Code's result record.
+ (INTENT_SHELL_CALLS, '{"type":"assistant","x":"tool_use","command":"ls"}', True),
+ (INTENT_SHELL_CALLS, '{"toolUseResult":"Error: Exit code 1"}', True),
+ (INTENT_SHELL_CALLS, '{"x":"tool_use","name":"Read"}', False),
+ (INTENT_SHELL_CALLS, '{"type":"user","message":"hi"}', False),
+ # Any tool traffic, shell or not.
+ (INTENT_TOOL_CALLS, '{"x":"tool_use","name":"Read"}', True),
+ (INTENT_TOOL_CALLS, '{"x":"tool_result","id":"1"}', True),
+ (INTENT_TOOL_CALLS, '{"type":"file-history-snapshot"}', False),
+ # Dialog turns, in either JSON spelling.
+ (INTENT_TURNS, '{"type":"user"}', True),
+ (INTENT_TURNS, '{"type": "assistant"}', True),
+ (INTENT_TURNS, '{"type":"file-history-snapshot"}', False),
+ (INTENT_TURNS, '{"type":"queue-operation"}', False),
+ ],
+)
+def test_claude_code_intent_gates(intent: str, line: str, expected: bool) -> None:
+ gate = ClaudeCodeAdapter().prefilter(intent)
+ assert gate is not None
+ assert gate(line) is expected
+
+
+def test_turn_gate_survives_pretty_printed_json() -> None:
+ """The spelling hazard the old two-token-per-kind tuple could not see."""
+ gate = ClaudeCodeAdapter().prefilter(INTENT_TURNS)
+ assert gate(json.dumps({"type": "user"}, indent=2)) is True
+
+
+def test_unknown_intent_gets_no_gate_rather_than_a_wrong_one() -> None:
+ """None means "parse everything", which is slow and correct."""
+ assert ClaudeCodeAdapter().prefilter("no_such_intent") is None
+ assert HarnessAdapter.prefilter(ClaudeCodeAdapter(), INTENT_TURNS) is None