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(attribution): backfill past commits from local agent transcripts (#3792)

Raghav Chamadiyae917a9adaf73
diff --git a/docs/layers/ATTRIBUTION.md b/docs/layers/ATTRIBUTION.md
index a8b4112fe..29581a96d 100644
--- a/docs/layers/ATTRIBUTION.md
+++ b/docs/layers/ATTRIBUTION.md
@@ -57,6 +57,14 @@ the model in `.repowise/attribution/events.jsonl`, never prompts or code. `repow
post-commit hook runs) matches those hashes to the lines new commits added and labels a
matched commit with the agent. An unmatched commit stays `unknown`.
+### Backfill from transcripts
+
+`repowise attribution backfill --agent claude-code,codex` binds past commits from the
+transcripts these agents keep on this machine, under the same consent. It keeps line
+hashes only, binds an edit to a commit made within 14 days after it, and needs a run of 6
+substantive lines. When it binds new commits, the next `repowise update` re-reads git
+history once to label them.
+
### `local` and `notes`: what leaves the machine
| Level | Writes | Leaves the machine |
@@ -94,6 +102,7 @@ Key reference: [CONFIG.md](../reference/CONFIG.md#the-attribution-block).
| Command | What it does |
|---|---|
| `repowise attribution status [--format json]` | Effective, repo and user values, why any differ, capture per agent, sidecar counts, and commits by label with coverage |
+| `repowise attribution backfill --agent claude-code,codex [--format json]` | Binds past commits from local transcripts; prints commits scanned, bound and coverage before and after |
| `repowise attribution purge [--yes]` | Deletes the index labels and file rollups, the `.repowise/attribution/` sidecar and the notes Repowise wrote locally. Git history, trailers and notes written by anything else stay |
| `repowise doctor` | At `capture: notes`, checks the fetch refspec, the push refspec and `notes.rewriteRef`, and names the command for anything missing |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index b05fb874a..7f6e33c49 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2251,10 +2251,13 @@ does not know or list the commands. See [pluggable storage and capability seams]
Inspect and clear AI attribution for a repository.
```bash
-repowise attribution status [PATH] [--format json] # what is on, capture per agent, coverage
+repowise attribution status [PATH] [--format json] # what is on, capture per agent, coverage, last backfill
+repowise attribution backfill [PATH] --agent claude-code,codex [--format json] # bind past commits from local transcripts
repowise attribution purge [PATH] [--yes] # delete derived attribution, captured edits and our notes
```
+`backfill` reads the Claude Code and Codex transcripts on this machine, keeps only line hashes of edits to this repository (worktrees included), and binds them to commits made within 14 days after each edit. It runs only when you ask, for agents that `capture` and `agents` allow in both configs, and prints the commits scanned, bound, and their coverage before and after; when it binds new commits in an indexed repo, the next `repowise update` re-reads git history once to label these commits. The first run reads every transcript these agents keep (about 4 minutes for 7 GB on a laptop); a later run reads only what they wrote since.
+
`purge` deletes the index labels, the `.repowise/attribution/` sidecar and the git-ai notes Repowise wrote locally. Git history, trailers and notes written by anything else stay as they are.
Settings live in the `attribution:` block of [CONFIG.md](CONFIG.md#the-attribution-block).
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index f580e9788..3f3d81450 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -639,7 +639,7 @@ attribution:
The same block in `~/.repowise/config.yaml` applies to every repository, and the stricter value wins per key: `enabled: false` in either file, the lower capture level, and the agents both files list. With `enabled: false` nothing about AI is stored or shown in the API, CLI, MCP, web or wiki, and `DO_NOT_TRACK=1` keeps capture off. `repowise attribution status` shows the effective, repo and user values with the coverage of the indexed history.
-`capture: local` records the listed agents' edits as line hashes in `.repowise/attribution/`; `capture: notes` also writes git-ai notes on `refs/notes/ai`. What each level stores, and what leaves the machine, is in [ATTRIBUTION.md](../layers/ATTRIBUTION.md).
+`capture: local` records the listed agents' edits as line hashes in `.repowise/attribution/`; `capture: notes` also writes git-ai notes on `refs/notes/ai`. What each level stores, and what leaves the machine, is in [ATTRIBUTION.md](../layers/ATTRIBUTION.md). The same consent lets `repowise attribution backfill --agent claude-code,codex` bind past commits from the transcripts these agents keep on this machine.
### The `refactoring:` block
diff --git a/packages/cli/src/repowise/cli/commands/attribution_cmd.py b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
index 0157e382c..de7999efc 100644
--- a/packages/cli/src/repowise/cli/commands/attribution_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
@@ -2,9 +2,11 @@
``status`` shows what is switched on (effective value beside the repo and user
values), for which agents, and how much of the indexed history has a known
-source, plus edit capture per agent. ``purge`` deletes the attribution the
-local index derived, the capture sidecar (events, bindings, cursor) and the
-git-ai notes Repowise itself wrote; notes from anyone else are never touched.
+source, plus edit capture per agent and the last backfill. ``backfill`` binds
+past commits from the agent transcripts on this machine, only when asked.
+``purge`` deletes the attribution the local index derived, the capture sidecar
+(events, bindings, cursors) and the git-ai notes Repowise itself wrote; notes
+from anyone else are never touched.
"""
from __future__ import annotations
@@ -142,11 +144,13 @@ def attribution_status(path: str | None, fmt: str) -> None:
capture = _capture_by_agent(settings)
sidecar = capture_summary(repo_path)
+ backfill = _last_backfill(repo_path)
if fmt == "json":
emit_json(
{
"capture_by_agent": capture,
"capture_sidecar": sidecar,
+ "backfill": backfill,
"effective": {
"enabled": settings.enabled,
"capture": settings.capture,
@@ -167,6 +171,8 @@ def attribution_status(path: str | None, fmt: str) -> None:
console.print("[bold]AI attribution[/bold]")
_print_settings(settings)
_print_capture(capture, sidecar)
+ if backfill:
+ console.print(f" backfill {_backfill_line(backfill)}")
_print_commits(settings, counts, share)
@@ -221,6 +227,158 @@ def _print_commits(settings: Any, counts: dict[str, int] | None, share: Any) ->
console.print(f" share {share.summary()}")
+def _request_history_rewalk(repo_path: Path) -> bool:
+ """Make the next ``repowise update`` re-read git history once, which labels
+ the newly bound commits in the index; False when there is no index.
+
+ Drops the git-history stamp in ``.repowise/state.json``, the same signal a
+ history-rules change raises. No update flag re-walks git history alone.
+ """
+ import json
+
+ from repowise.core.fsutils import atomic_write_text
+ from repowise.core.ingestion.git_indexer import GIT_HISTORY_VERSION_KEY
+
+ state_path = repo_path / ".repowise" / "state.json"
+ try:
+ state = json.loads(state_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ if not isinstance(state, dict):
+ return False
+ state.pop(GIT_HISTORY_VERSION_KEY, None)
+ atomic_write_text(state_path, json.dumps(state, indent=2))
+ return True
+
+
+def _last_backfill(repo_path: Path) -> dict[str, Any] | None:
+ from repowise.core.edit_capture.store import load_state
+
+ last = load_state(repo_path).get("backfill")
+ return last if isinstance(last, dict) else None
+
+
+def _pct(part: int, whole: int) -> str:
+ return f"{round(100 * part / whole)}%" if whole else "n/a"
+
+
+def _backfill_line(last: dict[str, Any]) -> str:
+ from datetime import datetime
+
+ commits = int(last.get("commits") or 0)
+ before, after = int(last.get("covered_before") or 0), int(last.get("covered_after") or 0)
+ when = datetime.fromtimestamp(float(last.get("at") or 0)).strftime("%Y-%m-%d")
+ return (
+ f"{when}: {commits} commits scanned, {last.get('bound', 0)} bound;"
+ f" known source {before} -> {after} ({_pct(before, commits)} -> {_pct(after, commits)})"
+ )
+
+
+async def _known_shas(repo_path: Path) -> set[str]:
+ """Commits the index labels agent or human-attested (empty without an index)."""
+ from sqlalchemy import select
+
+ from repowise.core.attribution import AGENT, HUMAN_ATTESTED, commit_label
+ from repowise.core.persistence.models import GitCommit
+
+ async with repo_index_session(repo_path) as opened:
+ if opened is None:
+ return set()
+ session, repo_id = opened
+ rows = await session.execute(
+ select(GitCommit.sha, GitCommit.attribution, GitCommit.agent_name).where(
+ GitCommit.repository_id == repo_id
+ )
+ )
+ return {
+ sha
+ for sha, attribution, agent in rows.all()
+ if commit_label(attribution, agent) in (AGENT, HUMAN_ATTESTED)
+ }
+
+
+@attribution_group.command(name="backfill")
[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))
+ "--agent",
+ "agents",
+ required=True,
+ help="Comma-separated agents whose transcripts to read, e.g. claude-code,codex.",
+)
+@format_option(choices=("table", "json"))
+def attribution_backfill(path: str | None, agents: str, fmt: str) -> None:
+ """Attribute past commits from the agent transcripts on this machine.
+
+ Reads Claude Code and Codex transcripts where they are and keeps only line
+ hashes of edits to this repository; an edit binds to a commit made within
+ 14 days after it. Each agent needs attribution.capture set to local or
+ notes and the agent listed in attribution.agents, in both the repo and the
+ user config. Runs only when you ask. The first run reads every transcript
+ these agents keep on this machine (about 4 minutes for 7 GB on a laptop);
+ a later run reads only what the agents wrote since. When it binds new
+ commits in an indexed repo, the next `repowise update` re-reads git history
+ once to label these commits.
+ """
+ from repowise.core.edit_capture.backfill import backfill, consent
+
+ repo_path = resolve_repo_path(path)
+ requested = list(dict.fromkeys(a.strip() for a in agents.split(",") if a.strip()))
+ allowed, refused = consent(repo_path, requested)
+ for agent, why in refused.items():
+ console.print(f"[yellow]![/yellow] {agent}: not read, {why}.")
+ if not allowed:
+ raise click.ClickException(
+ "No agent can be backfilled. `repowise attribution status` shows the settings."
+ )
+ if fmt != "json":
+ console.print(
+ f"Reading {', '.join(allowed)} transcripts on this machine; only line hashes of"
+ " edits to this repository are kept."
+ )
+ result = backfill(
+ repo_path,
+ allowed,
+ capture=_settings(repo_path).capture,
+ known=run_async(_known_shas(repo_path)),
+ )
+ rewalk = bool(result.bindings) and _request_history_rewalk(repo_path)
+ commits = len(result.commits)
+ if fmt == "json":
+ emit_json(
+ {
+ "agents": allowed,
+ "refused": refused,
+ "transcripts": result.transcripts,
+ "edits": result.edits,
+ "edits_in_repo": result.edits_in_repo,
+ "commits_scanned": commits,
+ "bound": len(result.bindings),
+ "already_bound": len(result.bound_before),
+ "covered_before": result.covered_before,
+ "covered_after": result.covered_after,
+ "handed_to_capture": result.handed_over,
+ "history_rewalk_on_next_update": rewalk,
+ }
+ )
+ return
+ files = ", ".join(f"{n} {agent}" for agent, n in result.transcripts.items())
+ console.print(f" transcripts {files}")
+ console.print(f" edits {result.edits} found, {result.edits_in_repo} in this repository")
+ console.print(
+ f" commits {commits} scanned, {len(result.bindings)} bound"
+ f" ({len(result.bound_before)} already bound)"
+ )
+ console.print(
+ f" coverage {result.covered_before} -> {result.covered_after} of {commits}"
+ " scanned commits have a known source"
+ f" ({_pct(result.covered_before, commits)} -> {_pct(result.covered_after, commits)})"
+ )
+ if rewalk:
+ console.print(
+ " The next `repowise update` re-reads git history once to label these commits."
+ )
+
+
async def _purge(repo_path: Path) -> bool:
from repowise.core.persistence.crud import clear_attribution
diff --git a/packages/core/src/repowise/core/edit_capture/__init__.py b/packages/core/src/repowise/core/edit_capture/__init__.py
index 9bd7ebe96..057fb995a 100644
--- a/packages/core/src/repowise/core/edit_capture/__init__.py
+++ b/packages/core/src/repowise/core/edit_capture/__init__.py
@@ -12,6 +12,7 @@ code text and person identities are never stored.
* :mod:`.store` - the consent gate and the sidecar files.
* :mod:`.binder` - commit binding (precision first: a miss beats a false hit).
* :mod:`.notes` - git-ai v3 note writing and removal of only our own notes.
+* :mod:`.backfill` - past commits bound from local agent transcripts, on request.
Every module here is stdlib-only at import: the hook path imports it.
"""
diff --git a/packages/core/src/repowise/core/edit_capture/backfill.py b/packages/core/src/repowise/core/edit_capture/backfill.py
new file mode 100644
index 000000000..3137357e5
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/backfill.py
@@ -0,0 +1,428 @@
+"""Transcript backfill: attribute past commits from agent transcripts on this machine.
+
+Runs only from ``repowise attribution backfill``, never from ``init`` or
+``update``, and only for agents the repo and the user both opted into
+(``attribution.capture`` at ``local`` or ``notes``, the agent listed in
+``attribution.agents``; ``DO_NOT_TRACK`` keeps it off).
+
+One read loop, one parser, one hash: transcripts go through the cursored
+:func:`~repowise.core.sessions.cursor.iter_new_events` loop and the adapter's
+``normalize`` that every transcript miner uses; :class:`TranscriptEditRecorder`
+observes that stream like the episode recorder does, pairs each tool call with
+its result, asks ``adapter.file_edits`` (the extractor the live hook runs) what
+it wrote, and keeps only line hashes through :func:`.binder.event_rows`. The
+cursor lives in the attribution sidecar, so a second run reads only what the
+agents appended since.
+
+Precision first, as in the live binder, plus two backfill rules:
+
+* An edit binds only to a commit made within :data:`WINDOW_SECONDS` after it.
+* A run needs :data:`MIN_RUN_BACKFILL` substantive lines, not the live two:
+ a transcript holds months of edits, so a short common run meets a commit
+ by chance far more often than one hook event does.
+
+Paths: a transcript records the absolute path the agent wrote, often in a
+worktree. An edit maps to this repo when the longest suffix of its path that
+some candidate commit touched sits under the main checkout or a live worktree,
+or under a directory that no longer exists. A vanished directory beside a live
+worktree, or inside a ``worktrees/`` directory, is taken for a removed worktree
+and needs a two-segment suffix; any other vanished directory may have been any
+project, so it needs three. A suffix under an existing directory that is
+neither is another checkout or a sibling repo, and the edit is dropped. A path
+no commit touched yet maps only under a live root with no nested checkout on
+the way, so work still in progress waits for its commit.
+"""
+
+from __future__ import annotations
+
+import os
+import posixpath
+import re
+import time
+from collections.abc import Callable, Iterable, Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from .binder import (
+ COMMIT_GRACE_SECONDS,
+ _commits_to_bind,
+ _git,
+ bind_commits,
+ event_rows,
+ write_notes,
+)
+from .edits import CapturedCall
+from .store import (
+ BINDINGS,
+ EVENT_TTL_SECONDS,
+ EVENTS,
+ append_jsonl,
+ bound_commits,
+ load_state,
+ read_jsonl,
+ save_state,
+ sidecar_dir,
+)
+
+#: Edit-to-commit window. Measured on this repo's transcripts: 3 days binds 2%
+#: fewer commits than 14; 30 days binds 1% more and 8 contributor commits (no
+#: local transcripts behind them) instead of 3.
+WINDOW_SECONDS = 14 * 24 * 3600
+
+#: Substantive lines a backfilled run needs (live capture needs 2). Measured on
+#: this repo (1,861 commits, 13,399 mapped edits) against a control that moves
+#: every edit 16 days later, so any bind it makes is spurious: control binds
+#: per real bind 11% at 2, 6% at 3, 2.6% at 4, 1.8% at 5, 1.0% at 6, 0.7% at 7.
+#: At 6 it binds 583 commits (665 at 2), one of them a contributor's.
+MIN_RUN_BACKFILL = 6
+
+#: The backfill's own transcript cursors, apart from the decision miner's: that
+#: pass may have read these transcripts already, and must keep its place.
+CURSORS = "transcripts.json"
+
+_DRIVE_RE = re.compile(r"^/([A-Za-z]):?(?=/)")
+
+
+@dataclass
+class BackfillResult:
+ """What one backfill run read and bound."""
+
+ transcripts: dict[str, int] = field(default_factory=dict)
+ edits: int = 0
+ edits_in_repo: int = 0
+ commits: list[str] = field(default_factory=list)
+ bound_before: set[str] = field(default_factory=set)
+ bindings: list[dict[str, Any]] = field(default_factory=list)
+ handed_over: int = 0
+ #: Scanned commits with a known source before and after this run.
+ covered_before: int = 0
+ covered_after: int = 0
+
+
+def consent(repo_root: Path, agents: Iterable[str]) -> tuple[list[str], dict[str, str]]:
+ """``(allowed, refused)`` for *agents* (target ids such as ``claude-code``).
+
+ *refused* maps an agent to the reason in plain words.
+ """
+ from repowise.core.agents.identity import get_identity
+ from repowise.core.attribution import load_attribution_settings
+
+ settings = load_attribution_settings(repo_root)
+ allowed: list[str] = []
+ refused: dict[str, str] = {}
+ for name in agents:
+ identity = get_identity(name.replace("-", "_"))
+ agent = identity.cli_target_id if identity is not None else name
+ if identity is None or identity.session_adapter is None or identity.capture_adapter is None:
+ refused[agent] = "no transcript adapter for this agent"
+ elif not settings.enabled:
+ refused[agent] = "attribution is switched off"
+ elif settings.do_not_track:
+ refused[agent] = "DO_NOT_TRACK is set"
+ elif settings.capture == "off":
+ refused[agent] = "attribution.capture is off (set local or notes in both configs)"
+ elif agent not in settings.agents:
+ refused[agent] = "not listed in attribution.agents (repo and user config)"
+ else:
+ allowed.append(agent)
+ return allowed, refused
+
+
+class TranscriptEditRecorder:
+ """Folds the edits a transcript stream records into hash rows, passing events through.
+
+ Paths stay as the transcript wrote them (with the call's cwd) until
+ :meth:`rows` maps them, because the map needs the commit window, which is
+ known only once every transcript has been read.
+ """
+
+ def __init__(self, keep: Callable[[str, str], Any] | None = None) -> None:
+ #: Drops at record time an edit no path of this repo could match.
+ self._keep = keep
+ self._rows: list[tuple[dict[str, Any], str]] = []
+ self._seen: set[tuple[str, str, str]] = set()
+ self._pending: dict[str, tuple[Any, Any]] = {}
+ self.edits = 0
+
+ def prefilter(self, adapter: Any) -> Callable[[str], bool]:
+ """The adapter's edit-call gate, plus result lines for calls awaiting one."""
+ from repowise.core.sessions.adapters.base import INTENT_EDIT_CALLS, INTENT_TOOL_CALLS
+
+ gate = adapter.prefilter(INTENT_EDIT_CALLS)
+ tool_lines = adapter.prefilter(INTENT_TOOL_CALLS)
+ pending = self._pending
+
+ def admit(raw: str) -> bool:
+ if gate is None or gate(raw):
+ return True
+ if not pending or (tool_lines is not None and not tool_lines(raw)):
+ return False
+ return any(use_id in raw for use_id in pending)
+
+ return admit
+
+ def observe(self, adapter: Any, agent: str, events: Iterable[Any]) -> Iterator[Any]:
+ """Yield *events* through untouched, recording the edits among them."""
+ self._pending.clear() # a call never pairs across transcripts
+ model: str | None = None
+ for event in events:
+ yield event
+ model = event.model or model
+ for use in event.tool_uses:
+ if use.name in adapter.edit_tool_names:
+ self._pending[use.id] = (use, event)
+ for result in event.tool_results:
+ found = self._pending.pop(result.tool_use_id, None)
+ if found is not None:
+ self._record(adapter, agent, found, result, event, model)
+
+ def _record(
+ self, adapter: Any, agent: str, found: tuple[Any, Any], result: Any, event: Any, model: str | None
+ ) -> None:
+ use, use_event = found
+ edits = adapter.file_edits(use, result)
+ ts = event.ts or use_event.ts
+ if not edits or ts is None:
+ return
+ self.edits += len(edits)
+ call = CapturedCall(
+ tool=use.name,
+ edits=edits,
+ session_id=use_event.session_id or "",
+ model=use_event.model or model,
+ cwd=use_event.cwd or "",
+ call_id=use.id,
+ )
+ for row in event_rows(agent, call, ts=ts):
+ key = (agent, row["call"], row["path"])
+ if self._keep is not None and self._keep(row["path"], call.cwd) is None:
+ continue
+ if key not in self._seen:
+ self._seen.add(key)
+ self._rows.append((row, call.cwd))
+
+ def rows(self, resolve: Any) -> list[dict[str, Any]]:
+ """Rows whose path maps into the repo, the path made repo-relative."""
+ out: list[dict[str, Any]] = []
+ for row, cwd in self._rows:
+ rel = resolve(row["path"], cwd)
+ if rel is not None:
+ out.append({**row, "path": rel})
+ return out
+
+ @property
+ def oldest(self) -> float | None:
+ return min((row["ts"] for row, _ in self._rows), default=None)
+
+
+def _absolute(path: str, cwd: str) -> str | None:
+ """*path* as an absolute POSIX-style path, resolved against *cwd*; None if neither says."""
+ path = path.replace("\\", "/")
+ if path.startswith("file://"):
+ path = path[len("file://") :]
+ if os.name == "nt":
+ path = _DRIVE_RE.sub(r"\1:", path) # /c/x and /C:/x are C:/x
+ if not (path.startswith("/") or path[1:2] == ":"):
+ if not cwd:
+ return None
+ base = _absolute(cwd, "")
+ if base is None:
+ return None
+ path = f"{base}/{path}"
+ return posixpath.normpath(path)
+
+
+class PathMap:
+ """Maps a transcript path to this repo's path; see the module docstring."""
+
+ def __init__(self, main: str, worktrees: Iterable[str], known: Iterable[str]) -> None:
+ self._fold = str.lower if os.name == "nt" else str
+ trees = [self._root(root) for root in worktrees]
+ self._live = {self._root(main), *trees}
+ # Where this repo's worktrees live: a vanished sibling was most likely one.
+ self._tree_parents = {posixpath.dirname(root) for root in trees}
+ self._known = {self._fold(path): path for path in known}
+ self._exists: dict[str, bool] = {}
+
+ def _root(self, root: str) -> str:
+ return self._fold(root.replace("\\", "/").rstrip("/"))
+
+ def __call__(self, path: str, cwd: str) -> str | None:
+ absolute = _absolute(path, cwd)
+ if absolute is None:
+ return None
+ segments = absolute.split("/")
+ # From 2: never take a drive or the filesystem root for a checkout.
+ for i in range(2, len(segments)):
+ rel = self._known.get(self._fold("/".join(segments[i:])))
+ if rel is None:
+ continue
+ root = "/".join(segments[:i])
+ if self._fold(root) in self._live:
+ return rel
+ if not self._exists_on_disk(root) and len(segments) - i >= self._suffix_needed(root):
+ return rel
+ return None
+ return self._uncommitted(segments)
+
+ def _suffix_needed(self, root: str) -> int:
+ parent = self._fold(posixpath.dirname(root))
+ return 2 if parent in self._tree_parents or posixpath.basename(parent) == "worktrees" else 3
+
+ def _uncommitted(self, segments: list[str]) -> str | None:
+ """A path no candidate commit touched yet, under a live root, with no
+ nested checkout (its own ``.git``) on the way to it."""
+ for i in range(len(segments) - 1, 1, -1):
+ if self._fold("/".join(segments[:i])) not in self._live:
+ continue
+ directory = "/".join(segments[:i])
+ for part in segments[i:-1]:
+ directory = f"{directory}/{part}"
+ if not self._exists_on_disk(directory) or self._exists_on_disk(f"{directory}/.git"):
+ return None
+ return "/".join(segments[i:])
+ return None
+
+ def _exists_on_disk(self, path: str) -> bool:
+ if path not in self._exists:
+ self._exists[path] = os.path.exists(path)
+ return self._exists[path]
+
+
+def worktree_roots(repo: Path) -> list[str]:
+ """The main checkout and every live worktree of *repo*."""
+ out = _git(repo, "worktree", "list", "--porcelain")
+ roots = [line[len("worktree ") :] for line in out.splitlines() if line.startswith("worktree ")]
+ return roots or [str(repo)]
+
+
+def _paths_since(repo: Path, since: float | None) -> set[str]:
+ """Paths commits since *since* touched; every path ever with None."""
+ window = [] if since is None else [f"--since={int(since) - COMMIT_GRACE_SECONDS}"]
+ out = _git(repo, "log", "--no-merges", *window, "--format=", "--name-only", "HEAD")
+ return {line for line in out.splitlines() if line}
+
+
+def read_transcripts(
+ agents: list[str],
+ recorder: TranscriptEditRecorder,
+ cursors: Any,
+ *,
+ projects_roots: dict[str, Path] | None = None,
+) -> dict[str, int]:
+ """Feed every transcript of *agents* through *recorder*; returns files read per agent.
+
+ *cursors* advance in memory; the caller saves them once the edits are bound.
+ """
+ from repowise.core.agents.identity import get_identity
+ from repowise.core.sessions import get_adapter
+ from repowise.core.sessions.cursor import iter_new_events
+
+ counts: dict[str, int] = {}
+ for agent in agents:
+ identity = get_identity(agent.replace("-", "_"))
+ if identity is None or identity.session_adapter is None:
+ continue
+ adapter = get_adapter(identity.session_adapter)
+ root = (projects_roots or {}).get(agent)
+ prefilter = recorder.prefilter(adapter)
+ counts[agent] = 0
+ for path in adapter.discover_all(projects_root=root):
+ try:
+ events = iter_new_events(adapter, path, cursors, prefilter=prefilter)
+ for _ in recorder.observe(adapter, identity.slug, events):
+ pass
+ except OSError:
+ continue
+ counts[agent] += 1
+ return counts
+
+
+def backfill(
+ repo: Path,
+ agents: list[str],
+ *,
+ capture: str,
+ projects_roots: dict[str, Path] | None = None,
+ now: float | None = None,
+ min_run: int = MIN_RUN_BACKFILL,
+ window: float = WINDOW_SECONDS,
+ known: set[str] | None = None,
+) -> BackfillResult:
+ """Read *agents*' transcripts and bind their edits to this repo's commits.
+
+ *agents* must already have passed :func:`consent`; *capture* is the
+ effective level (``notes`` also writes a git-ai note per bound commit).
+ *known* is the commits the index already labels agent or human-attested,
+ for the coverage figures.
+ Bindings land in the sidecar beside the live ones. Unbound edits younger
+ than the pending-event TTL join the pending events, so a commit made after
+ this run still finds them.
+ """
+ from repowise.core.sessions.cursor import CursorStore
+
+ now = time.time() if now is None else now
+ roots = worktree_roots(repo)
+ # Ceiling: one string per path the history ever held, so memory grows with
+ # the repo's history, not with the transcripts; edits elsewhere are dropped
+ # as they are read.
+ recorder = TranscriptEditRecorder(keep=PathMap(roots[0], roots[1:], _paths_since(repo, None)))
+ cursors = CursorStore(sidecar_dir(repo) / CURSORS)
+ result = BackfillResult(
+ transcripts=read_transcripts(agents, recorder, cursors, projects_roots=projects_roots)
+ )
+ result.edits = recorder.edits
+ oldest = recorder.oldest
+ if oldest is not None:
+ result.commits = _commits_to_bind(repo, oldest, None)
+ path_map = PathMap(roots[0], roots[1:], _paths_since(repo, oldest))
+ rows = recorder.rows(path_map)
+ result.edits_in_repo = len(rows)
+ done = bound_commits(repo)
+ result.bound_before = {sha for sha in result.commits if sha in done}
+ todo = [sha for sha in result.commits if sha not in done]
+ result.bindings = bind_commits(repo, rows, todo, window=window, min_run=min_run)
+ covered = {sha for sha in result.commits if sha in (known or set())} | result.bound_before
+ result.covered_before = len(covered)
+ result.covered_after = len(covered | {b["commit"] for b in result.bindings})
+ _persist(repo, result, rows, capture=capture, now=now, window=window)
+ cursors.save()
+ return result
+
+
+def _persist(
+ repo: Path,
+ result: BackfillResult,
+ rows: list[dict[str, Any]],
+ *,
+ capture: str,
+ now: float,
+ window: float,
+) -> None:
+ directory = sidecar_dir(repo)
+ live_pending = bool(read_jsonl(directory / EVENTS))
+ append_jsonl(directory / BINDINGS, result.bindings)
+ if capture == "notes" and result.bindings:
+ write_notes(repo, result.bindings)
+ left = [row for row in rows if row["hashes"] and now - row["ts"] <= EVENT_TTL_SECONDS]
+ append_jsonl(directory / EVENTS, left)
+ result.handed_over = len(left)
+ state = load_state(repo)
+ # With no live events waiting, every commit up to HEAD has been tried: the
+ # live binder may start after it, so an edit this run left unbound never
+ # meets an older commit under the live rule. Live events waiting for those
+ # commits keep the cursor where it is.
+ head = _git(repo, "rev-parse", "HEAD").strip()
+ if head and not state.get("cursor") and not live_pending:
+ state["cursor"] = head
+ state["backfill"] = {
+ "at": now,
+ "commits": len(result.commits),
+ "bound": len(result.bindings),
+ "bound_before": len(result.bound_before),
+ "covered_before": result.covered_before,
+ "covered_after": result.covered_after,
+ "window_days": round(window / 86400),
+ }
+ save_state(repo, state)
diff --git a/packages/core/src/repowise/core/edit_capture/binder.py b/packages/core/src/repowise/core/edit_capture/binder.py
index 376cb54fc..5e17ae776 100644
--- a/packages/core/src/repowise/core/edit_capture/binder.py
+++ b/packages/core/src/repowise/core/edit_capture/binder.py
@@ -19,10 +19,10 @@ The match is by content hash within a path, and every rule leans toward a miss:
A commit with no bound line stays unknown; nothing here ever says human.
-Backfill seam: transcript backfill feeds the same matcher. Inside the existing
-transcript pass, ``adapter.file_edits(use, result)`` yields the edits a recorded
-tool call made, and :func:`event_rows` turns them into the rows this module
-matches, so one read of a transcript serves both decisions and attribution.
+Transcript backfill (:mod:`.backfill`) feeds the same matcher through
+:func:`bind_commits`: ``adapter.file_edits(use, result)`` yields the edits a
+recorded tool call made, and :func:`event_rows` turns them into the rows this
+module matches.
"""
from __future__ import annotations
@@ -161,11 +161,18 @@ def _sole_owner(rows: list[dict[str, Any]], owners: list[int]) -> tuple[str, int
return next(iter(agents)), max(owners, key=lambda i: rows[i]["ts"])
-def _hash_owners(rows: list[dict[str, Any]], names: set[str], ct: int) -> dict[str, list[int]]:
- """Hash to the indexes of rows for *names* recorded before the commit at *ct*."""
+def _hash_owners(
+ rows: list[dict[str, Any]], candidates: list[int], ct: int, window: float | None = None
+) -> dict[str, list[int]]:
+ """Hash to the indexes among *candidates* of rows recorded before the commit at *ct*.
+
+ With *window*, only rows recorded at most that many seconds before it.
+ """
+ earliest = ct - window if window is not None else float("-inf")
by_hash: dict[str, list[int]] = {}
- for idx, row in enumerate(rows):
- if row["path"] in names and row["ts"] <= ct + COMMIT_GRACE_SECONDS:
+ for idx in candidates:
+ row = rows[idx]
+ if earliest <= row["ts"] <= ct + COMMIT_GRACE_SECONDS:
for h in row["hashes"]:
by_hash.setdefault(h, []).append(idx)
return by_hash
@@ -175,6 +182,7 @@ def _match_file(
rows: list[dict[str, Any]],
by_hash: dict[str, list[int]],
hunks: list[tuple[int, list[str]]],
+ min_run: int = MIN_RUN_SUBSTANTIVE,
) -> list[tuple[int, int, str]]:
"""``(row index, line number, hash)`` for every line this file binds."""
hashed = [[(n + i, text, line_hash(text)) for i, text in enumerate(added)] for n, added in hunks]
@@ -197,32 +205,65 @@ def _match_file(
return [
(idx, n, h)
for run in runs
- if sum(1 for *_, sub in run if sub) >= MIN_RUN_SUBSTANTIVE
+ if sum(1 for *_, sub in run if sub) >= min_run
for idx, n, h, _ in run
]
def _bind_commit(
- repo: Path, sha: str, rows: list[dict[str, Any]]
+ repo: Path,
+ sha: str,
+ rows: list[dict[str, Any]],
+ by_path: dict[str, list[int]],
+ window: float | None,
+ min_run: int,
) -> dict[str, Any] | None:
ct, files = commit_diff(repo, sha)
- sessions = _bound_lines(rows, ct, files)
+ sessions = _bound_lines(rows, by_path, ct, files, window, min_run)
return _binding(sha, ct, sessions) if sessions else None
+def bind_commits(
+ repo: Path,
+ rows: list[dict[str, Any]],
+ commits: list[str],
+ *,
+ window: float | None = None,
+ min_run: int = MIN_RUN_SUBSTANTIVE,
+) -> list[dict[str, Any]]:
+ """Bind *rows* to *commits* (oldest first), consuming the hashes they bind.
+
+ The matcher :func:`bind_pending` runs, for a caller that holds its own rows
+ and commit list (transcript backfill). *window* bounds how long before a
+ commit an edit may be; *min_run* raises the substantive lines a run needs.
+ """
+ by_path: dict[str, list[int]] = {}
+ for idx, row in enumerate(rows):
+ by_path.setdefault(row["path"], []).append(idx)
+ return [
+ binding
+ for sha in commits
+ if (binding := _bind_commit(repo, sha, rows, by_path, window, min_run)) is not None
+ ]
+
+
_Sessions = dict[tuple[str, str, str | None], dict[str, list[int]]]
def _bound_lines(
rows: list[dict[str, Any]],
+ by_path: dict[str, list[int]],
ct: int,
files: list[tuple[str, str | None, list[tuple[int, list[str]]]]],
+ window: float | None,
+ min_run: int,
) -> _Sessions:
"""Bound line numbers per ``(agent, session, model)`` and path; consumes matched hashes."""
sessions: _Sessions = {}
for path, old, hunks in files:
- by_hash = _hash_owners(rows, {path, old} if old else {path}, ct)
- for idx, number, h in _match_file(rows, by_hash, hunks) if by_hash else []:
+ candidates = by_path.get(path, []) + (by_path.get(old, []) if old else [])
+ by_hash = _hash_owners(rows, candidates, ct, window)
+ for idx, number, h in _match_file(rows, by_hash, hunks, min_run) if by_hash else []:
row = rows[idx]
if h in row["hashes"]:
row["hashes"].remove(h)
@@ -338,7 +379,7 @@ def bind_pending(repo: Path, *, capture: str, now: float | None = None) -> list[
bindings = _bind_rows(repo, rows)
append_jsonl(directory / BINDINGS, bindings)
if capture == "notes" and bindings:
- _write_notes(repo, bindings)
+ write_notes(repo, bindings)
finally:
_return_events(directory, [row for row in rows if row["hashes"]])
return bindings
@@ -352,11 +393,7 @@ def _bind_rows(repo: Path, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
since = min(row["ts"] for row in rows)
pending = _commits_to_bind(repo, since, load_state(repo).get("cursor"))
batch = pending[:MAX_COMMITS]
- bindings = [
- binding
- for sha in batch
- if sha not in done and (binding := _bind_commit(repo, sha, rows)) is not None
- ]
+ bindings = bind_commits(repo, rows, [sha for sha in batch if sha not in done])
# A capped run stops the cursor at its last commit; the next run
# continues from there instead of skipping the rest.
cursor = batch[-1] if len(pending) > MAX_COMMITS else _git(repo, "rev-parse", "HEAD").strip()
@@ -367,7 +404,7 @@ def _bind_rows(repo: Path, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
return bindings
-def _write_notes(repo: Path, bindings: list[dict[str, Any]]) -> None:
+def write_notes(repo: Path, bindings: list[dict[str, Any]]) -> None:
from .notes import ensure_rewrite_ref, render_note, write_note
ensure_rewrite_ref(repo)
diff --git a/packages/core/src/repowise/core/edit_capture/edits.py b/packages/core/src/repowise/core/edit_capture/edits.py
index 5b482ec6d..b096740de 100644
--- a/packages/core/src/repowise/core/edit_capture/edits.py
+++ b/packages/core/src/repowise/core/edit_capture/edits.py
@@ -24,7 +24,12 @@ Payload shapes, and where each was checked:
longer a tool in that build; kept for older transcripts, shape as documented.
* Codex ``PostToolUse``: adds ``model`` and ``turn_id``; ``apply_patch`` carries
the patch envelope in ``tool_input.command`` and a string ``tool_response``
- starting ``Exit code: N`` (openai/codex hook schema and hook tests).
+ starting ``Exit code: N`` (openai/codex hook schema and hook tests). In code
+ mode (an ``exec`` cell, Codex 0.144 to 0.162 rollouts on this machine) the
+ envelope is a JavaScript string literal passed to ``tools.apply_patch`` and
+ the response is a list of text blocks opening ``Script completed`` or
+ ``Script failed``; :func:`codex_edits` reads both shapes, whichever one the
+ hook or the rollout hands it.
* Cursor ``afterFileEdit``: ``conversation_id``, ``generation_id``, ``model``,
``workspace_roots``, ``file_path``, ``edits[]`` of
``old_string``/``new_string`` (cursor.com/docs/agent/hooks). ``user_email``
@@ -188,9 +193,118 @@ def parse_apply_patch(patch: str) -> list[FileEdit]:
return [edit for edit in edits if edit.added]
+_JS_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", "b": "\b", "f": "\f", "v": "\v", "0": "\0"}
+_APPLY_PATCH_CALL = re.compile(r"tools\.apply_patch\s*\(\s*")
+_JS_NAME = re.compile(r"[A-Za-z_$][\w$]*")
+_HEX = re.compile(r"[0-9a-fA-F]+")
+
+
+def _js_escape(source: str, i: int) -> tuple[str, int] | None:
+ """The escape whose letter sits at *source[i]*, decoded, and the index after it."""
+ esc = source[i]
+ if esc in _JS_ESCAPES:
+ return _JS_ESCAPES[esc], i + 1
+ if esc == "\r" and source[i + 1 : i + 2] == "\n":
+ return "", i + 2 # line continuation
+ if esc == "\n":
+ return "", i + 1
+ if esc == "x":
+ digits, end, size = source[i + 1 : i + 3], i + 3, 2
+ elif esc == "u" and source[i + 1 : i + 2] == "{":
+ close = source.find("}", i)
+ digits, end, size = (source[i + 2 : close], close + 1, 0) if close > 0 else ("", i, 0)
+ elif esc == "u":
+ digits, end, size = source[i + 1 : i + 5], i + 5, 4
+ else:
+ return esc, i + 1 # \\ \" \' \` and identity escapes
+ if not _HEX.fullmatch(digits) or (size and len(digits) != size) or int(digits, 16) > 0x10FFFF:
+ return None
+ return chr(int(digits, 16)), end
+
+
+def _js_string(source: str, start: int) -> str | None:
+ """The JavaScript string literal opening at *source[start]*, decoded.
+
+ None when it does not close, or is a template literal that interpolates.
+ """
+ quote, out, i = source[start], [], start + 1
+ while i < len(source):
+ ch = source[i]
+ if ch == quote:
+ try: # a \\uD83D\\uDE00 pair becomes one character
+ return "".join(out).encode("utf-16", "surrogatepass").decode("utf-16")
+ except UnicodeError:
+ return None
+ if ch == "\\" and i + 1 < len(source):
+ decoded = _js_escape(source, i + 1)
+ if decoded is None:
+ return None
+ out.append(decoded[0])
+ i = decoded[1]
+ continue
+ if (ch == "\n" and quote != "`") or (quote == "`" and source.startswith("${", i)):
+ return None
+ out.append(ch)
+ i += 1
+ return None
+
+
+def _apply_patch_argument(source: str, call: re.Match[str]) -> str | None:
+ """The string literal a ``tools.apply_patch(`` call receives: written in
+ place, or the literal last assigned to the variable it passes."""
+ start = call.end()
+ if source[start : start + 1] in ("\"", "'", "`"):
+ return _js_string(source, start)
+ name = _JS_NAME.match(source, start)
+ if name is None:
+ return None
+ assign = rf"(?<![\w$.]){re.escape(name.group(0))}\s*=\s*(?=[\"'`])"
+ found = list(re.finditer(assign, source[: call.start()]))
+ return _js_string(source, found[-1].end()) if found else None
+
+
+def _exec_cell_patches(source: str) -> list[str]:
+ """Patches a Codex code-mode cell passes to ``tools.apply_patch``.
+
+ The cell is JavaScript (``const patch = "*** Begin Patch\\n..."; await
+ tools.apply_patch(patch)``), so the envelope sits escaped inside a literal.
+ A literal the call does not receive is never read.
+ """
+ found = (_apply_patch_argument(source, m) for m in _APPLY_PATCH_CALL.finditer(source))
+ return [p for p in found if p and p.lstrip().startswith("*** Begin Patch")]
+
+
+def _response_text(tool_response: Any) -> str:
+ if isinstance(tool_response, list):
+ return "\n".join(
+ block["text"]
+ for block in tool_response
+ if isinstance(block, dict) and isinstance(block.get("text"), str)
+ )
+ return tool_response if isinstance(tool_response, str) else ""
+
+
+def _codex_call_failed(tool_response: Any) -> bool:
+ """Whether a Codex patch call reports it wrote nothing, or cannot say yet.
+
+ ``Exit code: N`` (N not 0) for a direct call; a code-mode cell says
+ ``Script failed``, or ``Script running`` while its outcome is unknown, and
+ a cell that caught a failed patch still prints the verification error.
+ """
+ text = _response_text(tool_response)
+ return bool(
+ re.match(r"Exit code: (?!0\b)-?\d+", text)
+ or text.startswith(("Script failed", "Script running"))
+ or "apply_patch verification failed" in text
+ )
+
+
def codex_edits(tool_name: str, tool_input: Any, tool_response: Any) -> list[FileEdit]:
- """Codex ``apply_patch``. A failed call (``Exit code: N``, N not 0) wrote nothing."""
- if isinstance(tool_response, str) and re.match(r"Exit code: (?!0\b)-?\d+", tool_response):
+ """Codex ``apply_patch``, called directly or from a code-mode cell.
+
+ A call whose response reports a failure (:func:`_codex_call_failed`) wrote nothing.
+ """
+ if _codex_call_failed(tool_response):
return []
patch = ""
if isinstance(tool_input, dict):
@@ -199,7 +313,9 @@ def codex_edits(tool_name: str, tool_input: Any, tool_response: Any) -> list[Fil
patch = tool_input
if "*** Begin Patch" not in patch:
return []
- return parse_apply_patch(patch)
+ if patch.lstrip().startswith("*** Begin Patch"):
+ return parse_apply_patch(patch)
+ return [edit for body in _exec_cell_patches(patch) for edit in parse_apply_patch(body)]
def cursor_edits(tool_name: str, tool_input: Any, tool_response: Any) -> list[FileEdit]:
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
index d3956672c..be945ef5a 100644
--- a/packages/core/src/repowise/core/sessions/adapters/base.py
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -43,6 +43,10 @@ INTENT_TOOL_CALLS = "tool_calls"
#: Conversation turns: user prose, assistant prose, and the tool traffic
#: carried on them.
INTENT_TURNS = "turns"
+#: Tool calls that may change a file, plus the lines that scope them (cwd,
+#: model). Results are not included: a consumer pairing them admits a result
+#: line by its call id, which only it knows.
+INTENT_EDIT_CALLS = "edit_calls"
class HarnessAdapter(ABC):
@@ -82,6 +86,15 @@ class HarnessAdapter(ABC):
tests). An absent directory yields an empty list, never an error.
"""
+ def discover_all(self, *, projects_root: Path | None = None) -> list[Path]:
+ """Every transcript this harness keeps on this machine, sorted.
+
+ For a pass that scopes each edit by its own path rather than by where
+ the session started: worktree sessions and subagent transcripts sit
+ outside :meth:`discover`'s directory. Empty unless an adapter says.
+ """
+ return []
+
@abstractmethod
def normalize(self, raw_line: str) -> Event | None:
"""One raw transcript line as an Event, or None when unparseable."""
@@ -164,13 +177,16 @@ class HarnessAdapter(ABC):
The same extractor the live capture hook runs (keyed by this adapter's
``name`` in :data:`repowise.core.edit_capture.edits.EXTRACTORS`), so a
- transcript and a hook payload of one call can never disagree.
+ transcript and a hook payload of one call can never disagree. A result
+ marked as an error wrote nothing.
"""
from repowise.core.edit_capture.edits import EXTRACTORS
extractor = EXTRACTORS.get(self.name)
if extractor is None or use.name not in self.edit_tool_names:
return []
+ if result is not None and result.is_error:
+ return []
return extractor(use.name, use.input, result.payload if result is not None else None)
def iter_events(self, path: Path, *, prefilter: RawPrefilter | None = None) -> Iterator[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
index 518448ca5..f37e9d261 100644
--- a/packages/core/src/repowise/core/sessions/adapters/claude_code.py
+++ b/packages/core/src/repowise/core/sessions/adapters/claude_code.py
@@ -23,9 +23,11 @@ from __future__ import annotations
import json
import re
from pathlib import Path
-from typing import Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar
+from repowise.core.fs_walk import iter_glob
from repowise.core.sessions.adapters.base import (
+ INTENT_EDIT_CALLS,
INTENT_SHELL_CALLS,
INTENT_TOOL_CALLS,
INTENT_TURNS,
@@ -35,6 +37,9 @@ from repowise.core.sessions.adapters.base import (
from repowise.core.sessions.adapters.registry import register_adapter
from repowise.core.sessions.events import Event, ToolResult, ToolUse, parse_timestamp
+if TYPE_CHECKING:
+ from repowise.core.edit_capture.edits import FileEdit
+
_NON_SLUG_RE = re.compile(r"[^A-Za-z0-9-]")
#: Conversation turns in Claude Code's JSONL. One alternation rather than a
@@ -42,6 +47,10 @@ _NON_SLUG_RE = re.compile(r"[^A-Za-z0-9-]")
#: 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)"')
+_EDIT_USE_RE = re.compile(r'"name":\s*"(?:Edit|Write|MultiEdit|NotebookEdit)"')
+#: What a ``Write`` result says when it made a new file. Subagent transcripts
+#: carry no ``toolUseResult``, so this text is the only record of a create.
+_CREATED_PREFIX = "File created successfully at:"
def transcript_dir_for(repo_root: Path, projects_root: Path | None = None) -> Path:
@@ -69,6 +78,33 @@ class ClaudeCodeAdapter(HarnessAdapter):
return []
return sorted(directory.glob("*.jsonl"))
+ def discover_all(self, *, projects_root: Path | None = None) -> list[Path]:
+ """Every project's transcripts, subagent transcripts under a session included."""
+ root = projects_root if projects_root is not None else Path.home() / ".claude" / "projects"
+ if not root.is_dir():
+ return []
+ return sorted(path for path in iter_glob(root, "*.jsonl") if path.is_file())
+
+ def file_edits(self, use: ToolUse, result: ToolResult | None = None) -> list[FileEdit]:
+ """As the base, recovering a subagent's ``Write`` of a new file from its result text.
+
+ Only a create is recovered: an overwrite may keep lines the agent did
+ not write, and without the structured patch nothing says which.
+ """
+ if (
+ result is not None
+ and result.payload is None
+ and use.name == "Write"
+ and _result_text(result.content).startswith(_CREATED_PREFIX)
+ ):
+ result = ToolResult(
+ tool_use_id=result.tool_use_id,
+ is_error=result.is_error,
+ content=result.content,
+ payload={"type": "create"},
+ )
+ return super().file_edits(use, result)
+
def prefilter(self, intent: str) -> RawPrefilter | None:
"""Claude Code's raw-line gates, keyed by what the consumer wants.
@@ -81,6 +117,8 @@ class ClaudeCodeAdapter(HarnessAdapter):
return _tool_calls_prefilter
if intent == INTENT_TURNS:
return _turns_prefilter
+ if intent == INTENT_EDIT_CALLS:
+ return _edit_calls_prefilter
return None
def normalize(self, raw_line: str) -> Event | None:
@@ -180,5 +218,17 @@ def _turns_prefilter(raw: str) -> bool:
return _TURN_RE.search(raw) is not None
+def _edit_calls_prefilter(raw: str) -> bool:
+ """Only tool_use lines naming an edit tool; every line carries its own cwd."""
+ return '"tool_use"' in raw and _EDIT_USE_RE.search(raw) is not None
+
+
+def _result_text(content: Any) -> str:
+ if isinstance(content, list):
+ texts = (block.get("text") for block in content if isinstance(block, dict))
+ return "".join(t for t in texts if isinstance(t, str)).lstrip()
+ return content.lstrip() if isinstance(content, str) else ""
+
+
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/codex.py b/packages/core/src/repowise/core/sessions/adapters/codex.py
index 6c6d903c4..ee8c612f3 100644
--- a/packages/core/src/repowise/core/sessions/adapters/codex.py
+++ b/packages/core/src/repowise/core/sessions/adapters/codex.py
@@ -15,6 +15,7 @@ from typing import Any, ClassVar
from repowise.core.fs_walk import iter_glob
from repowise.core.sessions.adapters.base import (
+ INTENT_EDIT_CALLS,
INTENT_SHELL_CALLS,
INTENT_TOOL_CALLS,
INTENT_TURNS,
@@ -57,6 +58,13 @@ def _tool_calls_prefilter(raw: str) -> bool:
)
+def _edit_calls_prefilter(raw: str) -> bool:
+ """Patch calls, direct or inside a code-mode cell, and the model each turn names."""
+ if "*** Begin Patch" in raw:
+ return '"type":"custom_tool_call"' in raw or '"type":"function_call"' in raw
+ return '"type":"turn_context"' in raw or _SESSION_META in raw
+
+
def _turns_prefilter(raw: str) -> bool:
return '"type":"event_msg"' in raw or '"type":"response_item"' in raw or _SESSION_META in raw
@@ -99,6 +107,10 @@ class CodexAdapter(HarnessAdapter):
return []
return sorted(path for path in iter_glob(root, "*.jsonl") if path.is_file())
+ def discover_all(self, *, projects_root: Path | None = None) -> list[Path]:
+ """Every rollout: :meth:`discover` already reads them all."""
+ return self.discover(Path(), projects_root=projects_root)
+
def normalize(self, raw_line: str) -> Event | None:
try:
entry = json.loads(raw_line)
@@ -184,6 +196,9 @@ class CodexAdapter(HarnessAdapter):
if intent == INTENT_TURNS:
return _turns_prefilter
+ if intent == INTENT_EDIT_CALLS:
+ return _edit_calls_prefilter
+
return None
def begin_file(self, path: Path | None = None) -> None:
diff --git a/tests/fixtures/attribution_capture/codex_exec_cell_rollout.jsonl b/tests/fixtures/attribution_capture/codex_exec_cell_rollout.jsonl
new file mode 100644
index 000000000..cd5986bd1
--- /dev/null
+++ b/tests/fixtures/attribution_capture/codex_exec_cell_rollout.jsonl
@@ -0,0 +1,6 @@
+{"timestamp":"2026-10-01T10:00:00.000Z","ordinal":0,"type":"session_meta","payload":{"session_id":"019f0000-0000-7000-8000-00000000c0de","cwd":"REPO_ROOT","originator":"codex_cli","cli_version":"0.154.0","model_provider":"openai"}}
+{"timestamp":"2026-10-01T10:00:01.000Z","ordinal":1,"type":"turn_context","payload":{"cwd":"REPO_ROOT","model":"gpt-5.5-codex"}}
+{"timestamp":"2026-10-01T10:00:02.000Z","ordinal":2,"type":"response_item","payload":{"type":"custom_tool_call","id":"ctc_1","status":"completed","call_id":"call_ok","name":"exec","input":"const patch = \"*** Begin Patch\\n*** Add File: src\\\\ledger.py\\n+def settle(ledger):\\n+ balance = sum(entry.amount for entry in ledger)\\n+ fees = compute_fees(balance, ledger.currency)\\n+ note = \\\"settled \\u2713\\\"\\n+ audit_settlement(ledger, balance, fees)\\n+ return balance - fees\\n*** End Patch\";\ntext(await tools.apply_patch(patch));\n"}}
+{"timestamp":"2026-10-01T10:00:03.000Z","ordinal":3,"type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_ok","output":[{"type":"input_text","text":"Script completed\nWall time 0.4 seconds\nOutput:\n {}"}]}}
+{"timestamp":"2026-10-01T10:00:04.000Z","ordinal":4,"type":"response_item","payload":{"type":"custom_tool_call","id":"ctc_2","status":"completed","call_id":"call_failed","name":"exec","input":"const patch = \"*** Begin Patch\\n*** Update File: src/report.py\\n@@\\n+def render(rows):\\n+ header = build_header(rows[0].keys())\\n+ body = [format_row(row) for row in rows]\\n*** End Patch\";\ntext(await tools.apply_patch(patch));\n"}}
+{"timestamp":"2026-10-01T10:00:05.000Z","ordinal":5,"type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_failed","output":[{"type":"input_text","text":"Script failed\nWall time 0.3 seconds\nOutput:\n Script error:\napply_patch verification failed: Failed to find expected lines in src/report.py"}]}}
diff --git a/tests/unit/cli/test_attribution_capture_cli.py b/tests/unit/cli/test_attribution_capture_cli.py
index d2ade8836..4a37ba1d3 100644
--- a/tests/unit/cli/test_attribution_capture_cli.py
+++ b/tests/unit/cli/test_attribution_capture_cli.py
@@ -168,3 +168,57 @@ def test_hook_stdout_stays_json_with_an_invalid_config(repo: Path, user_config:
assert "attribution_config_invalid" in out.stderr # the warning did fire
if out.stdout.strip():
json.loads(out.stdout)
+
+
+def _claude_write(home: Path, cwd: Path, rel: str, lines: list[str]) -> None:
+ """One Claude Code ``Write`` of a new file, as the transcript records it."""
+ import time
+
+ ts = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(time.time() - 600))
+ base = {"sessionId": "s", "cwd": str(cwd), "timestamp": ts}
+ use = base | {"type": "assistant", "message": {"model": "claude-opus-5", "content": [
+ {"type": "tool_use", "id": "toolu_1", "name": "Write",
+ "input": {"file_path": str(cwd / rel), "content": "\n".join(lines)}}]}}
+ result = base | {"type": "user", "toolUseResult": {"type": "create"}, "message": {"content": [
+ {"type": "tool_result", "tool_use_id": "toolu_1", "content": "ok"}]}}
+ path = home / ".claude" / "projects" / "p" / "s.jsonl"
+ path.parent.mkdir(parents=True)
+ path.write_text(json.dumps(use) + "\n" + json.dumps(result) + "\n", encoding="utf-8")
+
+
+def test_backfill_refuses_without_consent(repo: Path, user_config: Path) -> None:
+ result = CliRunner().invoke(attribution_group, ["backfill", str(repo), "--agent", "claude-code"])
+ assert result.exit_code != 0
+ assert "attribution.capture is off" in result.output
+
+
+def test_backfill_reports_and_status_shows_the_run(
+ repo: Path, user_config: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ home = tmp_path / "fakehome"
+ monkeypatch.setattr(Path, "home", lambda: home)
+ _opt_in(repo, user_config, "local", "[claude-code, codex]")
+ lines = [f"value_{i} = compute_value({i}, scale)" for i in range(8)]
+ _claude_write(home, repo, "src/values.py", lines)
+ (repo / "src").mkdir()
+ (repo / "src" / "values.py").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "values")
+ state = repo / ".repowise" / "state.json"
+ state.write_text(json.dumps({"git_history_version": 3, "last_sync_commit": "abc"}), encoding="utf-8")
+
+ result = CliRunner().invoke(
+ attribution_group, ["backfill", str(repo), "--agent", "claude-code,codex", "--format", "json"]
+ )
+ assert result.exit_code == 0, result.output
+ report = json.loads(result.output)
+ assert report["bound"] == 1 and report["commits_scanned"] >= 1
+ assert report["covered_after"] == report["covered_before"] + 1
+ # The next update re-reads git history once; nothing else in the state moves.
+ assert report["history_rewalk_on_next_update"] is True
+ assert json.loads(state.read_text(encoding="utf-8")) == {"last_sync_commit": "abc"}
+
+ status = CliRunner().invoke(attribution_group, ["status", str(repo), "--format", "json"])
+ assert json.loads(status.output)["backfill"]["bound"] == 1
+ text = CliRunner().invoke(attribution_group, ["status", str(repo)]).output
+ assert "backfill" in text and "1 bound" in text
diff --git a/tests/unit/edit_capture/test_backfill.py b/tests/unit/edit_capture/test_backfill.py
new file mode 100644
index 000000000..951a0eb17
--- /dev/null
+++ b/tests/unit/edit_capture/test_backfill.py
@@ -0,0 +1,433 @@
+"""Transcript backfill: one read loop and extractor, worktree path mapping, precision rules.
+
+Transcripts are synthetic, shapes are real: Claude Code lines as the 2.1.x
+writer records them (main and subagent transcripts), Codex rollouts as 0.154
+records a code-mode ``exec`` cell (``tests/fixtures/attribution_capture``).
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from repowise.core.edit_capture import backfill as bf
+from repowise.core.edit_capture.binder import bind_pending
+from repowise.core.edit_capture.edits import CAPTURE_ADAPTERS, CapturedCall, FileEdit, codex_edits
+from repowise.core.edit_capture.store import (
+ EVENTS,
+ load_state,
+ read_jsonl,
+ record_call,
+ sidecar_dir,
+)
+from repowise.core.sessions.adapters import get_adapter
+from repowise.core.sessions.events import ToolResult, ToolUse
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "attribution_capture"
+DAY = 86400
+
+LEDGER = [
+ "def settle(ledger):",
+ " balance = sum(entry.amount for entry in ledger)",
+ " fees = compute_fees(balance, ledger.currency)",
+ ' note = "settled \u2713"',
+ " audit_settlement(ledger, balance, fees)",
+ " return balance - fees",
+]
+
+
+def _body(name: str, n: int = bf.MIN_RUN_BACKFILL) -> list[str]:
+ """*n* distinct substantive lines."""
+ return [f"{name}_{i} = compute_{name}_value({i}, scale)" for i in range(n)]
+
+
+REPORT = _body("report")
+TAXES = _body("taxes")
+OLD, ERR, SUB, LATER = _body("old"), _body("err"), _body("sub"), _body("later")
+
+
+def _iso(ts: float) -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(ts))
+
+
+class ClaudeTranscript:
+ """Writes Claude Code JSONL: an assistant ``tool_use`` line, then its result line."""
+
+ def __init__(self, path: Path, cwd: str, *, subagent: bool = False) -> None:
+ self.path, self.cwd, self.subagent = path, cwd, subagent
+ self.lines: list[dict] = []
+ self.n = 0
+
+ def call(self, name: str, tool_input: dict, ts: float, *, result=None, error: bool = False, text: str = "ok") -> None:
+ self.n += 1
+ use_id = f"toolu_{self.n:04d}"
+ base = {"sessionId": "sess-1", "cwd": self.cwd, "isSidechain": self.subagent}
+ self.lines.append(
+ base
+ | {
+ "type": "assistant",
+ "timestamp": _iso(ts),
+ "message": {
+ "id": f"msg_{self.n}",
+ "model": "claude-opus-5",
+ "content": [{"type": "tool_use", "id": use_id, "name": name, "input": tool_input}],
+ },
+ }
+ )
+ entry = base | {
+ "type": "user",
+ "timestamp": _iso(ts + 1),
+ "message": {
+ "content": [
+ {"type": "tool_result", "tool_use_id": use_id, "content": text, "is_error": error}
+ ]
+ },
+ }
+ if result is not None and not self.subagent:
+ entry["toolUseResult"] = result
+ self.lines.append(entry)
+
+ def write(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.write_text("".join(json.dumps(x) + "\n" for x in self.lines), encoding="utf-8")
+
+
+def _codex_rollout(root: Path, repo_root: Path, ts: float) -> None:
+ text = (FIXTURES / "codex_exec_cell_rollout.jsonl").read_text(encoding="utf-8")
+ text = text.replace("REPO_ROOT", str(repo_root).replace("\\", "\\\\"))
+ lines = []
+ for i, line in enumerate(text.splitlines()):
+ row = json.loads(line)
+ row["timestamp"] = _iso(ts + i)
+ lines.append(json.dumps(row, separators=(",", ":")))
+ path = root / "2026" / "10" / "01" / "rollout-test.jsonl"
+ path.parent.mkdir(parents=True)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+# --- the shared extractor ------------------------------------------------------
+
+
+def test_codex_exec_cell_patch_is_decoded_from_its_js_literal() -> None:
+ lines = (FIXTURES / "codex_exec_cell_rollout.jsonl").read_text(encoding="utf-8").splitlines()
+ adapter = get_adapter("codex")
+ use_event, result_event = adapter.normalize(lines[2]), adapter.normalize(lines[3])
+ (use,) = use_event.tool_uses
+ assert use.name == "edit_file"
+ (edit,) = adapter.file_edits(use, result_event.tool_results[0])
+ assert edit.path == "src\\ledger.py" and edit.added == LEDGER
+
+
+ "cell",
+ [
+ "const p = '*** Begin Patch\\n*** Add File: a.py\\n+it\\'s = \"x\"\\n*** End Patch';\nawait tools.apply_patch(p);",
+ "const p = `*** Begin Patch\n*** Add File: a.py\n+it's = \"x\"\n*** End Patch`;\nawait tools.apply_patch(p);",
+ 'text(await tools.apply_patch("*** Begin Patch\\n*** Add File: a.py\\n+it\\x27s = \\"x\\"\\n*** End Patch"));',
+ ],
+ ids=["single-quoted", "template", "inline-hex-escape"],
+)
+def test_every_js_literal_form_decodes_the_same(cell: str) -> None:
+ (edit,) = codex_edits("edit_file", {"command": cell}, None)
+ assert (edit.path, edit.added) == ("a.py", ["it's = \"x\""])
+
+
+def test_a_direct_patch_that_mentions_the_cell_api_is_still_a_direct_patch() -> None:
+ patch = (
+ "*** Begin Patch\n*** Add File: docs/codex.md\n"
+ "+Code-mode cells call tools.apply_patch(patch) with a JavaScript literal.\n"
+ "*** End Patch"
+ )
+ (edit,) = codex_edits("apply_patch", {"command": patch}, "Exit code: 0\nSuccess.")
+ assert edit.path == "docs/codex.md" and len(edit.added) == 1
+
+
+def test_only_the_literal_apply_patch_receives_is_read() -> None:
+ cell = (
+ 'const draft = "*** Begin Patch\\n*** Add File: draft.py\\n+draft = 1\\n*** End Patch";\n'
+ 'let patch = "*** Begin Patch\\n*** Add File: old.py\\n+old = 1\\n*** End Patch";\n'
+ 'patch = "*** Begin Patch\\n*** Add File: real.py\\n+real = 1\\n*** End Patch";\n'
+ "text(await tools.apply_patch(patch));\n"
+ )
+ assert [e.path for e in codex_edits("edit_file", {"command": cell}, None)] == ["real.py"]
+
+
[email protected]("escape", ["\\x4g", "\\x+4", "\\u00 1", "\\u{+41}", "\\u{}"])
+def test_a_malformed_hex_escape_leaves_the_literal_unread(escape: str) -> None:
+ cell = f'await tools.apply_patch("*** Begin Patch\\n*** Add File: a.py\\n+v = {escape}\\n*** End Patch");'
+ assert codex_edits("edit_file", {"command": cell}, None) == []
+
+
+def test_an_interpolated_template_is_not_read() -> None:
+ cell = "const p = `*** Begin Patch\n*** Add File: ${name}\n+x = 1\n*** End Patch`;\nawait tools.apply_patch(p);"
+ assert codex_edits("edit_file", {"command": cell}, None) == []
+
+
+ "response",
+ [
+ [{"type": "input_text", "text": "Script failed\nWall time 0.3 seconds\nOutput:\n Script error:"}],
+ [{"type": "input_text", "text": "Script running with cell ID 4\nWall time 31.0 seconds\nOutput:\n"}],
+ [{"type": "input_text", "text": "Script completed\nOutput:\napply_patch verification failed: x"}],
+ "apply_patch verification failed: Failed to find expected lines in a.py",
+ "Exit code: 1\nWall time: 0.1 seconds",
+ ],
+ ids=["script-failed", "still-running", "caught-in-cell", "direct-verification", "exit-code"],
+)
+def test_a_failed_or_unfinished_patch_wrote_nothing(response) -> None:
+ patch = "*** Begin Patch\n*** Add File: a.py\n+value = compute_value()\n*** End Patch"
+ assert codex_edits("apply_patch", {"command": patch}, response) == []
+ assert codex_edits("apply_patch", {"command": patch}, "Exit code: 0\nSuccess.")
+
+
+def test_the_live_codex_hook_reads_an_exec_cell_too() -> None:
+ cell = json.loads((FIXTURES / "codex_exec_cell_rollout.jsonl").read_text().splitlines()[2])
+ payload = {
+ "hook_event_name": "PostToolUse",
+ "session_id": "s",
+ "cwd": "/work/demo",
+ "tool_name": "exec",
+ "tool_input": {"command": cell["payload"]["input"]},
+ "tool_response": [{"type": "input_text", "text": "Script completed\nOutput:\n {}"}],
+ "tool_use_id": "call_ok",
+ "model": "gpt-5.5-codex",
+ }
+ call = CAPTURE_ADAPTERS["codex"](payload)
+ assert call is not None and call.edits[0].added == LEDGER
+
+
+def test_a_claude_error_result_wrote_nothing() -> None:
+ adapter = get_adapter("claude_code")
+ use = ToolUse(id="t", name="Edit", input={"file_path": "a.py", "old_string": "x", "new_string": "y = compute()"})
+ failed = ToolResult(tool_use_id="t", is_error=True, payload="Error: File has not been read yet.")
+ assert adapter.file_edits(use, failed) == []
+
+
+ ("text", "recovered"),
+ [
+ ("File created successfully at: C:\\work\\a.py", True),
+ ("The file C:\\work\\a.py has been updated successfully.", False),
+ ],
+)
+def test_a_subagent_write_counts_only_as_a_create(text: str, recovered: bool) -> None:
+ """Subagent transcripts carry no toolUseResult; the result text says create or update."""
+ adapter = get_adapter("claude_code")
+ use = ToolUse(id="t", name="Write", input={"file_path": "C:\\work\\a.py", "content": "\n".join(TAXES)})
+ edits = adapter.file_edits(use, ToolResult(tool_use_id="t", content=text))
+ assert bool(edits) is recovered
+
+
+# --- path mapping ----------------------------------------------------------------
+
+
+def layout(tmp_path: Path) -> dict[str, str]:
+ main = tmp_path / "repo"
+ live = tmp_path / "wt" / "live"
+ other = tmp_path / "other"
+ for d in (main / "backend" / "app", live / "src", other / "src"):
+ d.mkdir(parents=True)
+ (main / "backend" / ".git").write_text("gitdir: elsewhere\n", encoding="utf-8")
+ posix = {k: str(v).replace("\\", "/") for k, v in {"main": main, "live": live, "other": other}.items()}
+ posix["removed"] = str(tmp_path / "wt" / "gone").replace("\\", "/")
+ return posix
+
+
+def _map(layout: dict[str, str]) -> bf.PathMap:
+ known = {"src/ledger.py", "README.md", "app/main.py", "src/index.ts", "packages/app/index.ts"}
+ return bf.PathMap(layout["main"], [layout["live"]], known)
+
+
+def test_paths_in_the_checkout_and_a_live_worktree_map(layout) -> None:
+ m = _map(layout)
+ assert m(f"{layout['main']}/src/ledger.py", "") == "src/ledger.py"
+ assert m(f"{layout['live']}/README.md", "") == "README.md"
+ # Windows separators and a path relative to the call's cwd.
+ assert m(layout["live"].replace("/", "\\") + "\\src\\ledger.py", "") == "src/ledger.py"
+ assert m("src\\ledger.py", layout["live"]) == "src/ledger.py"
+ assert m("../src/ledger.py", f"{layout['live']}/docs") == "src/ledger.py"
+
+
+def test_a_removed_worktree_maps_only_with_a_two_segment_path(layout) -> None:
+ m = _map(layout)
+ assert m(f"{layout['removed']}/src/ledger.py", "") == "src/ledger.py"
+ assert m(f"{layout['removed']}/README.md", "") is None
+
+
+def test_a_vanished_foreign_project_needs_a_longer_suffix(layout, tmp_path: Path) -> None:
+ """A deleted directory that is not beside a worktree may have been any project."""
+ m = _map(layout)
+ gone = str(tmp_path / "deleted-app").replace("\\", "/")
+ assert m(f"{gone}/src/index.ts", "") is None
+ assert m(f"{gone}/packages/app/index.ts", "") == "packages/app/index.ts"
+ # Inside a worktrees/ directory it is taken for one of ours.
+ old = str(tmp_path / "x" / "worktrees" / "old").replace("\\", "/")
+ assert m(f"{old}/src/index.ts", "") == "src/index.ts"
+
+
+def test_another_repo_and_a_sibling_repo_never_map(layout) -> None:
+ m = _map(layout)
+ assert m(f"{layout['other']}/src/ledger.py", "") is None
+ # backend/ is its own repo inside the checkout: backend/app/main.py is not ours.
+ assert m(f"{layout['main']}/backend/app/main.py", "") is None
+ assert m("src/ledger.py", "") is None # relative with no cwd
+
+
+def test_a_file_no_commit_touched_yet_maps_only_inside_our_own_tree(layout) -> None:
+ m = _map(layout)
+ assert m(f"{layout['live']}/src/new.py", "") == "src/new.py"
+ assert m(f"{layout['main']}/backend/app/new.py", "") is None # nested checkout
+ assert m(f"{layout['removed']}/src/new.py", "") is None
+ assert m(f"{layout['other']}/src/new.py", "") is None
+
+
+# --- end to end ------------------------------------------------------------------
+
+
+def _opt_in(repo, user_config: Path, agents: str = "[claude-code, codex]") -> None:
+ cfg = f"attribution:\n capture: local\n agents: {agents}\n"
+ repo.configure(cfg)
+ user_config.write_text(cfg, encoding="utf-8")
+
+
+def test_consent_needs_capture_and_the_agent_in_both_configs(repo, user_config, monkeypatch) -> None:
+ assert bf.consent(repo.root, ["claude-code"])[0] == []
+ _opt_in(repo, user_config, "[codex]")
+ allowed, refused = bf.consent(repo.root, ["claude-code", "codex", "cursor"])
+ assert allowed == ["codex"]
+ assert "attribution.agents" in refused["claude-code"] and "transcript" in refused["cursor"]
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ assert bf.consent(repo.root, ["codex"])[0] == []
+
+
+def scene(repo, user_config, tmp_path: Path):
+ """A repo with a live worktree, Claude and Codex transcripts, and one commit."""
+ _opt_in(repo, user_config)
+ wt = (tmp_path / "wt-feature").resolve()
+ repo.git("worktree", "add", "-q", "-b", "feature", str(wt))
+ now = time.time()
+ claude_root, codex_root = tmp_path / "claude", tmp_path / "codex"
+
+ main = ClaudeTranscript(claude_root / "C--repo" / "s1.jsonl", str(wt))
+ main.call("Write", {"file_path": str(wt / "src" / "taxes.py"), "content": "\n".join(TAXES) + "\n"},
+ now - 3 * 3600, result={"type": "create", "filePath": "x", "content": "", "structuredPatch": []})
+ # MultiEdit with CRLF replacements (a Windows agent): hashes like the LF commit.
+ main.call("MultiEdit", {"file_path": str(wt / "src" / "report.py"),
+ "edits": [{"old_string": "", "new_string": "\r\n".join(REPORT[:2])},
+ {"old_string": "pass", "new_string": "\r\n".join(REPORT[2:])}]},
+ now - 2 * 3600, result={"filePath": "x"})
+ # Made 20 days before the commit: outside the window.
+ main.call("Edit", {"file_path": str(wt / "src" / "old.py"), "old_string": "a", "new_string": "\n".join(OLD)},
+ now - 20 * DAY, result={"filePath": "x"})
+ # A failed edit wrote nothing.
+ main.call("Edit", {"file_path": str(wt / "src" / "err.py"), "old_string": "a", "new_string": "\n".join(ERR)},
+ now - 3600, result="Error: File has not been read yet.", error=True)
+ main.write()
+ # A subagent transcript: no toolUseResult, so a Write is a create only by its result text.
+ sub = ClaudeTranscript(claude_root / "C--repo" / "s1" / "subagents" / "agent-1.jsonl", str(wt), subagent=True)
+ sub.call("Write", {"file_path": str(wt / "src" / "sub.py"), "content": "\n".join(SUB)},
+ now - 3600, text=f"File created successfully at: {wt / 'src' / 'sub.py'}")
+ sub.write()
+ _codex_rollout(codex_root, wt, now - 3600)
+
+ for rel, body in {
+ "src/taxes.py": TAXES, "src/report.py": REPORT, "src/ledger.py": LEDGER,
+ "src/old.py": OLD, "src/err.py": ERR, "src/sub.py": SUB,
+ }.items():
+ repo.write(rel, "\n".join(body) + "\n")
+ sha = repo.commit("work")
+ roots = {"claude-code": claude_root, "codex": codex_root}
+ return repo, sha, roots
+
+
+def test_backfill_binds_edits_from_both_agents_and_skips_what_did_not_land(scene) -> None:
+ repo, sha, roots = scene
+ result = bf.backfill(repo.root, ["claude-code", "codex"], capture="local", projects_roots=roots)
+ assert result.transcripts == {"claude-code": 2, "codex": 1}
+ (binding,) = result.bindings
+ assert binding["commit"] == sha
+ files = {p for s in binding["sessions"] for p in s["files"]}
+ # Write create, MultiEdit, subagent Write create, Codex exec-cell patch.
+ assert files == {"src/taxes.py", "src/report.py", "src/sub.py", "src/ledger.py"}
+ by_agent = {s["agent"] for s in binding["sessions"]}
+ assert by_agent == {"claude_code", "codex"}
+ assert any(s["model"] == "gpt-5.5-codex" for s in binding["sessions"] if s["agent"] == "codex")
+ assert result.covered_before == 0 and result.covered_after == 1
+
+
+def test_backfill_records_its_run_and_reads_only_new_lines_next_time(scene) -> None:
+ repo, sha, roots = scene
+ bf.backfill(repo.root, ["claude-code", "codex"], capture="local", projects_roots=roots)
+ state = load_state(repo.root)
+ assert state["backfill"]["bound"] == 1 and state["cursor"] == sha
+ cursors = json.loads((sidecar_dir(repo.root) / bf.CURSORS).read_text(encoding="utf-8"))
+ assert all(c["offset"] == Path(f).stat().st_size for f, c in cursors.items())
+ again = bf.backfill(repo.root, ["claude-code", "codex"], capture="local", projects_roots=roots)
+ assert again.edits == 0 and again.bindings == []
+ # One line appended: the next run reads that edit and nothing before it.
+ t = ClaudeTranscript(roots["claude-code"] / "C--repo" / "s1.jsonl", str(repo.root))
+ t.n = 100
+ t.call("Write", {"file_path": str(repo.root / "src" / "next.py"), "content": "\n".join(LATER)},
+ time.time() - 60, result={"type": "create"})
+ with open(t.path, "a", encoding="utf-8") as handle:
+ handle.write("".join(json.dumps(x) + "\n" for x in t.lines))
+ third = bf.backfill(repo.root, ["claude-code"], capture="local", projects_roots=roots)
+ assert third.edits == 1
+
+
+def test_backfill_leaves_the_live_cursor_for_waiting_hook_events(scene) -> None:
+ repo, _, roots = scene
+ live = _body("live", 3)
+ call = CapturedCall(tool="Edit", edits=[FileEdit("src/live.py", live)], session_id="h", cwd=str(repo.root))
+ assert record_call(repo.root, "claude_code", call) == 1
+ repo.write("src/live.py", "\n".join(live) + "\n")
+ live_sha = repo.commit("live work")
+ bf.backfill(repo.root, ["claude-code", "codex"], capture="local", projects_roots=roots)
+ assert "cursor" not in load_state(repo.root)
+ assert [b["commit"] for b in bind_pending(repo.root, capture="local")] == [live_sha]
+
+
+def test_edits_outside_any_path_of_the_repo_are_dropped_as_read(layout, tmp_path: Path) -> None:
+ path = tmp_path / "t.jsonl"
+ t = ClaudeTranscript(path, layout["other"])
+ for name in ("ours", "theirs"):
+ rel = "src/ledger.py" if name == "ours" else "lib/elsewhere.py"
+ t.call("Write", {"file_path": f"{layout['main']}/{rel}" if name == "ours" else f"{layout['other']}/{rel}",
+ "content": "\n".join(_body(name))}, time.time(), result={"type": "create"})
+ t.write()
+ adapter = get_adapter("claude_code")
+ recorder = bf.TranscriptEditRecorder(keep=_map(layout))
+ for _ in recorder.observe(adapter, "claude_code", adapter.iter_events(path)):
+ pass
+ assert recorder.edits == 2 and [r["path"] for r, _ in recorder._rows] == [f"{layout['main']}/src/ledger.py"]
+
+
+def test_unbound_recent_edits_wait_for_the_next_commit(scene, tmp_path: Path) -> None:
+ repo, _, roots = scene
+ t = ClaudeTranscript(roots["claude-code"] / "C--repo" / "s2.jsonl", str(repo.root))
+ t.call("Write", {"file_path": str(repo.root / "src" / "later.py"),
+ "content": "\n".join(LATER)},
+ time.time() - 60, result={"type": "create"})
+ t.write()
+ result = bf.backfill(repo.root, ["claude-code"], capture="local", projects_roots=roots)
+ pending = read_jsonl(sidecar_dir(repo.root) / EVENTS)
+ assert result.handed_over == len(pending) and {r["path"] for r in pending} >= {"src/later.py"}
+ assert all(set(r) >= {"hashes", "agent", "ts", "path"} and "content" not in r for r in pending)
+
+
+def test_backfill_holds_a_run_below_the_minimum(repo, user_config, tmp_path: Path) -> None:
+ _opt_in(repo, user_config)
+ short = _body("short", bf.MIN_RUN_BACKFILL - 1)
+ t = ClaudeTranscript(tmp_path / "claude" / "p" / "s.jsonl", str(repo.root))
+ t.call("Write", {"file_path": str(repo.root / "a.py"), "content": "\n".join(short)}, time.time() - 600,
+ result={"type": "create"})
+ t.write()
+ repo.write("a.py", "\n".join(short) + "\n")
+ repo.commit("short run")
+ result = bf.backfill(repo.root, ["claude-code"], capture="local", projects_roots={"claude-code": tmp_path / "claude"})
+ assert result.bindings == []