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.

feat(core): shared agent-transcript layer core/sessions (#774)

Raghav Chamadiya02dbf888da3f
diff --git a/packages/core/src/repowise/core/distill/corrections.py b/packages/core/src/repowise/core/distill/corrections.py
index d6def7cf1..838fb481b 100644
--- a/packages/core/src/repowise/core/distill/corrections.py
+++ b/packages/core/src/repowise/core/distill/corrections.py
@@ -22,13 +22,12 @@ report, never an error. Everything stays local.
from __future__ import annotations
-import json
import re
import time
from pathlib import Path
from typing import Any
-from repowise.core.distill.missed import _parse_ts, transcript_dir_for
+from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
#: Default scan window, in days. Corrections are rarer than missed savings,
#: so the default window is wider.
@@ -45,6 +44,8 @@ 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.
@@ -172,69 +173,46 @@ 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]]:
"""Ordered shell events: ``{"command", "failed", "error"}`` per call."""
events: list[dict[str, Any]] = []
pending: dict[str, str] = {}
- with path.open(encoding="utf-8", errors="replace") as fh:
- for raw in fh:
- if '"tool_use"' in raw and '"command"' in raw:
- _collect_tool_use(raw, cutoff, repo_prefix, pending)
- elif pending and '"toolUseResult"' in raw:
- _collect_result(raw, pending, events)
+ 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:
+ _collect_result(event, pending, events)
return events
-def _collect_tool_use(raw: str, cutoff: float, repo_prefix: str, pending: dict[str, str]) -> None:
- try:
- entry = json.loads(raw)
- except ValueError:
- return
- if entry.get("type") != "assistant":
- return
- ts = _parse_ts(entry.get("timestamp"))
- if ts is not None and ts < cutoff:
+def _collect_tool_use(
+ event: Event, cutoff: float, repo_prefix: str, pending: dict[str, str]
+) -> None:
+ if event.ts is not None and event.ts < cutoff:
return
- cwd = str(entry.get("cwd") or "").lower().rstrip("\\/")
+ cwd = (event.cwd or "").lower().rstrip("\\/")
if not cwd.startswith(repo_prefix):
return
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return
- for block in content:
- if not isinstance(block, dict) or block.get("type") != "tool_use":
- continue
- if block.get("name") not in _SHELL_TOOLS:
+ for use in event.tool_uses:
+ if use.name not in _SHELL_TOOLS:
continue
- command = str((block.get("input") or {}).get("command") or "")
+ command = str(use.input.get("command") or "")
if not command:
continue
- block_id = block.get("id")
- if isinstance(block_id, str):
- pending[block_id] = command
+ pending[use.id] = command
-def _collect_result(raw: str, pending: dict[str, str], events: list[dict[str, Any]]) -> None:
- try:
- entry = json.loads(raw)
- except ValueError:
- return
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return
- block_id = next(
- (
- b.get("tool_use_id")
- for b in content
- if isinstance(b, dict) and b.get("type") == "tool_result"
- ),
- None,
- )
- command = pending.pop(block_id, None) if isinstance(block_id, str) else None
+def _collect_result(event: Event, pending: dict[str, str], events: list[dict[str, Any]]) -> None:
+ command = pending.pop(event.tool_results[0].tool_use_id, None)
if command is None:
return
- result = entry.get("toolUseResult")
+ result = event.tool_results[0].payload
if isinstance(result, dict):
# Real success shape: stdout/stderr/interrupted dict.
events.append({"command": command, "failed": False, "error": ""})
diff --git a/packages/core/src/repowise/core/distill/missed.py b/packages/core/src/repowise/core/distill/missed.py
index a774b6e85..d3b10a527 100644
--- a/packages/core/src/repowise/core/distill/missed.py
+++ b/packages/core/src/repowise/core/distill/missed.py
@@ -1,11 +1,11 @@
"""Missed-savings discovery — what did raw agent commands waste?
-Scans Claude Code transcript JSONL (``~/.claude/projects/<munged-cwd>/*.jsonl``)
-for Bash/PowerShell tool calls inside this repo that were **not** routed
-through ``repowise distill``, classifies each command with the same router the
-engine uses, and estimates the tokens a filter would have saved using that
-filter's conservative measured floor (the per-fixture savings floors asserted
-in CI, not the medians).
+Scans Claude Code transcripts (via the shared
+:mod:`repowise.core.sessions` layer) for Bash/PowerShell tool calls inside
+this repo that were **not** routed through ``repowise distill``, classifies
+each command with the same router the engine uses, and estimates the tokens
+a filter would have saved using that filter's conservative measured floor
+(the per-fixture savings floors asserted in CI, not the medians).
Read-only and best-effort by contract: malformed lines, unreadable files, or
an absent transcript directory produce an empty report, never an error — this
@@ -18,15 +18,15 @@ user's own transcript directory on this machine; nothing leaves it.
from __future__ import annotations
-import json
-import re
import time
-from datetime import datetime
from pathlib import Path
from typing import Any
from repowise.core.distill.budget import estimate_tokens
from repowise.core.distill.router import normalize_command, select_filter
+from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
+
+__all__ = ["scan_missed_savings", "transcript_dir_for"]
#: Default scan window, in days.
DEFAULT_WINDOW_DAYS = 7.0
@@ -54,18 +54,7 @@ _MIN_EST_TOKENS = 40
_SHELL_TOOLS = ("Bash", "PowerShell")
-_NON_SLUG_RE = re.compile(r"[^A-Za-z0-9-]")
-
-
-def transcript_dir_for(repo_root: Path, projects_root: Path | None = None) -> Path:
- """The Claude Code transcript directory for sessions started at *repo_root*.
-
- Claude Code munges the session cwd into a directory name by replacing
- every non ``[A-Za-z0-9-]`` character with ``-`` (``C:\\Users\\x\\repo`` →
- ``C--Users-x-repo``).
- """
- root = projects_root if projects_root is not None else Path.home() / ".claude" / "projects"
- return root / _NON_SLUG_RE.sub("-", str(repo_root))
+_ADAPTER = ClaudeCodeAdapter()
def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
@@ -129,72 +118,49 @@ 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]]
) -> None:
#: tool_use id -> command, for shell calls that passed every command gate.
pending: dict[str, str] = {}
- with path.open(encoding="utf-8", errors="replace") as fh:
- for raw in fh:
- # Cheap substring gates before paying for json.loads on huge lines.
- if '"tool_use"' in raw and '"command"' in raw:
- _collect_tool_use(raw, cutoff, repo_prefix, pending)
- elif pending and '"toolUseResult"' in raw:
- _collect_result(raw, pending, per_filter)
+ 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:
+ _collect_result(event, pending, per_filter)
-def _collect_tool_use(raw: str, cutoff: float, repo_prefix: str, pending: dict[str, str]) -> None:
- try:
- entry = json.loads(raw)
- except ValueError:
- return
- if entry.get("type") != "assistant":
- return
- ts = _parse_ts(entry.get("timestamp"))
- if ts is not None and ts < cutoff:
+def _collect_tool_use(
+ event: Event, cutoff: float, repo_prefix: str, pending: dict[str, str]
+) -> None:
+ if event.ts is not None and event.ts < cutoff:
return
- cwd = str(entry.get("cwd") or "").lower().rstrip("\\/")
+ cwd = (event.cwd or "").lower().rstrip("\\/")
if not cwd.startswith(repo_prefix):
return
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return
- for block in content:
- if not isinstance(block, dict) or block.get("type") != "tool_use":
- continue
- if block.get("name") not in _SHELL_TOOLS:
+ for use in event.tool_uses:
+ if use.name not in _SHELL_TOOLS:
continue
- command = str((block.get("input") or {}).get("command") or "")
+ command = str(use.input.get("command") or "")
if not command or normalize_command(command).startswith("repowise"):
continue # already distilled (or another repowise invocation)
- block_id = block.get("id")
- if isinstance(block_id, str):
- pending[block_id] = command
+ pending[use.id] = command
def _collect_result(
- raw: str, pending: dict[str, str], per_filter: dict[str, dict[str, int]]
+ event: Event, pending: dict[str, str], per_filter: dict[str, dict[str, int]]
) -> None:
- try:
- entry = json.loads(raw)
- except ValueError:
- return
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return
- block_id = next(
- (
- b.get("tool_use_id")
- for b in content
- if isinstance(b, dict) and b.get("type") == "tool_result"
- ),
- None,
- )
- command = pending.pop(block_id, None) if isinstance(block_id, str) else None
+ result = event.tool_results[0]
+ command = pending.pop(result.tool_use_id, None)
if command is None:
return
- output = _result_text(entry.get("toolUseResult"))
+ output = _result_text(result.payload)
if not output:
return
chosen = select_filter(command, output)
@@ -221,12 +187,3 @@ def _result_text(result: Any) -> str:
parts = [str(result.get(key) or "") for key in ("stdout", "stderr")]
return "\n".join(p for p in parts if p)
return ""
-
-
-def _parse_ts(value: Any) -> float | None:
- if not isinstance(value, str):
- return None
- try:
- return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
- except ValueError:
- return None
diff --git a/packages/core/src/repowise/core/distill/missed_mcp.py b/packages/core/src/repowise/core/distill/missed_mcp.py
index f2ced44a6..06d660200 100644
--- a/packages/core/src/repowise/core/distill/missed_mcp.py
+++ b/packages/core/src/repowise/core/distill/missed_mcp.py
@@ -7,10 +7,10 @@ session. The first read puts the file in context; a later *full* re-read of
the unchanged file re-bills the whole thing, when a targeted ``get_symbol``
or a line-range read would have returned a fraction.
-It scans the same Claude Code transcript JSONL
-(``~/.claude/projects/<munged-cwd>/*.jsonl``) as the missed-savings scan,
-tracks per-file read and edit order within each session, and credits a
-conservative fraction of each wasteful re-read's tokens as foregone savings.
+It scans the same Claude Code transcripts as the missed-savings scan (via
+the shared :mod:`repowise.core.sessions` layer), tracks per-file read and
+edit order within each session, and credits a conservative fraction of each
+wasteful re-read's tokens as foregone savings.
Read-only and best-effort by the same contract as
:mod:`repowise.core.distill.missed`: malformed lines, unreadable files, or an
@@ -30,14 +30,13 @@ What counts as a wasteful re-read (high precision on purpose):
from __future__ import annotations
-import json
import os.path
import time
from pathlib import Path
from typing import Any
from repowise.core.distill.budget import estimate_tokens
-from repowise.core.distill.missed import _parse_ts, transcript_dir_for
+from repowise.core.sessions import ClaudeCodeAdapter, Event, transcript_dir_for
#: Default scan window, in days. Matches the missed-savings scan.
DEFAULT_WINDOW_DAYS = 7.0
@@ -54,6 +53,8 @@ _MIN_EST_TOKENS = 40
_MUTATING_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
+_ADAPTER = ClaudeCodeAdapter()
+
def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
return {
@@ -122,6 +123,11 @@ 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(
path: Path,
cutoff: float,
@@ -140,16 +146,15 @@ def _scan_file(
last_read_seq: dict[str, int] = {}
last_edit_seq: dict[str, int] = {}
- with path.open(encoding="utf-8", errors="replace") as fh:
- for raw in fh:
- if '"tool_use"' in raw:
- seq = _collect_tool_use(raw, cutoff, repo_prefix, seq, pending, last_edit_seq)
- elif pending and '"tool_result"' in raw:
- _collect_result(raw, pending, last_read_seq, last_edit_seq, repo_root, per_file)
+ 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:
+ _collect_result(event, pending, last_read_seq, last_edit_seq, repo_root, per_file)
def _collect_tool_use(
- raw: str,
+ event: Event,
cutoff: float,
repo_prefix: str,
seq: int,
@@ -157,67 +162,34 @@ def _collect_tool_use(
last_edit_seq: dict[str, int],
) -> int:
"""Record Read tool_use ids (awaiting result) and Edit ordering. Returns seq."""
- try:
- entry = json.loads(raw)
- except ValueError:
+ if event.ts is not None and event.ts < cutoff:
return seq
- if entry.get("type") != "assistant":
- return seq
- ts = _parse_ts(entry.get("timestamp"))
- if ts is not None and ts < cutoff:
- return seq
- cwd = str(entry.get("cwd") or "").lower().rstrip("\\/")
+ cwd = (event.cwd or "").lower().rstrip("\\/")
if not cwd.startswith(repo_prefix):
return seq
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return seq
seq += 1
- for block in content:
- if not isinstance(block, dict) or block.get("type") != "tool_use":
- continue
- name = block.get("name")
- tool_input = block.get("input")
- if not isinstance(tool_input, dict):
- continue
- file_path = tool_input.get("file_path") or tool_input.get("path")
+ for use in event.tool_uses:
+ file_path = use.input.get("file_path") or use.input.get("path")
if not isinstance(file_path, str) or not file_path.strip():
continue
- if name == "Read":
- partial = tool_input.get("offset") is not None or tool_input.get("limit") is not None
- block_id = block.get("id")
- if isinstance(block_id, str):
- pending[block_id] = (file_path, partial, seq)
- elif name in _MUTATING_TOOLS:
+ if use.name == "Read":
+ partial = use.input.get("offset") is not None or use.input.get("limit") is not None
+ pending[use.id] = (file_path, partial, seq)
+ elif use.name in _MUTATING_TOOLS:
last_edit_seq[file_path] = seq
return seq
def _collect_result(
- raw: str,
+ event: Event,
pending: dict[str, tuple[str, bool, int]],
last_read_seq: dict[str, int],
last_edit_seq: dict[str, int],
repo_root: Path,
per_file: dict[str, dict[str, int]],
) -> None:
- try:
- entry = json.loads(raw)
- except ValueError:
- return
- content = (entry.get("message") or {}).get("content")
- if not isinstance(content, list):
- return
- block_id = next(
- (
- b.get("tool_use_id")
- for b in content
- if isinstance(b, dict) and b.get("type") == "tool_result"
- ),
- None,
- )
- record = pending.pop(block_id, None) if isinstance(block_id, str) else None
+ record = pending.pop(event.tool_results[0].tool_use_id, None)
if record is None:
return
file_path, partial, read_seq = record
@@ -235,7 +207,7 @@ def _collect_result(
if not is_waste:
return
- output = _read_output_text(entry.get("toolUseResult"))
+ output = _read_output_text(event.tool_results[0].payload)
if not output:
return
raw_tokens = estimate_tokens(output)
diff --git a/packages/core/src/repowise/core/distill/session_model.py b/packages/core/src/repowise/core/distill/session_model.py
index 0af0a6ea7..47f9f9acd 100644
--- a/packages/core/src/repowise/core/distill/session_model.py
+++ b/packages/core/src/repowise/core/distill/session_model.py
@@ -129,7 +129,7 @@ def _resolve(
def _claude_code_sighting(repo_root: Path, projects_root: Path | None) -> _Sighting | None:
"""Newest Claude Code transcript for *repo_root* that names a model."""
- from repowise.core.distill.missed import transcript_dir_for
+ from repowise.core.sessions import transcript_dir_for
directory = transcript_dir_for(repo_root, projects_root)
if not directory.is_dir():
@@ -238,9 +238,7 @@ def _extract_codex_fields(entry: dict) -> tuple[str | None, str | None]:
model = _first_str(
entry.get("model"), payload.get("model"), turn.get("model"), info.get("model")
)
- cwd = _first_str(
- entry.get("cwd"), payload.get("cwd"), turn.get("cwd"), info.get("cwd")
- )
+ cwd = _first_str(entry.get("cwd"), payload.get("cwd"), turn.get("cwd"), info.get("cwd"))
return model, cwd
diff --git a/packages/core/src/repowise/core/sessions/README.md b/packages/core/src/repowise/core/sessions/README.md
new file mode 100644
index 000000000..e7fe228ed
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/README.md
@@ -0,0 +1,64 @@
+# core/sessions: the shared agent-transcript layer
+
+One normalized event stream over coding-agent session transcripts, so every
+consumer (savings mining, correction mining, session decision mining) reads
+the same `Event` objects instead of parsing harness-specific JSONL itself.
+
+Everything here is read-only and local: transcripts are read from the user's
+own machine and never leave it.
+
+## Layout
+
+| File | What it holds |
+|------|---------------|
+| `events.py` | The `Event` / `ToolUse` / `ToolResult` model, the `INTERRUPT_MARKER` constant, and `iter_deduped_usage` |
+| `adapters/base.py` | The `HarnessAdapter` contract: `discover()` + `normalize()`, with shared `iter_events()` built on top |
+| `adapters/claude_code.py` | First adapter: `~/.claude/projects/<munged-cwd>/*.jsonl` |
+| `cursor.py` | `CursorStore` (byte offset + mtime per file) and `iter_new_events` for incremental scans |
+
+## The contract
+
+An adapter implements exactly two things:
+
+- `discover(repo_root, projects_root=None)`: transcript files for sessions
+ rooted at a repo. Absent directory means empty list, never an error.
+- `normalize(raw_line)`: one raw transcript line to an `Event`, or `None`
+ when the line is unparseable. Never raises on content.
+
+Iteration, prefiltering, and cursoring are shared code. Consumers that only
+care about a slice of the stream pass a `prefilter` callable that gates on
+the raw string before any JSON parsing happens; transcript lines routinely
+run to hundreds of kilobytes, so this is the difference between skimming and
+parsing whole sessions.
+
+## Claude Code schema gotchas (encoded in the adapter and fixtures)
+
+- One API message spans several JSONL lines (one per content block) and each
+ repeats the full `usage` object. Summing raw lines overcounts roughly
+ 2.6x; always go through `iter_deduped_usage`, which keys on `message.id`.
+- `isSidechain` (subagent) lines are kept in the stream and flagged, not
+ dropped. Subagent activity is real activity; filter it out per consumer
+ if you must.
+- `isMeta` and `isCompactSummary` lines are flagged: their text is
+ harness-injected or synthetic, so skip them for prompt-derived signals.
+- A user interrupt is the text marker `[Request interrupted by user`;
+ `Event.interrupted` checks it.
+- A shell tool result's top-level `toolUseResult` is a dict on success and
+ an `Error: Exit code N` string on command failure; it rides on
+ `ToolResult.payload`.
+
+## Cursors
+
+Transcripts are append-only, so a byte offset at a line boundary is a full
+resume point. `iter_new_events(adapter, path, store)` seeks to the stored
+offset, yields only appended events, and advances the in-memory cursor per
+consumed line; the caller batches one `store.save()` per scan. A truncated
+or replaced file restarts from zero; a trailing line without a newline is a
+write in progress and waits for the next pass.
+
+## Adding a harness
+
+Subclass `HarnessAdapter` in `adapters/<name>.py`, populate whatever fields
+the harness records (leave the rest at defaults), and add a real-shaped
+JSONL fixture under `tests/unit/sessions/data/`. Consumers written against
+`Event` need no changes.
diff --git a/packages/core/src/repowise/core/sessions/__init__.py b/packages/core/src/repowise/core/sessions/__init__.py
new file mode 100644
index 000000000..d7ef78f3e
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/__init__.py
@@ -0,0 +1,43 @@
+"""Shared agent-session transcript layer.
+
+One normalized :class:`Event` stream over coding-agent transcripts, behind a
+:class:`HarnessAdapter` interface so consumers never parse harness-specific
+JSONL themselves. Claude Code is the first adapter; Codex and others slot in
+behind the same interface later.
+
+Consumers today are the distill transcript miners (missed savings, wasteful
+re-reads, correction mining). Session decision mining rides the same stream
+next.
+
+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 (
+ ClaudeCodeAdapter,
+ parse_timestamp,
+ transcript_dir_for,
+)
+from repowise.core.sessions.cursor import CursorStore, iter_new_events
+from repowise.core.sessions.events import (
+ INTERRUPT_MARKER,
+ Event,
+ ToolResult,
+ ToolUse,
+ iter_deduped_usage,
+)
+
+__all__ = [
+ "INTERRUPT_MARKER",
+ "ClaudeCodeAdapter",
+ "CursorStore",
+ "Event",
+ "HarnessAdapter",
+ "ToolResult",
+ "ToolUse",
+ "iter_deduped_usage",
+ "iter_new_events",
+ "parse_timestamp",
+ "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
new file mode 100644
index 000000000..7cc93289e
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/adapters/__init__.py
@@ -0,0 +1,6 @@
+"""Harness adapters: one per coding agent whose transcripts we can read."""
+
+from repowise.core.sessions.adapters.base import HarnessAdapter
+from repowise.core.sessions.adapters.claude_code import ClaudeCodeAdapter
+
+__all__ = ["ClaudeCodeAdapter", "HarnessAdapter"]
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
new file mode 100644
index 000000000..6f644e788
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -0,0 +1,61 @@
+"""The adapter contract every harness implements.
+
+An adapter knows two things about its agent: where transcripts for a given
+repo live (:meth:`HarnessAdapter.discover`) and how one raw transcript line
+becomes a normalized :class:`~repowise.core.sessions.events.Event`
+(:meth:`HarnessAdapter.normalize`). Iteration, cursoring, and mining are
+shared code built on those two primitives.
+
+Best-effort contract, matching the distill miners this layer was extracted
+from: ``normalize`` returns None for anything it cannot parse rather than
+raising; filesystem errors from :meth:`iter_events` propagate so callers can
+apply their own skip policy per file.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from typing import ClassVar
+
+from repowise.core.sessions.events import Event
+
+#: Cheap gate on the raw line, applied before paying for JSON parsing.
+#: Transcript lines routinely run to hundreds of kilobytes; a substring
+#: check on the raw string is orders of magnitude cheaper than json.loads,
+#: so consumers that only want tool events pass one of these.
+RawPrefilter = Callable[[str], bool]
+
+
+class HarnessAdapter(ABC):
+ """Reads one agent's transcripts into the shared Event stream."""
+
+ #: Stable identifier, e.g. ``"claude_code"``.
+ name: ClassVar[str]
+
+ @abstractmethod
+ def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
+ """Transcript files for sessions rooted at *repo_root*, sorted.
+
+ *projects_root* overrides the harness's real transcript root (for
+ tests). An absent directory yields an empty list, never an error.
+ """
+
+ @abstractmethod
+ 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.
+
+ 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:
+ for raw in fh:
+ if prefilter is not None and not prefilter(raw):
+ continue
+ event = self.normalize(raw)
+ if event is not None:
+ yield event
diff --git a/packages/core/src/repowise/core/sessions/adapters/claude_code.py b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
new file mode 100644
index 000000000..4eb5a3f85
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
@@ -0,0 +1,143 @@
+"""Claude Code transcript adapter.
+
+Claude Code writes one JSONL file per session under
+``~/.claude/projects/<munged-cwd>/``, where the munged name replaces every
+non ``[A-Za-z0-9-]`` character of the session cwd with ``-``. Each line is
+one entry; the shapes this adapter understands (verified against real
+transcripts on this machine, 2026-07):
+
+- ``assistant`` entries: top-level ``cwd``/``timestamp``/``sessionId``/
+ ``isSidechain``; ``message`` carries ``id``, ``model``, ``usage`` and a
+ ``content[]`` list with ``text`` and ``tool_use`` blocks.
+- ``user`` entries: plain prompts (string or text-block content, sometimes
+ ``isMeta`` or ``isCompactSummary``) or tool results (``content[]`` with
+ ``tool_result`` blocks plus a top-level ``toolUseResult`` whose
+ string-vs-dict shape distinguishes command failures from successes).
+- Other types (``system``, ``file-history-snapshot``, ``queue-operation``,
+ ...) normalize with their type passed through so consumers can ignore
+ them by kind.
+"""
+
+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
+
+_NON_SLUG_RE = re.compile(r"[^A-Za-z0-9-]")
+
+
+def transcript_dir_for(repo_root: Path, projects_root: Path | None = None) -> Path:
+ """The Claude Code transcript directory for sessions started at *repo_root*.
+
+ ``C:\\Users\\x\\repo`` munges to ``C--Users-x-repo``.
+ """
+ root = projects_root if projects_root is not None else Path.home() / ".claude" / "projects"
+ 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
+
+
+class ClaudeCodeAdapter(HarnessAdapter):
+ """Normalizes Claude Code session JSONL into the shared Event stream."""
+
+ name: ClassVar[str] = "claude_code"
+
+ def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
+ directory = transcript_dir_for(repo_root, projects_root)
+ if not directory.is_dir():
+ return []
+ return sorted(directory.glob("*.jsonl"))
+
+ def normalize(self, raw_line: str) -> Event | None:
+ try:
+ entry = json.loads(raw_line)
+ except ValueError:
+ return None
+ if not isinstance(entry, dict):
+ return None
+
+ kind = entry.get("type")
+ if not isinstance(kind, str) or not kind:
+ return None
+ message = entry.get("message") if isinstance(entry.get("message"), dict) else {}
+ usage = message.get("usage")
+
+ event = Event(
+ kind=kind,
+ ts=parse_timestamp(entry.get("timestamp")),
+ session_id=_str_or_none(entry.get("sessionId")),
+ cwd=_str_or_none(entry.get("cwd")),
+ usage=usage if isinstance(usage, dict) else None,
+ message_id=_str_or_none(message.get("id")),
+ model=_str_or_none(message.get("model")),
+ sidechain=bool(entry.get("isSidechain")),
+ is_meta=bool(entry.get("isMeta")),
+ is_compact_summary=bool(entry.get("isCompactSummary")),
+ )
+
+ content = message.get("content")
+ if isinstance(content, str):
+ event.text = content
+ elif isinstance(content, list):
+ self._fill_blocks(event, content, entry.get("toolUseResult"))
+ return event
+
+ @staticmethod
+ def _fill_blocks(event: Event, content: list[Any], tool_use_result: Any) -> None:
+ """Populate text and tool blocks from a message ``content[]`` list.
+
+ The top-level ``toolUseResult`` record belongs to the entry, not a
+ block; real transcripts carry exactly one ``tool_result`` block per
+ entry, so it is attached to every result block seen.
+ """
+ texts: list[str] = []
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+ if block_type == "text":
+ text = block.get("text")
+ if isinstance(text, str) and text:
+ texts.append(text)
+ elif block_type == "tool_use":
+ block_id = block.get("id")
+ name = block.get("name")
+ if isinstance(block_id, str) and isinstance(name, str):
+ tool_input = block.get("input")
+ event.tool_uses.append(
+ ToolUse(
+ id=block_id,
+ name=name,
+ input=tool_input if isinstance(tool_input, dict) else {},
+ )
+ )
+ elif block_type == "tool_result":
+ use_id = block.get("tool_use_id")
+ if isinstance(use_id, str):
+ event.tool_results.append(
+ ToolResult(
+ tool_use_id=use_id,
+ is_error=bool(block.get("is_error")),
+ content=block.get("content"),
+ payload=tool_use_result,
+ )
+ )
+ event.text = "\n".join(texts)
+
+
+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/cursor.py b/packages/core/src/repowise/core/sessions/cursor.py
new file mode 100644
index 000000000..a9d822b3e
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/cursor.py
@@ -0,0 +1,101 @@
+"""Incremental transcript cursors: never re-read what was already mined.
+
+Transcripts are append-only JSONL, so a byte offset at a line boundary is a
+complete resume point. :class:`CursorStore` keeps one ``{offset, mtime}``
+record per transcript file in a small JSON sidecar;
+:func:`iter_new_events` seeks to the stored offset and yields only events
+from lines appended since, advancing the cursor as each complete line is
+consumed (a partially consumed iterator leaves the cursor at the last line
+it actually delivered).
+
+Safety rules:
+- a file shorter than its stored offset was truncated or replaced: restart
+ from zero;
+- a trailing line without a newline is a write in progress: leave it for
+ the next pass;
+- an unreadable or corrupt sidecar degrades to an empty store, never an
+ error.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+from repowise.core.sessions.adapters.base import HarnessAdapter, RawPrefilter
+from repowise.core.sessions.events import Event
+
+
+class CursorStore:
+ """Per-file resume offsets, persisted as one JSON sidecar.
+
+ Load happens on construction, mutation is in memory, and nothing hits
+ disk until :meth:`save`; callers batch one save per scan.
+ """
+
+ def __init__(self, path: Path) -> None:
+ self.path = path
+ self._cursors: dict[str, dict[str, Any]] = self._load()
+
+ def _load(self) -> dict[str, dict[str, Any]]:
+ try:
+ data = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+ if not isinstance(data, dict):
+ return {}
+ return {
+ key: value
+ for key, value in data.items()
+ if isinstance(value, dict) and isinstance(value.get("offset"), int)
+ }
+
+ def get(self, file: Path) -> dict[str, Any] | None:
+ return self._cursors.get(str(file))
+
+ def advance(self, file: Path, *, offset: int, mtime: float) -> None:
+ self._cursors[str(file)] = {"offset": offset, "mtime": mtime}
+
+ def save(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.write_text(json.dumps(self._cursors, indent=0, sort_keys=True), encoding="utf-8")
+
+
+def iter_new_events(
+ adapter: HarnessAdapter,
+ path: Path,
+ store: CursorStore,
+ *,
+ prefilter: RawPrefilter | None = None,
+) -> Iterator[Event]:
+ """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`.
+ """
+ stat = path.stat()
+ cursor = store.get(path)
+ start = 0
+ if cursor is not None and 0 <= cursor["offset"] <= stat.st_size:
+ start = cursor["offset"]
+ 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
diff --git a/packages/core/src/repowise/core/sessions/events.py b/packages/core/src/repowise/core/sessions/events.py
new file mode 100644
index 000000000..2f53d1300
--- /dev/null
+++ b/packages/core/src/repowise/core/sessions/events.py
@@ -0,0 +1,101 @@
+"""The normalized transcript event model, harness-agnostic by design.
+
+An :class:`Event` is one transcript line reduced to the fields miners care
+about: who spoke, when, from where, what tools ran and what came back. The
+shape is deliberately flat and tolerant; adapters populate whatever their
+harness records and leave the rest at defaults, so a consumer written against
+Events never needs to know which agent produced the transcript.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass, field
+from typing import Any
+
+#: Claude Code injects this text into the conversation when the user
+#: interrupts a running turn; it is the strongest pushback signal a
+#: transcript carries.
+INTERRUPT_MARKER = "[Request interrupted by user"
+
+
+@dataclass(slots=True)
+class ToolUse:
+ """One tool invocation block inside an assistant event."""
+
+ id: str
+ name: str
+ input: dict[str, Any]
+
+
+@dataclass(slots=True)
+class ToolResult:
+ """One tool result block, paired to its invocation by ``tool_use_id``.
+
+ ``content`` is the message-level result block content (what the model
+ read back); ``payload`` is the harness-level result record when the
+ transcript carries one (Claude Code's top-level ``toolUseResult``, whose
+ string-vs-dict shape distinguishes command failures from successes).
+ """
+
+ tool_use_id: str
+ is_error: bool = False
+ content: Any = None
+ payload: Any = None
+
+
+@dataclass(slots=True)
+class Event:
+ """One normalized transcript line.
+
+ ``kind`` is the harness's own entry type ("user", "assistant", "system",
+ ...) passed through verbatim; consumers gate on the kinds they know.
+ Timestamps are epoch seconds or None when the line carries none.
+ """
+
+ kind: str
+ ts: float | None = None
+ session_id: str | None = None
+ cwd: str | None = None
+ text: str = ""
+ tool_uses: list[ToolUse] = field(default_factory=list)
+ tool_results: list[ToolResult] = field(default_factory=list)
+ #: Model-reported token usage for this line, verbatim. The same usage
+ #: object repeats on every content-block line of one API message; sum
+ #: via :func:`iter_deduped_usage`, never directly.
+ usage: dict[str, Any] | None = None
+ #: The API message id (``message.id``), the usage dedup key.
+ message_id: str | None = None
+ #: Model that produced an assistant line (``message.model``).
+ model: str | None = None
+ #: True for subagent (sidechain) lines. Kept in the stream on purpose:
+ #: subagent activity is real activity; consumers that only want the
+ #: main thread filter it out themselves.
+ sidechain: bool = False
+ #: Harness-injected line, not something the user typed.
+ is_meta: bool = False
+ #: Post-compaction summary line; text is synthetic, skip for
+ #: prompt-derived signals.
+ is_compact_summary: bool = False
+
+ @property
+ def interrupted(self) -> bool:
+ """True when this line records a user interrupt."""
+ return INTERRUPT_MARKER in self.text
+
+
+def iter_deduped_usage(events: Iterable[Event]) -> Iterator[Event]:
+ """Events whose usage should be counted, one per API message.
+
+ One API message spans several transcript lines (one per content block)
+ and each repeats the full usage object; summing raw lines overcounts by
+ roughly 2.6x. Yields only the first usage-bearing event per message id.
+ """
+ seen: set[str] = set()
+ for event in events:
+ if event.usage is None or event.message_id is None:
+ continue
+ if event.message_id in seen:
+ continue
+ seen.add(event.message_id)
+ yield event
diff --git a/tests/unit/sessions/data/claude_code_session.jsonl b/tests/unit/sessions/data/claude_code_session.jsonl
new file mode 100644
index 000000000..8b3b4953c
--- /dev/null
+++ b/tests/unit/sessions/data/claude_code_session.jsonl
@@ -0,0 +1,13 @@
+{"type":"assistant","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:00.000Z","sessionId":"sess-1","isSidechain":false,"message":{"id":"msg_01","model":"claude-fable-5","role":"assistant","content":[{"type":"text","text":"Running the tests now."}],"usage":{"input_tokens":100,"output_tokens":20}}}
+{"type":"assistant","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:01.000Z","sessionId":"sess-1","isSidechain":false,"message":{"id":"msg_01","model":"claude-fable-5","role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"command":"pytest -q"}}],"usage":{"input_tokens":100,"output_tokens":20}}}
+{"type":"user","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:05.000Z","sessionId":"sess-1","isSidechain":false,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"3 passed"}]},"toolUseResult":{"stdout":"3 passed","stderr":""}}
+{"type":"assistant","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:06.000Z","sessionId":"sess-1","isSidechain":false,"message":{"id":"msg_02","model":"claude-fable-5","role":"assistant","content":[{"type":"tool_use","id":"toolu_02","name":"Bash","input":{"command":"pytest bad/path"}}],"usage":{"input_tokens":150,"output_tokens":10}}}
+{"type":"user","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:08.000Z","sessionId":"sess-1","isSidechain":false,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_02","is_error":true,"content":"Error: Exit code 4"}]},"toolUseResult":"Error: Exit code 4\nERROR: file or directory not found: bad/path"}
+{"type":"assistant","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:09.000Z","sessionId":"sess-1","isSidechain":true,"message":{"id":"msg_03","model":"claude-fable-5","role":"assistant","content":[{"type":"text","text":"Subagent reporting back."}],"usage":{"input_tokens":50,"output_tokens":5}}}
+{"type":"user","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:10.000Z","sessionId":"sess-1","isSidechain":false,"isMeta":true,"message":{"role":"user","content":"<system-reminder>injected by the harness</system-reminder>"}}
+{"type":"user","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:11.000Z","sessionId":"sess-1","isSidechain":false,"isCompactSummary":true,"message":{"role":"user","content":"This session is being continued from a previous conversation."}}
+{"type":"user","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:12.000Z","sessionId":"sess-1","isSidechain":false,"message":{"role":"user","content":[{"type":"text","text":"[Request interrupted by user for tool use]"},{"type":"text","text":"no, use approach B instead"}]}}
+{"type":"system","cwd":"C:\\Users\\x\\repo","timestamp":"2026-07-11T10:00:13.000Z","sessionId":"sess-1","subtype":"info","content":"hook output","isMeta":true}
+{"type":"file-history-snapshot","messageId":"msg_02","snapshot":{}}
+this line is not json at all
+[1, 2, 3]
diff --git a/tests/unit/sessions/test_claude_code_adapter.py b/tests/unit/sessions/test_claude_code_adapter.py
new file mode 100644
index 000000000..770e20e25
--- /dev/null
+++ b/tests/unit/sessions/test_claude_code_adapter.py
@@ -0,0 +1,147 @@
+"""Claude Code adapter — discovery, normalization, and the schema gotchas.
+
+The checked-in fixture (``data/claude_code_session.jsonl``) mirrors real
+transcript shapes captured on this machine: split usage blocks sharing one
+``message.id``, sidechain and meta/compact-summary lines, dict and
+error-string ``toolUseResult`` payloads, an interrupt marker, and malformed
+lines.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.sessions import (
+ ClaudeCodeAdapter,
+ Event,
+ iter_deduped_usage,
+ parse_timestamp,
+ transcript_dir_for,
+)
+
+FIXTURE = Path(__file__).parent / "data" / "claude_code_session.jsonl"
+
+ADAPTER = ClaudeCodeAdapter()
+
+
+def events() -> list[Event]:
+ return list(ADAPTER.iter_events(FIXTURE))
+
+
+def test_transcript_dir_munging() -> None:
+ assert (
+ transcript_dir_for(Path(r"C:\Users\x\Desktop\repo"), Path("/p")).name
+ == "C--Users-x-Desktop-repo"
+ )
+
+
+def test_discover_lists_jsonl_sorted(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ transcripts = transcript_dir_for(repo, tmp_path / "projects")
+ transcripts.mkdir(parents=True)
+ (transcripts / "b.jsonl").write_text("", encoding="utf-8")
+ (transcripts / "a.jsonl").write_text("", encoding="utf-8")
+ (transcripts / "notes.txt").write_text("", encoding="utf-8")
+ found = ADAPTER.discover(repo, projects_root=tmp_path / "projects")
+ assert [p.name for p in found] == ["a.jsonl", "b.jsonl"]
+
+
+def test_discover_absent_dir_is_empty(tmp_path: Path) -> None:
+ assert ADAPTER.discover(tmp_path / "repo", projects_root=tmp_path / "nowhere") == []
+
+
+def test_malformed_lines_normalize_to_none(events: list[Event]) -> None:
+ # 13 fixture lines: 11 valid entries, one non-JSON line, one non-dict line.
+ assert len(events) == 11
+ assert ADAPTER.normalize("not json at all") is None
+ assert ADAPTER.normalize("[1, 2, 3]") is None
+ assert ADAPTER.normalize('{"no_type_field": true}') is None
+
+
+def test_common_fields(events: list[Event]) -> None:
+ first = events[0]
+ assert first.kind == "assistant"
+ assert first.session_id == "sess-1"
+ assert first.cwd == r"C:\Users\x\repo"
+ assert first.model == "claude-fable-5"
+ assert first.message_id == "msg_01"
+ assert first.text == "Running the tests now."
+ assert first.ts == parse_timestamp("2026-07-11T10:00:00.000Z")
+
+
+def test_tool_use_blocks(events: list[Event]) -> None:
+ use = events[1].tool_uses[0]
+ assert (use.id, use.name) == ("toolu_01", "Bash")
+ assert use.input == {"command": "pytest -q"}
+
+
+def test_tool_result_success_and_error_payloads(events: list[Event]) -> None:
+ ok = events[2].tool_results[0]
+ assert ok.tool_use_id == "toolu_01"
+ assert ok.is_error is False
+ assert ok.content == "3 passed"
+ assert ok.payload == {"stdout": "3 passed", "stderr": ""}
+
+ failed = events[4].tool_results[0]
+ assert failed.tool_use_id == "toolu_02"
+ assert failed.is_error is True
+ assert isinstance(failed.payload, str)
+ assert failed.payload.startswith("Error: Exit code 4")
+
+
+def test_sidechain_events_are_kept_and_flagged(events: list[Event]) -> None:
+ sidechain = events[5]
+ assert sidechain.sidechain is True
+ assert sidechain.text == "Subagent reporting back."
+ assert all(not e.sidechain for e in events if e is not sidechain)
+
+
+def test_meta_and_compact_summary_flags(events: list[Event]) -> None:
+ meta = events[6]
+ assert meta.is_meta is True
+ assert "system-reminder" in meta.text # string content passes through
+ compact = events[7]
+ assert compact.is_compact_summary is True
+
+
+def test_interrupt_marker(events: list[Event]) -> None:
+ interrupted = events[8]
+ assert interrupted.interrupted is True
+ assert "use approach B instead" in interrupted.text
+ assert not events[0].interrupted
+
+
+def test_other_entry_types_pass_kind_through(events: list[Event]) -> None:
+ assert events[9].kind == "system"
+ assert events[10].kind == "file-history-snapshot"
+
+
+def test_usage_dedup_by_message_id(events: list[Event]) -> None:
+ # msg_01 spans two lines (text block, then tool_use block) with the same
+ # usage object; counting both would double-bill the message.
+ counted = list(iter_deduped_usage(events))
+ assert [e.message_id for e in counted] == ["msg_01", "msg_02", "msg_03"]
+ assert sum(e.usage["input_tokens"] for e in counted) == 300
+
+
+def test_prefilter_skips_lines_without_parsing(tmp_path: Path) -> None:
+ path = tmp_path / "s.jsonl"
+ lines = [
+ json.dumps({"type": "assistant", "message": {"content": "plain text"}}),
+ json.dumps(
+ {
+ "type": "assistant",
+ "message": {
+ "content": [{"type": "tool_use", "id": "t1", "name": "Bash", "input": {}}]
+ },
+ }
+ ),
+ ]
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ got = list(ADAPTER.iter_events(path, prefilter=lambda raw: '"tool_use"' in raw))
+ assert len(got) == 1
+ assert got[0].tool_uses[0].id == "t1"
diff --git a/tests/unit/sessions/test_cursor.py b/tests/unit/sessions/test_cursor.py
new file mode 100644
index 000000000..c860791bf
--- /dev/null
+++ b/tests/unit/sessions/test_cursor.py
@@ -0,0 +1,101 @@
+"""Cursor semantics — resume at a byte offset, never re-yield, never lose."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.sessions import ClaudeCodeAdapter, CursorStore, iter_new_events
+
+ADAPTER = ClaudeCodeAdapter()
+
+
+def _line(text: str) -> str:
+ return json.dumps({"type": "user", "message": {"content": text}}) + "\n"
+
+
+def _write(path: Path, content: str) -> None:
+ path.write_text(content, encoding="utf-8", newline="")
+
+
+def test_first_pass_yields_all_and_resume_yields_only_new(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ store = CursorStore(tmp_path / "cursors.json")
+ _write(transcript, _line("one") + _line("two"))
+
+ first = [e.text for e in iter_new_events(ADAPTER, transcript, store)]
+ assert first == ["one", "two"]
+
+ with transcript.open("a", encoding="utf-8", newline="") as fh:
+ fh.write(_line("three"))
+ second = [e.text for e in iter_new_events(ADAPTER, transcript, store)]
+ assert second == ["three"]
+
+ assert list(iter_new_events(ADAPTER, transcript, store)) == []
+
+
+def test_partial_trailing_line_waits_for_completion(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ store = CursorStore(tmp_path / "cursors.json")
+ complete = _line("done")
+ partial = _line("in progress").rstrip("\n")
+ _write(transcript, complete + partial)
+
+ assert [e.text for e in iter_new_events(ADAPTER, transcript, store)] == ["done"]
+
+ with transcript.open("a", encoding="utf-8", newline="") as fh:
+ fh.write("\n")
+ assert [e.text for e in iter_new_events(ADAPTER, transcript, store)] == ["in progress"]
+
+
+def test_truncated_file_restarts_from_zero(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ store = CursorStore(tmp_path / "cursors.json")
+ _write(transcript, _line("old one") + _line("old two"))
+ assert len(list(iter_new_events(ADAPTER, transcript, store))) == 2
+
+ _write(transcript, _line("fresh")) # shorter than the stored offset
+ assert [e.text for e in iter_new_events(ADAPTER, transcript, store)] == ["fresh"]
+
+
+def test_partial_consumption_leaves_cursor_at_last_delivered_line(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ store = CursorStore(tmp_path / "cursors.json")
+ _write(transcript, _line("one") + _line("two") + _line("three"))
+
+ iterator = iter_new_events(ADAPTER, transcript, store)
+ assert next(iterator).text == "one"
+ iterator.close()
+
+ rest = [e.text for e in iter_new_events(ADAPTER, transcript, store)]
+ assert rest == ["two", "three"]
+
+
+def test_store_roundtrip_and_corrupt_sidecar(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ sidecar = tmp_path / "cursors.json"
+ _write(transcript, _line("one"))
+
+ store = CursorStore(sidecar)
+ list(iter_new_events(ADAPTER, transcript, store))
+ store.save()
+
+ reloaded = CursorStore(sidecar)
+ assert list(iter_new_events(ADAPTER, transcript, reloaded)) == []
+
+ sidecar.write_text("{ corrupt", encoding="utf-8")
+ fresh = CursorStore(sidecar)
+ assert [e.text for e in iter_new_events(ADAPTER, transcript, fresh)] == ["one"]
+
+
+def test_prefilter_skips_but_still_advances(tmp_path: Path) -> None:
+ transcript = tmp_path / "s.jsonl"
+ store = CursorStore(tmp_path / "cursors.json")
+ _write(transcript, _line("skip me") + _line("keep me"))
+
+ got = [
+ e.text for e in iter_new_events(ADAPTER, transcript, store, prefilter=lambda r: "keep" in r)
+ ]
+ assert got == ["keep me"]
+ # Skipped lines are consumed, not deferred: nothing on the next pass.
+ assert list(iter_new_events(ADAPTER, transcript, store)) == []