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): opt-in edit capture for Claude Code, Codex and Cursor (#3744)

Raghav Chamadiya8585ce1e24bb
diff --git a/docs/agent/INTEGRATIONS.md b/docs/agent/INTEGRATIONS.md
index ff24316b8..1c370ef52 100644
--- a/docs/agent/INTEGRATIONS.md
+++ b/docs/agent/INTEGRATIONS.md
@@ -27,16 +27,21 @@ for that agent. `Indexing` is `Yes` when the agent's own CLI can run as the
LLM that writes the index, selected by its provider id (`claude_cli`, for
example). It is separate from the tier: it says nothing about the session.
-| Agent | Tier | MCP | Hooks | Skills | Commands | Instructions | Transcripts | Indexing |
-|---|---|---|---|---|---|---|---|---|
-| [Claude Code](https://docs.claude.com/en/docs/claude-code) | Full | Yes | Yes | Plugin | Plugin | Yes | Yes | Yes |
-| [Codex CLI](https://developers.openai.com/codex/cli) | Full | Yes | Yes | Plugin | Yes | Yes | Yes | Yes |
-| [VS Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) | Good | Yes | No | No | No | Yes | No | No |
-| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | Yes | No | No | Yes | No | No |
-| [OpenCode](https://opencode.ai/docs/mcp-servers/) | Good | Yes | No | No | No | Yes | No | Yes |
-| [Hermes](https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp) | Good | Yes | No | No | No | Yes | No | No |
-| [GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference) | Good | Yes | No | No | No | Yes | No | No |
-| [Kiro](https://kiro.dev/docs/mcp/configuration) | Good | Yes | No | No | No | Yes | No | No |
+`Attribution` is `Yes` when repowise can record the agent's edits as they
+happen, an opt-in set by `attribution.capture` and `attribution.agents`. Every
+agent's own git-ai notes, Agent Trace files and commit trailers are read
+either way.
+
+| Agent | Tier | MCP | Hooks | Skills | Commands | Instructions | Transcripts | Indexing | Attribution |
+|---|---|---|---|---|---|---|---|---|---|
+| [Claude Code](https://docs.claude.com/en/docs/claude-code) | Full | Yes | Yes | Plugin | Plugin | Yes | Yes | Yes | Yes |
+| [Codex CLI](https://developers.openai.com/codex/cli) | Full | Yes | Yes | Plugin | Yes | Yes | Yes | Yes | Yes |
+| [VS Code](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) | Good | Yes | No | No | No | Yes | No | No | No |
+| [Cursor](https://cursor.com/docs/context/mcp) | Good | Yes | Yes | No | No | Yes | No | No | Yes |
+| [OpenCode](https://opencode.ai/docs/mcp-servers/) | Good | Yes | No | No | No | Yes | No | Yes | No |
+| [Hermes](https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp) | Good | Yes | No | No | No | Yes | No | No | No |
+| [GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference) | Good | Yes | No | No | No | Yes | No | No | No |
+| [Kiro](https://kiro.dev/docs/mcp/configuration) | Good | Yes | No | No | No | Yes | No | No | No |
Target ids for `--target=`: `claude-code`, `codex`, `vscode`, `cursor`, `opencode`, `hermes`, `copilot`, `kiro`.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index dc3ab12db..2b741268f 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2234,11 +2234,11 @@ 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, for which agents, coverage
-repowise attribution purge [PATH] [--yes] # delete attribution derived into the local index
+repowise attribution status [PATH] [--format json] # what is on, capture per agent, coverage
+repowise attribution purge [PATH] [--yes] # delete derived attribution, captured edits and our notes
```
-`purge` leaves git history, trailers and notes in the repository as they are.
+`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 2e7ba95dd..877d81201 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -599,6 +599,8 @@ 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.
+With `capture: local` the edit hooks of the listed agents (those with `Yes` under Attribution in [INTEGRATIONS.md](../agent/INTEGRATIONS.md)) record which lines the agent wrote, as hashes with the file, session and model, in `.repowise/attribution/`; prompts and code are never stored. `repowise update` matches them to new commits by content and labels a matched commit with the agent; an unmatched commit stays unknown. `capture: notes` also writes a git-ai v3 note on `refs/notes/ai` and sets `notes.rewriteRef` so the note follows a local amend or rebase; teammates see notes once you `git push origin refs/notes/ai` and add the fetch refspec `repowise doctor` names. Cursor records edits through an `afterFileEdit` hook, which `repowise agents add --target=cursor --scope=user` adds once your user config captures Cursor.
+
### The `refactoring:` block
Controls the refactoring-intelligence layer: the structured Extract Class /
diff --git a/packages/cli/src/repowise/cli/agent_adapters/cursor.py b/packages/cli/src/repowise/cli/agent_adapters/cursor.py
index 11c0b6d9b..ed9d54255 100644
--- a/packages/cli/src/repowise/cli/agent_adapters/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_adapters/cursor.py
@@ -207,11 +207,14 @@ def uninstall_cursor_rewrite_hook() -> bool:
hooks[event] = kept
else:
hooks.pop(event)
- if not changed:
- return False
+ return changed and _save_or_remove(path, doc)
+
+
+def _save_or_remove(path: Path, doc: dict) -> bool:
+ """Write *doc* back after removing our entry; True unless the write failed."""
try:
# A file holding nothing but our entry was ours; leave no stub behind.
- if not hooks and set(doc) <= {"version", "hooks"}:
+ if not doc["hooks"] and set(doc) <= {"version", "hooks"}:
path.unlink()
else:
_write(path, doc)
@@ -238,3 +241,90 @@ def cursor_rewrite_hook_matcher() -> str | None:
matcher = entry.get("matcher")
return matcher if isinstance(matcher, str) else ""
return None
+
+
+# ---------------------------------------------------------------------------
+# Opt-in edit capture: ``afterFileEdit`` in ~/.cursor/hooks.json.
+# ---------------------------------------------------------------------------
+
+_CAPTURE_EVENT = "afterFileEdit"
+_CAPTURE_HOOK_ENTRY = {"command": "repowise augment --client cursor", "timeout": 5}
+
+
+def _is_capture_hook(entry: object) -> bool:
+ if not isinstance(entry, dict):
+ return False
+ command = entry.get("command")
+ if not isinstance(command, str):
+ return False
+ parts = command.replace("\\", "/").split()
+ if len(parts) < 2:
+ return False
+ exe = parts[0].strip("\"'").rsplit("/", 1)[-1].lower().removesuffix(".exe")
+ return exe == "repowise" and parts[1] == "augment"
+
+
+def _load_hooks_doc(path: Path) -> dict | None:
+ """The hooks file, ``{}`` when absent, None when unreadable or not a JSON object."""
+ from click import ClickException
+
+ if not path.exists():
+ return {}
+ try:
+ return _load(path)
+ except ClickException:
+ return None
+
+
+def _capture_entries(doc: dict | None) -> list | None:
+ hooks = doc.get("hooks") if doc else None
+ entries = hooks.get(_CAPTURE_EVENT) if isinstance(hooks, dict) else None
+ return entries if isinstance(entries, list) else None
+
+
+def cursor_capture_hook_installed() -> bool:
+ entries = _capture_entries(_load_hooks_doc(user_hooks_path()))
+ return entries is not None and any(_is_capture_hook(e) for e in entries)
+
+
+def install_cursor_capture_hook() -> Path | None:
+ """Register the capture entry under ``afterFileEdit``; the path, or None on failure.
+
+ Only written once the user has opted Cursor into capture: Cursor starts a
+ process per agent file edit, which nobody should pay for a feature they
+ have not turned on. A hooks file of another shape is left alone.
+ """
+ path = user_hooks_path()
+ doc = _load_hooks_doc(path)
+ hooks = doc.setdefault("hooks", {}) if doc is not None else None
+ entries = hooks.setdefault(_CAPTURE_EVENT, []) if isinstance(hooks, dict) else None
+ if doc is None or not isinstance(entries, list):
+ return None
+ if any(_is_capture_hook(entry) for entry in entries):
+ return path
+ doc.setdefault("version", 1)
+ entries.append(dict(_CAPTURE_HOOK_ENTRY))
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _write(path, doc)
+ except OSError:
+ return None
+ return path
+
+
+def uninstall_cursor_capture_hook() -> bool:
+ """Remove our ``afterFileEdit`` entry; True when the file changed."""
+ path = user_hooks_path()
+ doc = _load_hooks_doc(path)
+ entries = _capture_entries(doc)
+ if doc is None or entries is None:
+ return False
+ kept = [entry for entry in entries if not _is_capture_hook(entry)]
+ if len(kept) == len(entries):
+ return False
+ hooks = doc["hooks"]
+ if kept:
+ hooks[_CAPTURE_EVENT] = kept
+ else:
+ hooks.pop(_CAPTURE_EVENT)
+ return _save_or_remove(path, doc)
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index fc21af9b4..24b344153 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -364,6 +364,7 @@ class ClaudeCodeTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index d8ea23fc6..9502575d4 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -983,6 +983,7 @@ class CodexTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/copilot.py b/packages/cli/src/repowise/cli/agent_targets/targets/copilot.py
index a6754d1f6..4c6c80ab2 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/copilot.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/copilot.py
@@ -172,6 +172,7 @@ class CopilotTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
index 01fae5664..6f32fc8be 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -339,6 +339,41 @@ def _install_rewrite_hook(result: WriteResult) -> WriteResult:
return result
+def user_opted_into_capture() -> bool:
+ """Whether the user config captures Cursor's edits (``attribution`` block).
+
+ Read from the user layer because the hook file is per user; each repo still
+ has to opt in before an edit there is recorded.
+ """
+ from repowise.core.attribution import load_attribution_settings
+
+ settings = load_attribution_settings(None)
+ user = settings.user
+ return (
+ not settings.do_not_track
+ and user.enabled is not False
+ and user.capture in ("local", "notes")
+ and ID in (user.agents or ())
+ )
+
+
+def _install_capture_hook(result: WriteResult) -> WriteResult:
+ """Add the ``afterFileEdit`` capture entry, only for a user who opted in."""
+ from repowise.cli.agent_adapters.cursor import install_cursor_capture_hook, user_hooks_path
+
+ from ..formats.observe import observed_action, read_bytes
+
+ if not user_opted_into_capture():
+ return result
+ hooks_path = user_hooks_path()
+ before = read_bytes(hooks_path)
+ if install_cursor_capture_hook():
+ result.record(hooks_path, observed_action(before, read_bytes(hooks_path)))
+ else:
+ result.record(hooks_path, FileAction.KEPT, "not valid JSON, or could not be written")
+ return result
+
+
def cursor_rewrite_hook_present() -> bool:
"""Our entry is registered, or the file is unreadable and still names it."""
from repowise.cli.agent_adapters.cursor import cursor_rewrite_hook_matcher, user_hooks_path
@@ -394,6 +429,7 @@ class CursorTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
@@ -427,7 +463,7 @@ class CursorTarget:
) -> WriteResult:
result = WriteResult()
if scope is Scope.USER:
- return _install_rewrite_hook(result)
+ return _install_capture_hook(_install_rewrite_hook(result))
if repo_path is None:
raise ValueError("project-scope install needs a repo_path")
@@ -495,10 +531,12 @@ class CursorTarget:
result = WriteResult()
if scope is Scope.USER:
from repowise.cli.agent_adapters.cursor import (
+ uninstall_cursor_capture_hook,
uninstall_cursor_rewrite_hook,
user_hooks_path,
)
+ uninstall_cursor_capture_hook()
removed = uninstall_cursor_rewrite_hook()
# Asked of the file, not the boolean, which is also False for "could
# not parse" and "write failed".
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
index 9a4375001..6eacce5f6 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
@@ -806,6 +806,7 @@ class HermesTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/kiro.py b/packages/cli/src/repowise/cli/agent_targets/targets/kiro.py
index 5ded27a59..85b5bee78 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/kiro.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/kiro.py
@@ -206,6 +206,7 @@ class KiroTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
index 1df076d56..f611507ac 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
@@ -591,6 +591,7 @@ class OpenCodeTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
index a03257e6a..620193935 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -333,6 +333,7 @@ class VSCodeTarget:
docs_url = DOCS_URL
hook_adapter = IDENTITY.hook_adapter
session_adapter = IDENTITY.session_adapter
+ capture_adapter = IDENTITY.capture_adapter
methods = METHODS
project_file_id = PROJECT_FILE_ID
diff --git a/packages/cli/src/repowise/cli/agent_targets/types.py b/packages/cli/src/repowise/cli/agent_targets/types.py
index 7180a130b..69c11feac 100644
--- a/packages/cli/src/repowise/cli/agent_targets/types.py
+++ b/packages/cli/src/repowise/cli/agent_targets/types.py
@@ -293,6 +293,12 @@ class AgentTarget(Protocol):
#: out of the Full tier.
hook_adapter: str | None
session_adapter: str | None
+ #: Named entry in ``core.edit_capture.edits``: turns this agent's edit hook
+ #: payload into an edit event for opt-in AI attribution. ``None`` means its
+ #: edits are attributed only through the markers it leaves in git (git-ai
+ #: notes, Agent Trace files, trailers). Not a tier input: capture is off
+ #: unless the user turns it on, so it adds no depth the agent always gets.
+ capture_adapter: str | None
#: Routes this target can be wired through, in preference order.
methods: tuple[InstallMethod, ...]
diff --git a/packages/cli/src/repowise/cli/commands/attribution_cmd.py b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
index e77fc0cc8..0157e382c 100644
--- a/packages/cli/src/repowise/cli/commands/attribution_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
@@ -2,9 +2,9 @@
``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. ``purge`` deletes the attribution the local index derived. Capture is
-not wired yet, so there is no sidecar, cursor or Repowise-written note to
-remove; third-party git-ai notes are never touched.
+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.
"""
from __future__ import annotations
@@ -50,6 +50,23 @@ async def _label_counts(repo_path: Path) -> dict[str, int] | None:
_DEFAULTS: dict[str, Any] = {"enabled": True, "capture": "off", "agents": ()}
+def _capture_by_agent(settings: Any) -> dict[str, str]:
+ """Per agent target: its capture level here, or why it is not captured."""
+ from repowise.cli.agent_targets.registry import all_targets
+
+ out: dict[str, str] = {}
+ for target in all_targets():
+ if target.capture_adapter is None:
+ out[target.id] = "no capture adapter (git markers only)"
+ elif settings.capture == "off":
+ out[target.id] = "off"
+ elif target.id not in settings.agents:
+ out[target.id] = "off (not in attribution.agents)"
+ else:
+ out[target.id] = settings.capture
+ return out
+
+
def _fmt(value: Any) -> str:
if isinstance(value, (tuple, list)):
return ", ".join(value) or "none"
@@ -121,9 +138,15 @@ def attribution_status(path: str | None, fmt: str) -> None:
if counts is not None
else None
)
+ from repowise.core.edit_capture.store import summary as capture_summary
+
+ capture = _capture_by_agent(settings)
+ sidecar = capture_summary(repo_path)
if fmt == "json":
emit_json(
{
+ "capture_by_agent": capture,
+ "capture_sidecar": sidecar,
"effective": {
"enabled": settings.enabled,
"capture": settings.capture,
@@ -141,11 +164,17 @@ def attribution_status(path: str | None, fmt: str) -> None:
}
)
return
+ console.print("[bold]AI attribution[/bold]")
+ _print_settings(settings)
+ _print_capture(capture, sidecar)
+ _print_commits(settings, counts, share)
- def _show(value: Any) -> str:
- return "[dim]unset[/dim]" if value is None else _fmt(value)
- console.print("[bold]AI attribution[/bold]")
+def _show(value: Any) -> str:
+ return "[dim]unset[/dim]" if value is None else _fmt(value)
+
+
+def _print_settings(settings: Any) -> None:
for key in ("enabled", "capture", "agents"):
console.print(
f" {key:<8} {_show(getattr(settings, key))}"
@@ -158,6 +187,27 @@ def attribution_status(path: str | None, fmt: str) -> None:
console.print(f" [yellow]![/yellow] {error} (treated as the strictest value)")
for reason in _explanations(settings):
console.print(f" [dim]{reason}[/dim]")
+
+
+def _print_capture(capture: dict[str, str], sidecar: dict[str, int]) -> None:
+ for target_id, level in capture.items():
+ console.print(f" capture {target_id:<12} {level}")
+ if capture.get("cursor") in ("local", "notes"):
+ from repowise.cli.agent_adapters.cursor import cursor_capture_hook_installed
+
+ if not cursor_capture_hook_installed():
+ console.print(
+ " [yellow]![/yellow] Cursor capture needs its afterFileEdit hook: run"
+ " 'repowise agents add --target=cursor --scope=user'"
+ )
+ if any(sidecar.values()):
+ console.print(
+ f" sidecar {sidecar['pending_events']} pending edit events,"
+ f" {sidecar['bound_commits']} bound commits, {sidecar['notes_written']} notes written"
+ )
+
+
+def _print_commits(settings: Any, counts: dict[str, int] | None, share: Any) -> None:
if not settings.enabled:
console.print(" Nothing about AI is stored or shown for this repository.")
elif counts is None:
@@ -182,23 +232,42 @@ async def _purge(repo_path: Path) -> bool:
return True
+def _purge_capture(repo_path: Path) -> tuple[int, bool]:
+ """Remove our notes, then the sidecar that names them: ``(notes, sidecar)``."""
+ from repowise.core.edit_capture.notes import purge_notes
+ from repowise.core.edit_capture.store import delete_sidecar
+
+ notes = purge_notes(repo_path)
+ return notes, delete_sidecar(repo_path)
+
+
@attribution_group.command(name="purge")
@click.argument("path", required=False, type=click.Path(exists=True, file_okay=False))
@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.")
def attribution_purge(path: str | None, yes: bool) -> None:
- """Delete the AI attribution derived into the local index.
+ """Delete the AI attribution derived into the local index and captured here.
- Clears every commit label and file rollup. Git history, trailers and notes
- in the repository are left as they are.
+ Clears every commit label and file rollup, the edit-capture sidecar under
+ .repowise/attribution/ and the git-ai notes Repowise wrote. Git history,
+ trailers and notes written by anything else are left as they are.
"""
repo_path = resolve_repo_path(path)
if not yes and not click.confirm(
- "Delete all AI attribution derived into this repository's index?", default=False
+ "Delete all AI attribution derived into this repository's index and captured here?",
+ default=False,
):
console.print("Nothing deleted.")
return
+ notes, sidecar = _purge_capture(repo_path)
+ if sidecar:
+ console.print("[green]✓[/green] Edit-capture sidecar deleted.")
+ if notes:
+ console.print(
+ f"[green]✓[/green] {notes} git-ai note(s) Repowise wrote removed locally."
+ " Repowise never pushes, so notes you already pushed stay on the remote."
+ )
if not run_async(_purge(repo_path)):
- console.print("No index found; nothing to delete.")
+ console.print("No index found; nothing else to delete.")
return
console.print("[green]✓[/green] AI attribution deleted from the local index.")
if _settings(repo_path).enabled:
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index 332eee5ac..bce47964f 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -69,6 +69,10 @@ registers it any more — see :mod:`.codex`.)
decision, strictly capped); Codex lifecycle hooks instead get the
index-staleness reminder below.
+ PostToolUse → edit tools, Cursor afterFileEdit
+ * Opt-in edit capture (``attribution.capture``): the lines the agent
+ wrote, as hashes, in a local sidecar. Silent; see :mod:`.edit_capture`.
+
PostToolUse → edit tools (Codex)
* After file edits, emit a short reminder that the indexed context may
be stale.
@@ -111,6 +115,7 @@ from .bash_staleness import _handle_bash_post
from .codex import _handle_codex_context_event, _handle_post_edit_use
from .coverage_reingest import coverage_reingest_notice
from .decision_capture import commit_capture_notice
+from .edit_capture import capture_edit
from .read_state import _handle_edit_post, _handle_read_post, _record_edit
from .search import _handle_search_post
from .served_reads import _handle_mcp_read_post, _log_read_after_served
@@ -144,9 +149,9 @@ def _adapter(client: str | None):
@click.command("augment")
@click.option(
"--client",
- type=click.Choice(["codex"]),
+ type=click.Choice(["codex", "cursor"]),
default=None,
- help="Hook client marker. Codex lifecycle hooks pass this explicitly.",
+ help="Hook client marker. Codex and Cursor hooks pass this explicitly.",
)
@click.option(
"--coverage-only",
@@ -195,6 +200,15 @@ def _run_augment(*, client: str | None = None, coverage_only: bool = False) -> N
_run_coverage_only(payload, client)
return
+ # Opt-in edit capture for AI attribution. First, so a slow enrichment
+ # below cannot cost an event; it returns at once when capture is off.
+ if event == "afterFileEdit" or (
+ event == "PostToolUse" and tool_name in _adapter(client).edit_tool_names
+ ):
+ capture_edit(_adapter(client).name, payload)
+ if event == "afterFileEdit":
+ return
+
if client == "codex" and event in ("SessionStart", "UserPromptSubmit"):
session_id = payload.get("session_id", "")
session_id = session_id if isinstance(session_id, str) else ""
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/edit_capture.py b/packages/cli/src/repowise/cli/commands/augment_cmd/edit_capture.py
new file mode 100644
index 000000000..9a9a58b5d
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/edit_capture.py
@@ -0,0 +1,53 @@
+"""Edit-time AI attribution: record an agent's edit as line hashes, when opted in.
+
+The consent gate runs before the payload is parsed for edits, and it is cheap
+when capture is off (see :func:`repowise.core.edit_capture.store.capture_level`),
+because this runs on every hooked edit of every user. Nothing is emitted to the
+agent; the event lands in ``.repowise/attribution/events.jsonl`` and
+``repowise update`` binds it to a commit.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from ._shared import _find_repo_root
+
+
+def _payload_cwd(payload: dict) -> str:
+ cwd = payload.get("cwd")
+ if isinstance(cwd, str) and cwd:
+ return cwd
+ roots = payload.get("workspace_roots")
+ if isinstance(roots, list):
+ return next((r for r in roots if isinstance(r, str) and r), "")
+ return ""
+
+
+def capture_edit(hook_adapter: str, payload: dict) -> int:
+ """Record *payload*'s edits for the agent behind *hook_adapter*.
+
+ Returns the number of events written (0 when capture is off for it, or
+ when the repo or sidecar cannot be read or written). Anything else is a
+ bug and reaches the hook's top-level guard.
+ """
+ try:
+ from repowise.core.agents.identity import get_identity, slug_for_hook_adapter
+
+ identity = get_identity(slug_for_hook_adapter(hook_adapter))
+ if identity is None or identity.capture_adapter is None:
+ return 0
+ cwd = _payload_cwd(payload)
+ repo_root = _find_repo_root(Path(cwd)) if cwd else None
+ if repo_root is None:
+ return 0
+ from repowise.core.edit_capture.store import capture_level, record_call
+
+ if capture_level(repo_root, identity.slug) == "off":
+ return 0
+ from repowise.core.edit_capture.edits import CAPTURE_ADAPTERS
+
+ call = CAPTURE_ADAPTERS[identity.capture_adapter](payload)
+ return record_call(repo_root, identity.slug, call) if call is not None else 0
+ except (OSError, RuntimeError, ValueError):
+ return 0
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 131aa6bc9..d50aee902 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -241,6 +241,41 @@ def _autosync_hook_check(repo_path: _DoctorPath) -> DoctorCheck:
return _check("Post-commit hook", True, state)
+def _attribution_notes_check(repo_path: _DoctorPath) -> DoctorCheck | None:
+ """At ``attribution.capture: notes``, whether notes travel with the repo.
+
+ None at every other level. Notes reach teammates only through a fetch
+ refspec and an explicit push, and survive a rebase only via
+ ``notes.rewriteRef``; without them coverage is silently low elsewhere.
+ """
+ name = "Attribution notes"
+ try:
+ from repowise.core.attribution import load_attribution_settings
+
+ if load_attribution_settings(repo_path).capture != "notes":
+ return None
+ from repowise.core.edit_capture.notes import FETCH_REFSPEC, NOTES_REF, refspec_status
+
+ status = refspec_status(_DoctorPath(repo_path))
+ except OSError as exc:
+ return _check(name, True, f"could not read git config ({exc})")
+ if not status["remote"]:
+ return _check(name, True, "no origin remote, so notes stay on this machine")
+ push = (
+ "push refspec set"
+ if status["push"]
+ else f"share them with 'git push origin {NOTES_REF}'"
+ )
+ problems = []
+ if not status["fetch"]:
+ problems.append(f"run 'git config --add remote.origin.fetch \"{FETCH_REFSPEC}\"'")
+ if not status["rewrite_ref"]:
+ problems.append(f"run 'git config --add notes.rewriteRef {NOTES_REF}'")
+ if problems:
+ return _check(name, False, "; ".join([*problems, push]))
+ return _check(name, True, f"fetch refspec and notes.rewriteRef set; {push}")
+
+
def _run_repo_checks(
repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"
) -> tuple[bool, list[DoctorCheck]]:
@@ -272,6 +307,9 @@ def _run_repo_checks(
# 2b. Post-commit auto-sync hook. init installs it by default; not having
# it is a choice (--no-hook), so its absence is informational, not a fail.
checks.append(_autosync_hook_check(repo_path))
+ notes_check = _attribution_notes_check(repo_path)
+ if notes_check is not None:
+ checks.append(notes_check)
# 3. Database connectable?
db_path = repowise_dir / "wiki.db"
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 0c0aa66d1..78805f94e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -9,6 +9,7 @@ rendering (:mod:`.reporting`).
from __future__ import annotations
+import contextlib
import sys
import time
from collections.abc import Callable
@@ -1092,6 +1093,12 @@ def run_update(
# it must not wait on a re-score (7-day decay) or cost an indexing run.
if not dry_run:
_repair_module_attribution(repo_path)
+ # Opt-in edit capture: bind pending agent edits to the new commits
+ # before the git walk labels them. A no-op unless capture is on.
+ with contextlib.suppress(Exception):
+ from repowise.core.edit_capture.binder import bind_repo
+
+ bind_repo(Path(repo_path))
analyzer_changed = health_analyzer_changed(state)
# Stored per-file git rows written under older history rules. Only a full
diff --git a/packages/core/src/repowise/core/agents/identity.py b/packages/core/src/repowise/core/agents/identity.py
index b302d6d04..049fc1f7e 100644
--- a/packages/core/src/repowise/core/agents/identity.py
+++ b/packages/core/src/repowise/core/agents/identity.py
@@ -103,6 +103,10 @@ class AgentIdentity:
#: ``derive_tier`` reads them.
hook_adapter: str | None = None
session_adapter: str | None = None
+ #: Entry in ``core.edit_capture.edits``: hook payload to edit event, for
+ #: opt-in edit-time attribution. Declared for the same reason as the two
+ #: above; it does not move the tier.
+ capture_adapter: str | None = None
#: The agent's command on PATH, when it ships one.
executable: str | None = None
#: Arguments to ``executable`` that exit 0 only when signed in. Empty when
@@ -178,6 +182,7 @@ CLAUDE_CODE = AgentIdentity(
announced_as=frozenset({"claude"}),
hook_adapter="claude-code",
session_adapter="claude_code",
+ capture_adapter="claude_code",
executable="claude",
#: Documented to exit 0 when signed in and 1 when not.
login_check=("auth", "status"),
@@ -190,6 +195,7 @@ CODEX = AgentIdentity(
display_name="Codex CLI",
hook_adapter="codex",
session_adapter="codex",
+ capture_adapter="codex",
executable="codex",
login_check=("login", "status"),
install_hint="npm install -g @openai/codex",
@@ -201,6 +207,7 @@ CURSOR = AgentIdentity(
slug="cursor",
display_name="Cursor",
hook_adapter="cursor",
+ capture_adapter="cursor",
executable="cursor",
)
OPENCODE = AgentIdentity(
diff --git a/packages/core/src/repowise/core/edit_capture/__init__.py b/packages/core/src/repowise/core/edit_capture/__init__.py
new file mode 100644
index 000000000..9bd7ebe96
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/__init__.py
@@ -0,0 +1,17 @@
+"""Edit-time AI attribution: capture agent edits as hashes, bind them to commits.
+
+Opt-in (``attribution.capture``, see :mod:`repowise.core.attribution`). A hook
+records which lines an agent wrote as content hashes in a local sidecar under
+``.repowise/attribution/``; ``repowise update`` binds them to the commits that
+added those lines and, at ``capture: notes``, writes git-ai v3 notes. Prompts,
+code text and person identities are never stored.
+
+* :mod:`.hashing` - the one line-normalisation and hash function.
+* :mod:`.edits` - one edit extractor per agent, shared by the live hook and the
+ transcript adapters, plus the hook-payload capture adapters.
+* :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.
+
+Every module here is stdlib-only at import: the hook path imports it.
+"""
diff --git a/packages/core/src/repowise/core/edit_capture/binder.py b/packages/core/src/repowise/core/edit_capture/binder.py
new file mode 100644
index 000000000..376cb54fc
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/binder.py
@@ -0,0 +1,392 @@
+"""Bind pending edit events to the commits that added those lines.
+
+Runs from ``repowise update`` (which the post-commit hook already starts), over
+the commits since the last cursor that are newer than the oldest pending event,
+capped at :data:`MAX_COMMITS`. Never a full-history walk.
+
+The match is by content hash within a path, and every rule leans toward a miss:
+
+* An added line matches an event only in the same file (or the file git reports
+ it was renamed from), and only for events recorded before the commit.
+* A line whose hash two different agents claim is ambiguous and matches neither.
+* A line repeated :data:`BOILERPLATE_REPEAT` or more times among one file's
+ added lines in a commit is boilerplate and cannot anchor a match.
+* Matched lines bind only as a run of consecutive added lines from one agent
+ holding at least :data:`MIN_RUN_SUBSTANTIVE` substantive lines
+ (:func:`~repowise.core.edit_capture.hashing.is_substantive`). A one-line
+ agent edit is therefore a miss: measured precision first, recall later.
+* A bound hash is consumed, so the same text typed again later cannot bind twice.
+
+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.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import time
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from .edits import CapturedCall, FileEdit
+from .hashing import is_substantive, line_hash, opaque_id
+from .store import (
+ BINDINGS,
+ EVENT_TTL_SECONDS,
+ EVENTS,
+ append_jsonl,
+ bound_commits,
+ edit_event,
+ load_state,
+ read_jsonl,
+ save_state,
+ sidecar_dir,
+)
+
+MAX_COMMITS = 50
+MIN_RUN_SUBSTANTIVE = 2
+BOILERPLATE_REPEAT = 3
+#: An event may be stamped a little after the commit that contains it when the
+#: hook and ``git commit`` race; allow for that, no more.
+COMMIT_GRACE_SECONDS = 120
+
+#: git-ai's ``agent_id.tool`` names for our agent slugs; others pass through.
+_GIT_AI_TOOLS = {"claude_code": "claude"}
+
+_WORK = "events.binding.jsonl"
+_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
+_DIFF_RE = re.compile(r"^diff --git ", re.MULTILINE)
+
+
+def git_ai_tool(agent: str) -> str:
+ return _GIT_AI_TOOLS.get(agent, agent)
+
+
+def event_rows(
+ agent: str, call: CapturedCall, *, ts: float, repo_relative: list[str] | None = None
+) -> list[dict[str, Any]]:
+ """Event rows for *call*'s edits, the shape :func:`bind_pending` reads.
+
+ The live hook writes these through :func:`~.store.record_call`; a backfill
+ builds them in memory from transcript edits wrapped in a
+ :class:`~.edits.CapturedCall`. *repo_relative* gives each edit's
+ repo-relative path when the caller already resolved it.
+ """
+ paths = repo_relative or [edit.path for edit in call.edits]
+ return [
+ edit_event(agent, call, FileEdit(path, edit.added), ts)
+ for path, edit in zip(paths, call.edits, strict=True)
+ ]
+
+
+def _git(repo: Path, *args: str) -> str:
+ result = subprocess.run(
+ ["git", "-c", "core.quotepath=false", *args],
+ cwd=repo,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ return result.stdout if result.returncode == 0 else ""
+
+
+def commit_diff(repo: Path, sha: str) -> tuple[int, list[tuple[str, str | None, list[tuple[int, list[str]]]]]]:
+ """``(commit time, [(path, renamed_from, [(first_line, added_lines)])])``."""
+ out = _git(
+ repo, "diff-tree", "-p", "-M", "--unified=0", "--no-color", "--no-ext-diff",
+ "--root", "--format=%ct", sha,
+ )
+ head, _, body = out.partition("\n")
+ try:
+ ct = int(head.strip())
+ except ValueError:
+ return 0, []
+ parsed = (_file_diff(chunk) for chunk in _DIFF_RE.split(body)[1:])
+ return ct, [entry for entry in parsed if entry is not None]
+
+
+def _file_diff(chunk: str) -> tuple[str, str | None, list[tuple[int, list[str]]]] | None:
+ """``(path, renamed_from, hunks)`` of one file's diff; None without hunks."""
+ header, sep, rest = chunk.partition("\n@@")
+ path, old = _file_header(header)
+ hunks = _added_hunks(f"@@{rest}".split("\n")) if sep else []
+ if path is None or not hunks:
+ return None
+ return path, old, [h for h in hunks if h[1]]
+
+
+def _file_header(header: str) -> tuple[str | None, str | None]:
+ """``(new path, renamed_from)``; the path is None for a deleted file."""
+ path: str | None = None
+ old: str | None = None
+ for line in header.split("\n"):
+ if line.startswith("rename from "):
+ old = line[len("rename from ") :]
+ elif line.startswith("+++ "):
+ target = line[4:].rstrip("\t")
+ path = target[2:] if target.startswith("b/") else None
+ return path, old
+
+
+def _added_hunks(lines: list[str]) -> list[tuple[int, list[str]]]:
+ """``(first new line, added lines)`` per ``@@`` hunk header of *lines*."""
+ hunks: list[tuple[int, list[str]]] = []
+ in_hunk = False
+ for line in lines:
+ if line.startswith("@@"):
+ match = _HUNK_RE.match(line)
+ in_hunk = match is not None
+ if match:
+ hunks.append((int(match.group(1)), []))
+ elif in_hunk and line.startswith("+"):
+ hunks[-1][1].append(line[1:])
+ return hunks
+
+
+def _sole_owner(rows: list[dict[str, Any]], owners: list[int]) -> tuple[str, int] | None:
+ """``(agent, latest row index)`` when one agent claims a hash; None if none or several."""
+ agents = {rows[i]["agent"] for i in owners}
+ if len(agents) != 1:
+ return None
+ 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*."""
+ 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 h in row["hashes"]:
+ by_hash.setdefault(h, []).append(idx)
+ return by_hash
+
+
+def _match_file(
+ rows: list[dict[str, Any]],
+ by_hash: dict[str, list[int]],
+ hunks: list[tuple[int, list[str]]],
+) -> 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]
+ repeats = Counter(h for hunk in hashed for _, _, h in hunk)
+ # Runs of consecutive lines one agent claims; a None owner breaks a run.
+ runs: list[list[tuple[int, int, str, bool]]] = []
+ for hunk in hashed:
+ run_agent: str | None = None
+ for number, text, h in hunk:
+ owner = _sole_owner(rows, by_hash.get(h, []))
+ if owner is None:
+ run_agent = None
+ continue
+ agent, latest = owner
+ if agent != run_agent:
+ runs.append([])
+ run_agent = agent
+ substantive = is_substantive(text) and repeats[h] < BOILERPLATE_REPEAT
+ runs[-1].append((latest, number, h, substantive))
+ return [
+ (idx, n, h)
+ for run in runs
+ if sum(1 for *_, sub in run if sub) >= MIN_RUN_SUBSTANTIVE
+ for idx, n, h, _ in run
+ ]
+
+
+def _bind_commit(
+ repo: Path, sha: str, rows: list[dict[str, Any]]
+) -> dict[str, Any] | None:
+ ct, files = commit_diff(repo, sha)
+ sessions = _bound_lines(rows, ct, files)
+ return _binding(sha, ct, sessions) if sessions else None
+
+
+_Sessions = dict[tuple[str, str, str | None], dict[str, list[int]]]
+
+
+def _bound_lines(
+ rows: list[dict[str, Any]],
+ ct: int,
+ files: list[tuple[str, str | None, list[tuple[int, list[str]]]]],
+) -> _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 []:
+ row = rows[idx]
+ if h in row["hashes"]:
+ row["hashes"].remove(h)
+ key = (row["agent"], row.get("session") or "", row.get("model"))
+ sessions.setdefault(key, {}).setdefault(path, []).append(number)
+ return sessions
+
+
+def _binding(sha: str, ct: int, sessions: _Sessions) -> dict[str, Any]:
+ per_agent: Counter[str] = Counter()
+ for (agent, _, _), file_lines in sessions.items():
+ per_agent[agent] += sum(len(v) for v in file_lines.values())
+ top = per_agent.most_common()
+ # A tie between agents names none (precision first, as for git-ai notes).
+ agent = top[0][0] if len(top) == 1 or top[0][1] > top[1][1] else ""
+ return {
+ "commit": sha,
+ "agent": agent,
+ "lines": sum(per_agent.values()),
+ "ts": ct,
+ "sessions": [
+ {"agent": a, "session": s, "model": m, "files": {p: sorted(n) for p, n in f.items()}}
+ for (a, s, m), f in sessions.items()
+ ],
+ }
+
+
+def _take_events(directory: Path) -> list[dict[str, Any]]:
+ """Move pending events into the work file; hooks keep appending a new one.
+
+ A work file left by a crashed run is read first, so no event is lost.
+ """
+ work = directory / _WORK
+ rows = read_jsonl(work)
+ events = directory / EVENTS
+ if events.exists():
+ taken = directory / f"{_WORK}.{os.getpid()}"
+ try:
+ os.replace(events, taken)
+ except OSError:
+ return rows
+ rows += read_jsonl(taken)
+ append_jsonl(work, read_jsonl(taken))
+ taken.unlink(missing_ok=True)
+ return rows
+
+
+def _return_events(directory: Path, rows: list[dict[str, Any]]) -> None:
+ append_jsonl(directory / EVENTS, rows)
+ (directory / _WORK).unlink(missing_ok=True)
+
+
+def _clean(rows: list[dict[str, Any]], now: float) -> list[dict[str, Any]]:
+ """Drop expired, malformed and duplicate events (two hooks, one call)."""
+ seen: set[tuple] = set()
+ kept = []
+ for row in rows:
+ if not _live(row, now):
+ continue
+ if row.get("call"):
+ key = (row["agent"], row.get("session"), row["call"], row["path"])
+ if key in seen:
+ continue
+ seen.add(key)
+ kept.append(row)
+ return kept
+
+
+def _live(row: dict[str, Any], now: float) -> bool:
+ """A well-formed event younger than :data:`EVENT_TTL_SECONDS`."""
+ ts, hashes = row.get("ts"), row.get("hashes")
+ if not isinstance(ts, (int, float)) or now - ts > EVENT_TTL_SECONDS:
+ return False
+ return (
+ isinstance(hashes, list)
+ and bool(hashes)
+ and isinstance(row.get("path"), str)
+ and isinstance(row.get("agent"), str)
+ )
+
+
+def _commits_to_bind(repo: Path, since: float, cursor: str | None) -> list[str]:
+ """Commits after *cursor* and newer than *since*, oldest first.
+
+ No ``--max-count`` here: git applies it before ``--reverse``, which would
+ keep the newest commits and skip the oldest. Listing ids is cheap; the
+ caller caps how many it diffs. ``--topo-order`` puts every parent before
+ its child, so a cursor at the last processed commit covers all before it.
+ """
+ args = [
+ "rev-list", "--no-merges", "--topo-order", "--reverse",
+ f"--since={int(since) - COMMIT_GRACE_SECONDS}", "HEAD",
+ ]
+ if cursor and _git(repo, "cat-file", "-t", cursor).strip() == "commit":
+ args.append(f"^{cursor}")
+ return _git(repo, *args).split()
+
+
+def bind_pending(repo: Path, *, capture: str, now: float | None = None) -> list[dict[str, Any]]:
+ """Bind pending events to recent commits; returns the new bindings.
+
+ *capture* is the effective level; ``notes`` also writes a git-ai note per
+ bound commit and makes sure ``notes.rewriteRef`` carries it through rebase.
+ """
+ if capture == "off":
+ return []
+ directory = sidecar_dir(repo)
+ if not (directory / EVENTS).exists() and not (directory / _WORK).exists():
+ return []
+ now = time.time() if now is None else now
+ rows = _clean(_take_events(directory), now)
+ try:
+ bindings = _bind_rows(repo, rows)
+ append_jsonl(directory / BINDINGS, bindings)
+ if capture == "notes" and bindings:
+ _write_notes(repo, bindings)
+ finally:
+ _return_events(directory, [row for row in rows if row["hashes"]])
+ return bindings
+
+
+def _bind_rows(repo: Path, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Bind *rows* to the next batch of commits and advance the cursor past it."""
+ if not rows:
+ return []
+ done = bound_commits(repo)
+ 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
+ ]
+ # 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()
+ if cursor:
+ state = load_state(repo)
+ state["cursor"] = cursor
+ save_state(repo, state)
+ return bindings
+
+
+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)
+ for binding in bindings:
+ sessions = [
+ {
+ "tool": git_ai_tool(entry["agent"]),
+ "session": entry["session"] or opaque_id(f"{binding['commit']}:{entry['agent']}"),
+ "model": entry["model"],
+ "files": entry["files"],
+ }
+ for entry in binding["sessions"]
+ ]
+ write_note(repo, binding["commit"], render_note(binding["commit"], sessions))
+
+
+def bind_repo(repo: Path) -> list[dict[str, Any]]:
+ """:func:`bind_pending` at the repo's effective capture level."""
+ from repowise.core.attribution import load_attribution_settings
+
+ settings = load_attribution_settings(repo)
+ return bind_pending(repo, capture=settings.capture) if settings.enabled else []
diff --git a/packages/core/src/repowise/core/edit_capture/edits.py b/packages/core/src/repowise/core/edit_capture/edits.py
new file mode 100644
index 000000000..5b482ec6d
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/edits.py
@@ -0,0 +1,275 @@
+"""What an agent's tool call wrote, per agent, from the live hook or a transcript.
+
+Two layers, and the split is what lets one parser serve both event sources:
+
+* An **edit extractor** per agent, ``(tool_name, tool_input, tool_response)`` to
+ the lines each file gained. The live hook and the transcript adapters hand it
+ the same three values (a Claude Code transcript's ``tool_use.input`` and
+ ``toolUseResult`` are the hook's ``tool_input`` and ``tool_response``; a Codex
+ rollout's ``apply_patch`` input is the hook's ``tool_input.command``), so
+ :meth:`repowise.core.sessions.adapters.base.HarnessAdapter.file_edits` calls
+ the extractor named here rather than parsing edits a second time.
+* A **capture adapter** per agent, a hook payload to a :class:`CapturedCall`:
+ the envelope (session, model, cwd, call id) around the extractor's result.
+
+Payload shapes, and where each was checked:
+
+* Claude Code ``PostToolUse``: ``session_id``, ``cwd``, ``tool_name``,
+ ``tool_input``, ``tool_response``, ``tool_use_id``; no model. ``Edit`` input
+ ``file_path``/``old_string``/``new_string``/``replace_all``, ``Write`` input
+ ``file_path``/``content``; responses carry ``structuredPatch`` hunks
+ (``lines`` prefixed ``+``/``-``/space) and ``userModified``. Read from the
+ installed 2.1.280 binary and local transcripts. ``MultiEdit``
+ (``file_path`` plus ``edits[]`` of ``old_string``/``new_string``) is no
+ 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).
+* Cursor ``afterFileEdit``: ``conversation_id``, ``generation_id``, ``model``,
+ ``workspace_roots``, ``file_path``, ``edits[]`` of
+ ``old_string``/``new_string`` (cursor.com/docs/agent/hooks). ``user_email``
+ is in the payload and is never read.
+
+Stdlib only: imported on the hook path.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from collections.abc import Callable
+from typing import Any
+
+from .hashing import normalize_line, split_lines
+
+
+class FileEdit:
+ """Lines one tool call added to one file. Text lives only in memory."""
+
+ __slots__ = ("added", "path")
+
+ def __init__(self, path: str, added: list[str]) -> None:
+ self.path = path
+ self.added = added
+
+ def __repr__(self) -> str:
+ return f"FileEdit({self.path!r}, {len(self.added)} lines)"
+
+
+class CapturedCall:
+ """One hook payload, reduced to what an edit event records."""
+
+ __slots__ = ("call_id", "cwd", "edits", "model", "session_id", "tool")
+
+ def __init__(
+ self,
+ *,
+ tool: str,
+ edits: list[FileEdit],
+ session_id: str = "",
+ model: str | None = None,
+ cwd: str = "",
+ call_id: str = "",
+ ) -> None:
+ self.tool = tool
+ self.edits = edits
+ self.session_id = session_id
+ self.model = model
+ self.cwd = cwd
+ self.call_id = call_id
+
+
+def _str(value: Any) -> str:
+ return value if isinstance(value, str) else ""
+
+
+def _replacement_lines(old: Any, new: Any) -> list[str]:
+ """Lines of *new* that *old* did not already have (multiset difference).
+
+ Context an agent repeats from ``old_string`` is not a line it wrote.
+ """
+ remaining = Counter(split_lines(_str(old)))
+ added: list[str] = []
+ for line in split_lines(_str(new)):
+ if remaining[line] > 0:
+ remaining[line] -= 1
+ else:
+ added.append(line)
+ return added
+
+
+def _plus_lines(hunk: Any) -> list[str]:
+ lines = hunk.get("lines") if isinstance(hunk, dict) else None
+ if not isinstance(lines, list):
+ return []
+ return [
+ normalize_line(line[1:])
+ for line in lines
+ if isinstance(line, str) and line.startswith("+")
+ ]
+
+
+def _patch_added(structured_patch: Any) -> list[str] | None:
+ """``+`` lines of a Claude Code ``structuredPatch``, or None when it has none."""
+ if not isinstance(structured_patch, list) or not structured_patch:
+ return None
+ return [line for hunk in structured_patch for line in _plus_lines(hunk)]
+
+
+def _edits_added(edits: Any) -> list[str]:
+ """Replacement lines of an ``edits[]`` list of old/new string pairs."""
+ added: list[str] = []
+ for edit in edits if isinstance(edits, list) else []:
+ if isinstance(edit, dict):
+ added += _replacement_lines(edit.get("old_string"), edit.get("new_string"))
+ return added
+
+
+def _claude_code_added(tool_name: str, tool_input: dict, response: dict) -> list[str]:
+ if tool_name == "MultiEdit":
+ return _edits_added(tool_input.get("edits"))
+ if tool_name not in ("Write", "Edit"):
+ return []
+ patched = _patch_added(response.get("structuredPatch"))
+ if patched is not None:
+ return patched
+ if tool_name == "Edit":
+ return _replacement_lines(tool_input.get("old_string"), tool_input.get("new_string"))
+ # A Write without a patch: only a new file is all the agent's; an
+ # overwrite (``update``, or no response) may keep lines it did not write.
+ if response.get("type") == "create":
+ return split_lines(_str(tool_input.get("content")))
+ return []
+
+
+def claude_code_edits(tool_name: str, tool_input: Any, tool_response: Any) -> list[FileEdit]:
+ """Claude Code ``Edit`` / ``Write`` / ``MultiEdit``.
+
+ The response's ``structuredPatch`` is preferred because it names exactly
+ the added lines. A response saying ``userModified`` is skipped: the user
+ changed the proposal before it landed, so the lines are not the agent's alone.
+ """
+ if not isinstance(tool_input, dict):
+ return []
+ path = _str(tool_input.get("file_path"))
+ response = tool_response if isinstance(tool_response, dict) else {}
+ if not path or response.get("userModified") is True:
+ return []
+ added = _claude_code_added(tool_name, tool_input, response)
+ return [FileEdit(path, added)] if added else []
+
+
+def _patch_header(line: str, current: FileEdit | None, edits: list[FileEdit]) -> FileEdit | None:
+ """The file a ``*** `` header line opens (appended to *edits*), renames, or ends."""
+ if line.startswith(("*** Add File: ", "*** Update File: ")):
+ edits.append(FileEdit(line.split(": ", 1)[1].strip(), []))
+ return edits[-1]
+ if line.startswith("*** Move to: ") and current is not None:
+ current.path = line.split(": ", 1)[1].strip()
+ return current
+ return None
+
+
+def parse_apply_patch(patch: str) -> list[FileEdit]:
+ """The files and added lines of a Codex ``apply_patch`` envelope.
+
+ ``*** Add File:`` bodies are all added; ``*** Update File:`` hunks add their
+ ``+`` lines, under the ``*** Move to:`` path when the file is renamed.
+ ``*** Delete File:`` adds nothing.
+ """
+ edits: list[FileEdit] = []
+ current: FileEdit | None = None
+ for raw in patch.split("\n"):
+ line = raw.rstrip("\r")
+ if line.startswith("*** "):
+ current = _patch_header(line, current, edits)
+ elif current is not None and line.startswith("+"):
+ current.added.append(normalize_line(line[1:]))
+ return [edit for edit in edits if edit.added]
+
+
+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):
+ return []
+ patch = ""
+ if isinstance(tool_input, dict):
+ patch = _str(tool_input.get("command")) or _str(tool_input.get("input"))
+ elif isinstance(tool_input, str):
+ patch = tool_input
+ if "*** Begin Patch" not in patch:
+ return []
+ return parse_apply_patch(patch)
+
+
+def cursor_edits(tool_name: str, tool_input: Any, tool_response: Any) -> list[FileEdit]:
+ """Cursor ``afterFileEdit``: ``file_path`` plus ``edits[]`` of old/new strings."""
+ if not isinstance(tool_input, dict):
+ return []
+ path = _str(tool_input.get("file_path"))
+ added = _edits_added(tool_input.get("edits")) if path else []
+ return [FileEdit(path, added)] if added else []
+
+
+Extractor = Callable[[str, Any, Any], list[FileEdit]]
+
+#: Keyed by the agent's capture adapter name (``AgentIdentity.capture_adapter``),
+#: which is also its transcript adapter name where it has one.
+EXTRACTORS: dict[str, Extractor] = {
+ "claude_code": claude_code_edits,
+ "codex": codex_edits,
+ "cursor": cursor_edits,
+}
+
+
+def _tool_call(payload: dict, extractor: Extractor) -> CapturedCall | None:
+ if payload.get("hook_event_name") != "PostToolUse":
+ return None
+ tool = _str(payload.get("tool_name"))
+ edits = extractor(tool, payload.get("tool_input"), payload.get("tool_response"))
+ if not edits:
+ return None
+ return CapturedCall(
+ tool=tool,
+ edits=edits,
+ session_id=_str(payload.get("session_id")),
+ model=_str(payload.get("model")) or None,
+ cwd=_str(payload.get("cwd")),
+ call_id=_str(payload.get("tool_use_id")),
+ )
+
+
+def claude_code_call(payload: dict) -> CapturedCall | None:
+ return _tool_call(payload, claude_code_edits)
+
+
+def codex_call(payload: dict) -> CapturedCall | None:
+ return _tool_call(payload, codex_edits)
+
+
+def cursor_call(payload: dict) -> CapturedCall | None:
+ if payload.get("hook_event_name") != "afterFileEdit":
+ return None
+ edits = cursor_edits("afterFileEdit", payload, None)
+ if not edits:
+ return None
+ roots = payload.get("workspace_roots")
+ cwd = next((r for r in roots if isinstance(r, str) and r), "") if isinstance(roots, list) else ""
+ generation = _str(payload.get("generation_id"))
+ return CapturedCall(
+ tool="afterFileEdit",
+ edits=edits,
+ session_id=_str(payload.get("conversation_id")),
+ model=_str(payload.get("model")) or None,
+ cwd=cwd,
+ # One afterFileEdit per file per generation.
+ call_id=f"{generation}:{edits[0].path}" if generation else "",
+ )
+
+
+#: Hook payload to :class:`CapturedCall`, by capture adapter name.
+CAPTURE_ADAPTERS: dict[str, Callable[[dict], CapturedCall | None]] = {
+ "claude_code": claude_code_call,
+ "codex": codex_call,
+ "cursor": cursor_call,
+}
diff --git a/packages/core/src/repowise/core/edit_capture/hashing.py b/packages/core/src/repowise/core/edit_capture/hashing.py
new file mode 100644
index 000000000..6bcf7b2ab
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/hashing.py
@@ -0,0 +1,49 @@
+"""The one content hash shared by capture, commit binding and transcript backfill.
+
+A line is normalised before hashing so the same text hashes the same whichever
+tool wrote it: a trailing ``\\r`` (CRLF checkouts, Windows agents) and trailing
+whitespace are dropped, leading indentation is kept because it is content.
+
+Only hashes leave this module; the text never does.
+"""
+
+from __future__ import annotations
+
+import hashlib
+
+#: A line needs this many non-space characters, one of them alphanumeric, to
+#: count toward a binding. Blank, brace-only and short lines (``}``, ``pass``,
+#: ``return x``) occur everywhere, so they can ride inside a bound run but never
+#: anchor one.
+MIN_SUBSTANTIVE_CHARS = 10
+
+
+def normalize_line(line: str) -> str:
+ return line.rstrip("\r\n").rstrip()
+
+
+def split_lines(text: str) -> list[str]:
+ """*text* as normalised lines, split on ``\\n`` only, as git does.
+
+ ``str.splitlines`` would also split on form feed and U+2028, lines git
+ keeps whole, so the hashes would never meet the diff's.
+ """
+ lines = text.split("\n")
+ if lines and lines[-1] == "":
+ lines.pop()
+ return [normalize_line(line) for line in lines]
+
+
+def line_hash(line: str) -> str:
+ """16 hex chars of BLAKE2b over the normalised line."""
+ return hashlib.blake2b(normalize_line(line).encode("utf-8"), digest_size=8).hexdigest()
+
+
+def is_substantive(line: str) -> bool:
+ stripped = normalize_line(line).strip()
+ return len(stripped) >= MIN_SUBSTANTIVE_CHARS and any(ch.isalnum() for ch in stripped)
+
+
+def opaque_id(value: str) -> str:
+ """A session id as stored: 16 hex chars of SHA-256, never the raw id."""
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
diff --git a/packages/core/src/repowise/core/edit_capture/notes.py b/packages/core/src/repowise/core/edit_capture/notes.py
new file mode 100644
index 000000000..f2d3066fd
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/notes.py
@@ -0,0 +1,184 @@
+"""git-ai v3 authorship notes on ``refs/notes/ai``: write ours, remove only ours.
+
+Format: Git AI Standard v3.0.0 (``specs/git_ai_standard_v3.0.0.md`` in
+github.com/git-ai-project/git-ai, last changed by commit ``e2411d98``,
+2026-05-18). An attestation section (file path at column 0, two-space indented
+``s_<14hex>::t_<14hex> <ranges>`` lines), a ``---`` line, then JSON metadata
+with ``schema_version: "authorship/3.0.0"``, ``base_commit_sha``, ``prompts``
+and ``sessions``.
+
+What we put in a note is narrower than the format allows: ``agent_id.id`` is
+the opaque session hash, never the agent's conversation id, and there is no
+``human_author``, ``humans`` or ``custom_attributes`` - a note is readable by
+everyone with repo access.
+
+A commit that already has a note is never written: the note is someone else's
+(git-ai, another machine) and the spec allows one per commit. Which notes are
+ours is recorded by note blob id in the sidecar ledger, so purge removes our
+notes, including the copies ``notes.rewriteRef`` carried across a rebase (same
+blob), and never a foreign one.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import secrets
+import subprocess
+from pathlib import Path
+
+from .store import NOTES_LEDGER, append_jsonl, load_state, read_jsonl, save_state, sidecar_dir
+
+NOTES_REF = "refs/notes/ai"
+SCHEMA_VERSION = "authorship/3.0.0"
+#: The fetch refspec a clone needs to receive teammates' notes.
+FETCH_REFSPEC = f"+{NOTES_REF}:{NOTES_REF}"
+
+
+def _git(repo: Path, *args: str, stdin: str | None = None) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["git", *args],
+ cwd=repo,
+ input=stdin,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=None if stdin is not None else subprocess.DEVNULL,
+ check=False,
+ )
+
+
+def session_key(tool: str, session: str) -> str:
+ """``s_`` + SHA-256(``<tool>:<session>``)[:14], the spec's session id rule."""
+ return "s_" + hashlib.sha256(f"{tool}:{session}".encode()).hexdigest()[:14]
+
+
+def format_ranges(lines: list[int]) -> str:
+ """Sorted 1-indexed lines as ``1-4,9,12-13``."""
+ out: list[str] = []
+ ordered = sorted(set(lines))
+ i = 0
+ while i < len(ordered):
+ j = i
+ while j + 1 < len(ordered) and ordered[j + 1] == ordered[j] + 1:
+ j += 1
+ out.append(str(ordered[i]) if i == j else f"{ordered[i]}-{ordered[j]}")
+ i = j + 1
+ return ",".join(out)
+
+
+def _quote(path: str) -> str:
+ return f'"{path}"' if any(ch in path for ch in " \t\n") else path
+
+
+def render_note(commit: str, sessions: list[dict]) -> str:
+ """One commit's note from binder sessions.
+
+ Each session is ``{"tool", "session", "model", "files": {path: [line, ...]}}``
+ with ``tool`` the git-ai tool name (``claude``, ``codex``, ``cursor``).
+ """
+ by_path: dict[str, list[str]] = {}
+ meta: dict[str, dict] = {}
+ for entry in sessions:
+ key = session_key(entry["tool"], entry["session"])
+ trace = f"t_{secrets.token_hex(7)}"
+ meta[key] = {
+ "agent_id": {
+ "tool": entry["tool"],
+ "id": entry["session"],
+ "model": entry.get("model") or "unknown",
+ }
+ }
+ for path, lines in entry["files"].items():
+ by_path.setdefault(path, []).append(f" {key}::{trace} {format_ranges(lines)}")
+ attestation = []
+ for path in sorted(by_path):
+ attestation.append(_quote(path))
+ attestation.extend(by_path[path])
+ metadata = {
+ "schema_version": SCHEMA_VERSION,
+ "base_commit_sha": commit,
+ "prompts": {},
+ "sessions": meta,
+ }
+ return "\n".join([*attestation, "---", json.dumps(metadata, indent=2, sort_keys=True)]) + "\n"
+
+
+def _note_blob(repo: Path, commit: str) -> str | None:
+ result = _git(repo, "notes", f"--ref={NOTES_REF}", "list", commit)
+ blob = result.stdout.strip()
+ return blob if result.returncode == 0 and blob else None
+
+
+def write_note(repo: Path, commit: str, text: str) -> bool:
+ """Attach *text* to *commit* unless it already has a note; True when written."""
+ if _note_blob(repo, commit) is not None:
+ return False
+ if _git(repo, "notes", f"--ref={NOTES_REF}", "add", "-F", "-", commit, stdin=text).returncode:
+ return False
+ blob = _note_blob(repo, commit)
+ if blob:
+ append_jsonl(sidecar_dir(repo) / NOTES_LEDGER, [{"commit": commit, "blob": blob}])
+ return blob is not None
+
+
+def _config_values(repo: Path, key: str) -> list[str]:
+ result = _git(repo, "config", "--get-all", key)
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
+
+
+def ensure_rewrite_ref(repo: Path) -> bool:
+ """Add ``notes.rewriteRef = refs/notes/ai`` to the repo config if missing.
+
+ Git then copies the note when ``commit --amend`` or ``rebase`` (including
+ a squash) rewrites the commit. True when this call added it; the state file
+ remembers so purge can take it back out.
+ """
+ if NOTES_REF in _config_values(repo, "notes.rewriteRef"):
+ return False
+ if _git(repo, "config", "--add", "notes.rewriteRef", NOTES_REF).returncode:
+ return False
+ state = load_state(repo)
+ state["rewrite_ref_added"] = True
+ save_state(repo, state)
+ return True
+
+
+def _mentions_notes(refspec: str) -> bool:
+ return NOTES_REF in refspec or "refs/notes/*" in refspec
+
+
+def refspec_status(repo: Path, remote: str = "origin") -> dict[str, bool]:
+ """Whether notes would reach teammates: remote, fetch, push and rewrite config."""
+ has_remote = bool(_config_values(repo, f"remote.{remote}.url"))
+ return {
+ "remote": has_remote,
+ "fetch": any(_mentions_notes(r) for r in _config_values(repo, f"remote.{remote}.fetch")),
+ "push": any(_mentions_notes(r) for r in _config_values(repo, f"remote.{remote}.push")),
+ "rewrite_ref": NOTES_REF in _config_values(repo, "notes.rewriteRef"),
+ }
+
+
+def purge_notes(repo: Path) -> int:
+ """Remove every note whose blob Repowise wrote; returns how many went.
+
+ Also takes out the ``notes.rewriteRef`` entry if we added it. Remote notes
+ are never touched; the caller prints the push that would delete them.
+ """
+ ours = {row.get("blob") for row in read_jsonl(sidecar_dir(repo) / NOTES_LEDGER)}
+ ours.discard(None)
+ removed = 0
+ if ours:
+ listing = _git(repo, "notes", f"--ref={NOTES_REF}", "list")
+ for line in listing.stdout.splitlines():
+ parts = line.split()
+ if (
+ len(parts) == 2
+ and parts[0] in ours
+ and not _git(repo, "notes", f"--ref={NOTES_REF}", "remove", parts[1]).returncode
+ ):
+ removed += 1
+ if load_state(repo).get("rewrite_ref_added"):
+ _git(repo, "config", "--unset-all", "notes.rewriteRef", f"^{NOTES_REF}$")
+ return removed
diff --git a/packages/core/src/repowise/core/edit_capture/store.py b/packages/core/src/repowise/core/edit_capture/store.py
new file mode 100644
index 000000000..82b0decd7
--- /dev/null
+++ b/packages/core/src/repowise/core/edit_capture/store.py
@@ -0,0 +1,183 @@
+"""The consent gate and the local sidecar edit events and bindings live in.
+
+Everything sits under ``.repowise/attribution/`` (gitignored with the rest of
+``.repowise/``):
+
+* ``events.jsonl`` - pending edit events: agent, opaque session id, model,
+ tool, repo-relative path, line hashes, timestamp. Never code, prompts or a
+ person's identity.
+* ``bindings.jsonl`` - commits the binder attributed, with line ranges.
+* ``notes.jsonl`` - the git-ai notes Repowise wrote (commit and note blob), so
+ purge can remove exactly those and nothing else.
+* ``state.json`` - the binding cursor and whether we added ``notes.rewriteRef``.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import shutil
+import time
+from pathlib import Path
+from typing import Any
+
+from .edits import CapturedCall, FileEdit
+from .hashing import line_hash, opaque_id
+
+EVENTS = "events.jsonl"
+BINDINGS = "bindings.jsonl"
+NOTES_LEDGER = "notes.jsonl"
+STATE = "state.json"
+
+#: Pending events older than this are dropped at the next binding: an edit not
+#: committed within two weeks is more likely reverted than waiting.
+EVENT_TTL_SECONDS = 14 * 24 * 3600
+
+
+def sidecar_dir(repo_root: Path | str) -> Path:
+ return Path(repo_root) / ".repowise" / "attribution"
+
+
+def capture_level(repo_root: Path | str, agent_slug: str) -> str:
+ """``off``, ``local`` or ``notes`` for *agent_slug* in this repo.
+
+ Ordered cheapest first, because every hooked edit asks: ``DO_NOT_TRACK``,
+ then a substring test on the repo config (capture needs the repo to opt in,
+ so a file that never says ``capture`` is off without a YAML parse), and
+ only then the full stricter-wins resolution.
+ """
+ from repowise.core.platform.telemetry import _env_truthy
+
+ if _env_truthy("DO_NOT_TRACK"):
+ return "off"
+ try:
+ text = (Path(repo_root) / ".repowise" / "config.yaml").read_text(encoding="utf-8")
+ except OSError:
+ return "off"
+ if "capture" not in text:
+ return "off"
+ from repowise.core.attribution import load_attribution_settings
+
+ settings = load_attribution_settings(repo_root)
+ if settings.capture == "off" or agent_slug.replace("_", "-") not in settings.agents:
+ return "off"
+ return settings.capture
+
+
+def edit_event(agent_slug: str, call: CapturedCall, edit: FileEdit, ts: float) -> dict[str, Any]:
+ """The event row for one *edit* of *call*; ``edit.path`` is repo-relative."""
+ return {
+ "v": 1,
+ "ts": ts,
+ "agent": agent_slug,
+ "session": opaque_id(call.session_id) if call.session_id else "",
+ "model": call.model,
+ "tool": call.tool,
+ "call": opaque_id(call.call_id) if call.call_id else "",
+ "path": edit.path,
+ "hashes": [line_hash(line) for line in edit.added],
+ }
+
+
+def _repo_relative(repo_root: Path, cwd: str, path: str) -> str | None:
+ """*path* (absolute, or relative to *cwd*) relative to *repo_root*; None outside it."""
+ from repowise.core.sessions.events import relative_files
+
+ path = path.replace("\\", "/")
+ if not (path.startswith("/") or (len(path) > 1 and path[1] == ":")):
+ path = f"{cwd}/{path}"
+ rel = relative_files([path], repo_root)
+ return rel[0] if rel else None
+
+
+def record_call(repo_root: Path, agent_slug: str, call: CapturedCall) -> int:
+ """Append one event per edited file inside *repo_root*; returns how many."""
+ cwd = (call.cwd or str(repo_root)).replace("\\", "/").rstrip("/")
+ now = time.time()
+ rows = [
+ edit_event(agent_slug, call, FileEdit(rel, edit.added), now)
+ for edit in call.edits
+ if (rel := _repo_relative(repo_root, cwd, edit.path)) is not None
+ ]
+ append_jsonl(sidecar_dir(repo_root) / EVENTS, rows)
+ return len(rows)
+
+
+def read_jsonl(path: Path) -> list[dict[str, Any]]:
+ """Every object line of *path*; a torn or foreign line is skipped."""
+ rows: list[dict[str, Any]] = []
+ try:
+ with open(path, encoding="utf-8") as handle:
+ for line in handle:
+ with contextlib.suppress(ValueError):
+ row = json.loads(line)
+ if isinstance(row, dict):
+ rows.append(row)
+ except OSError:
+ return []
+ return rows
+
+
+def append_lines(path: Path, lines: list[str]) -> None:
+ """Append *lines* in one ``write`` on an ``O_APPEND`` fd.
+
+ A buffered text write splits past 8 KB, so two hooks finishing together
+ could interleave inside a line; one syscall keeps each batch whole.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o644)
+ try:
+ os.write(fd, "".join(lines).encode("utf-8"))
+ finally:
+ os.close(fd)
+
+
+def append_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
+ if rows:
+ append_lines(path, [json.dumps(row, separators=(",", ":")) + "\n" for row in rows])
+
+
+def load_state(repo_root: Path | str) -> dict[str, Any]:
+ try:
+ data = json.loads((sidecar_dir(repo_root) / STATE).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def save_state(repo_root: Path | str, state: dict[str, Any]) -> None:
+ directory = sidecar_dir(repo_root)
+ directory.mkdir(parents=True, exist_ok=True)
+ tmp = directory / f"{STATE}.tmp"
+ tmp.write_text(json.dumps(state, sort_keys=True), encoding="utf-8")
+ os.replace(tmp, directory / STATE)
+
+
+def bound_commits(repo_root: Path | str) -> dict[str, str]:
+ """``commit sha -> agent slug`` for every commit the binder attributed."""
+ out: dict[str, str] = {}
+ for row in read_jsonl(sidecar_dir(repo_root) / BINDINGS):
+ sha, agent = row.get("commit"), row.get("agent")
+ if isinstance(sha, str) and isinstance(agent, str) and agent:
+ out[sha] = agent
+ return out
+
+
+def summary(repo_root: Path | str) -> dict[str, int]:
+ """Counts for ``repowise attribution status``."""
+ directory = sidecar_dir(repo_root)
+ return {
+ "pending_events": len(read_jsonl(directory / EVENTS)),
+ "bound_commits": len(bound_commits(repo_root)),
+ "notes_written": len(read_jsonl(directory / NOTES_LEDGER)),
+ }
+
+
+def delete_sidecar(repo_root: Path | str) -> bool:
+ """Remove the whole sidecar; True when there was one."""
+ directory = sidecar_dir(repo_root)
+ if not directory.exists():
+ return False
+ shutil.rmtree(directory, ignore_errors=True)
+ return True
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index b73ee604d..ac89d73cf 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -77,9 +77,30 @@ def load_git_ai_note_agents(repo: object, commit_limit: int | None) -> dict[str,
note = parse_git_ai_note(raw)
if note.agent or note.human:
notes[sha.strip()] = note
+ _merge_capture_bindings(repo, notes)
return notes
+def _merge_capture_bindings(repo: object, notes: dict[str, GitAiNote]) -> None:
+ """Add commits this machine's edit capture bound; a real note wins."""
+ root = getattr(repo, "working_tree_dir", None)
+ if not root:
+ return
+ from repowise.core.attribution import load_attribution_settings
+ from repowise.core.edit_capture.store import bound_commits
+
+ # Bindings are consent-gated at read time too: turning capture off stops them.
+ if load_attribution_settings(root).capture == "off":
+ return
+
+ from .git_indexer.agent_provenance import GitAiNote, _normalize_agent_token
+
+ for sha, agent in bound_commits(root).items():
+ label = _normalize_agent_token(agent.replace("_", " "), allow_slug=True)
+ if label and sha not in notes:
+ notes[sha] = GitAiNote(agent=label, source="edit_capture")
+
+
def _git_ai_notes_log(repo: object, commit_limit: int | None) -> str:
"""The raw ``refs/notes/ai`` log, or ``""`` when the ref is absent or git fails."""
try:
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
index fda1a4a9e..e8b28afba 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
@@ -30,6 +30,11 @@ Three cross-cutting channels ride the same rule set:
Tier 2 (``agent_trace`` channel).
* a ``Generated-by:`` trailer (Apache's AI-attribution footer) naming a
recognized agent — Tier 2 (``generated_by_trailer`` channel).
+ * an **edit-capture binding** (opt-in ``attribution.capture``): this
+ machine's hook recorded the agent's edits and :mod:`repowise.core.edit_capture`
+ matched them to the commit by content hash. Passed in like a git-ai note
+ with ``source="edit_capture"``; Tier 2 (``edit_capture`` channel), below a
+ note actually attached to the commit.
Precedence is tier order (1 > 2 > 3); first match wins. Every commit gets a
three-state label (:mod:`repowise.core.attribution`): ``agent`` on a match,
@@ -232,6 +237,9 @@ class GitAiNote:
# Files the attestation names; a human attestation counts only when it
# covers every path the commit changed.
paths: frozenset[str] = frozenset()
+ # The channel the agent label is stored under: ``edit_capture`` for a
+ # commit bound from this machine's own capture sidecar.
+ source: str = "git_ai_note"
# A note is a few KB; past this it is not read (a hostile or broken ref must
@@ -715,6 +723,7 @@ class AgentProvenanceClassifier:
trace_confidence: str = "high",
note_human: bool = False,
trace_human: bool = False,
+ note_channel: str = "git_ai_note",
) -> AgentProvenance:
"""Classify one commit from local metadata. *message* is the full
commit message (subject + body) — trailers and footers live in the
@@ -736,6 +745,7 @@ class AgentProvenanceClassifier:
note_agent,
trace_agent,
trace_confidence,
+ note_channel,
)
if prov is not None:
return prov
@@ -754,6 +764,7 @@ class AgentProvenanceClassifier:
note_agent: str | None,
trace_agent: str | None,
trace_confidence: str,
+ note_channel: str = "git_ai_note",
) -> AgentProvenance | None:
# T1 — agent service identity AUTHORED the commit.
hit = self._identity_match(author_email)
@@ -763,7 +774,7 @@ class AgentProvenanceClassifier:
# this commit. Below T1 (a bot service account is more autonomous) but
# above the message-derived channels.
if note_agent:
- return _agent(note_agent, 2, "git_ai_note")
+ return _agent(note_agent, 2, note_channel)
# T2 — agent-trace record resolved to this commit. Below the git-ai
# note (a commit-attached attestation beats heuristic revision
# mapping), above the message-derived channels.
@@ -830,6 +841,7 @@ def classify_commit(
trace_confidence=trace_hit[1] if trace_hit else "high",
note_human=note.human and bool(changed_paths) and changed_paths <= note.paths,
trace_human=bool(trace_index) and trace_index.resolve_human(sha, parents, changed_paths),
+ note_channel=note.source,
)
return prov, trace_hit
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
index 74a086b59..d3956672c 100644
--- a/packages/core/src/repowise/core/sessions/adapters/base.py
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -19,9 +19,12 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable, Iterator
from pathlib import Path
-from typing import ClassVar
+from typing import TYPE_CHECKING, ClassVar
-from repowise.core.sessions.events import Event
+from repowise.core.sessions.events import Event, ToolResult, ToolUse
+
+if TYPE_CHECKING:
+ from repowise.core.edit_capture.edits import FileEdit
#: Cheap gate on the raw line, applied before paying for JSON parsing.
#: Transcript lines routinely run to hundreds of kilobytes; a substring
@@ -156,6 +159,20 @@ class HarnessAdapter(ABC):
finally:
self.end_file()
+ def file_edits(self, use: ToolUse, result: ToolResult | None = None) -> list[FileEdit]:
+ """Lines a recorded tool call added, per file; empty for a non-edit call.
+
+ 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.
+ """
+ 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 []
+ 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]:
"""Events from one transcript file, in order.
diff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.py
index cee60bfc9..084e2c28c 100644
--- a/scripts/gen_agent_matrix.py
+++ b/scripts/gen_agent_matrix.py
@@ -130,6 +130,7 @@ def agent_rows() -> list[dict]:
"host": by_manager["host"],
"hook_adapter": target.hook_adapter,
"session_adapter": target.session_adapter,
+ "capture_adapter": target.capture_adapter,
"indexing_provider": identity.indexing_provider if identity else None,
}
)
@@ -238,6 +239,7 @@ _COLUMNS: tuple[tuple[str, str], ...] = (
("Instructions", "instructions"),
("Transcripts", "session_adapter"),
("Indexing", "indexing_provider"),
+ ("Attribution", "capture_adapter"),
)
@@ -322,6 +324,11 @@ def render() -> str:
"LLM that writes the index, selected by its provider id (`claude_cli`, for",
"example). It is separate from the tier: it says nothing about the session.",
"",
+ "`Attribution` is `Yes` when repowise can record the agent's edits as they",
+ "happen, an opt-in set by `attribution.capture` and `attribution.agents`. Every",
+ "agent's own git-ai notes, Agent Trace files and commit trailers are read",
+ "either way.",
+ "",
_matrix_table(rows),
"",
f"Target ids for `--target=`: {ids}.",
diff --git a/tests/fixtures/attribution_capture/claude_code_edit.json b/tests/fixtures/attribution_capture/claude_code_edit.json
new file mode 100644
index 000000000..d13dcab18
--- /dev/null
+++ b/tests/fixtures/attribution_capture/claude_code_edit.json
@@ -0,0 +1,38 @@
+{
+ "session_id": "6f1c2b9e-0000-4000-8000-00000000c1a0",
+ "transcript_path": "/home/dev/.claude/projects/-work-demo/6f1c2b9e.jsonl",
+ "cwd": "/work/demo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_use_id": "toolu_01EXAMPLE",
+ "duration_ms": 41,
+ "tool_name": "Edit",
+ "tool_input": {
+ "file_path": "/work/demo/src/billing.py",
+ "old_string": "def total(items):\n return 0\n",
+ "new_string": "def total(items):\n subtotal = sum(item.price for item in items)\n return round(subtotal * 1.2, 2)\n",
+ "replace_all": false
+ },
+ "tool_response": {
+ "filePath": "/work/demo/src/billing.py",
+ "oldString": "def total(items):\n return 0\n",
+ "newString": "def total(items):\n subtotal = sum(item.price for item in items)\n return round(subtotal * 1.2, 2)\n",
+ "originalFile": "def total(items):\n return 0\n",
+ "replaceAll": false,
+ "userModified": false,
+ "structuredPatch": [
+ {
+ "oldStart": 1,
+ "oldLines": 2,
+ "newStart": 1,
+ "newLines": 3,
+ "lines": [
+ " def total(items):",
+ "- return 0",
+ "+ subtotal = sum(item.price for item in items)",
+ "+ return round(subtotal * 1.2, 2)"
+ ]
+ }
+ ]
+ }
+}
diff --git a/tests/fixtures/attribution_capture/claude_code_edit_user_modified.json b/tests/fixtures/attribution_capture/claude_code_edit_user_modified.json
new file mode 100644
index 000000000..0764e6724
--- /dev/null
+++ b/tests/fixtures/attribution_capture/claude_code_edit_user_modified.json
@@ -0,0 +1,21 @@
+{
+ "session_id": "6f1c2b9e-0000-4000-8000-00000000c1a0",
+ "transcript_path": "/home/dev/.claude/projects/-work-demo/6f1c2b9e.jsonl",
+ "cwd": "/work/demo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_use_id": "toolu_01EXAMPLE",
+ "duration_ms": 41,
+ "tool_name": "Edit",
+ "tool_input": {
+ "file_path": "/work/demo/src/billing.py",
+ "old_string": " return 0\n",
+ "new_string": " return compute_total_with_tax(items)\n",
+ "replace_all": false
+ },
+ "tool_response": {
+ "filePath": "/work/demo/src/billing.py",
+ "userModified": true,
+ "structuredPatch": []
+ }
+}
diff --git a/tests/fixtures/attribution_capture/claude_code_edit_windows_crlf.json b/tests/fixtures/attribution_capture/claude_code_edit_windows_crlf.json
new file mode 100644
index 000000000..7051cbde4
--- /dev/null
+++ b/tests/fixtures/attribution_capture/claude_code_edit_windows_crlf.json
@@ -0,0 +1,25 @@
+{
+ "session_id": "6f1c2b9e-0000-4000-8000-00000000c1a0",
+ "transcript_path": "C:\\Users\\dev\\.claude\\projects\\C--work-demo\\6f1c2b9e.jsonl",
+ "cwd": "C:\\work\\demo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_use_id": "toolu_01EXAMPLE",
+ "duration_ms": 41,
+ "tool_name": "Edit",
+ "tool_input": {
+ "file_path": "C:\\work\\demo\\src\\billing.py",
+ "old_string": "def total(items):\r\n return 0\r\n",
+ "new_string": "def total(items):\r\n subtotal = sum(item.price for item in items)\r\n return round(subtotal * 1.2, 2)\r\n",
+ "replace_all": false
+ },
+ "tool_response": {
+ "filePath": "C:\\work\\demo\\src\\billing.py",
+ "oldString": "def total(items):\r\n return 0\r\n",
+ "newString": "def total(items):\r\n subtotal = sum(item.price for item in items)\r\n return round(subtotal * 1.2, 2)\r\n",
+ "originalFile": "def total(items):\r\n return 0\r\n",
+ "replaceAll": false,
+ "userModified": false,
+ "structuredPatch": []
+ }
+}
diff --git a/tests/fixtures/attribution_capture/claude_code_multiedit.json b/tests/fixtures/attribution_capture/claude_code_multiedit.json
new file mode 100644
index 000000000..454296cab
--- /dev/null
+++ b/tests/fixtures/attribution_capture/claude_code_multiedit.json
@@ -0,0 +1,27 @@
+{
+ "session_id": "6f1c2b9e-0000-4000-8000-00000000c1a0",
+ "transcript_path": "/home/dev/.claude/projects/-work-demo/6f1c2b9e.jsonl",
+ "cwd": "/work/demo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_use_id": "toolu_01EXAMPLE",
+ "duration_ms": 41,
+ "tool_name": "MultiEdit",
+ "tool_input": {
+ "file_path": "/work/demo/src/billing.py",
+ "edits": [
+ {
+ "old_string": "TAX = 0\n",
+ "new_string": "TAX_RATE = Decimal('0.20')\n"
+ },
+ {
+ "old_string": "def total(items):\n return 0\n",
+ "new_string": "def total(items):\n return sum(item.price for item in items) * (1 + TAX_RATE)\n",
+ "replace_all": false
+ }
+ ]
+ },
+ "tool_response": {
+ "filePath": "/work/demo/src/billing.py"
+ }
+}
diff --git a/tests/fixtures/attribution_capture/claude_code_write.json b/tests/fixtures/attribution_capture/claude_code_write.json
new file mode 100644
index 000000000..69d3a7313
--- /dev/null
+++ b/tests/fixtures/attribution_capture/claude_code_write.json
@@ -0,0 +1,22 @@
+{
+ "session_id": "6f1c2b9e-0000-4000-8000-00000000c1a0",
+ "transcript_path": "/home/dev/.claude/projects/-work-demo/6f1c2b9e.jsonl",
+ "cwd": "/work/demo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUse",
+ "tool_use_id": "toolu_01EXAMPLE",
+ "duration_ms": 41,
+ "tool_name": "Write",
+ "tool_input": {
+ "file_path": "/work/demo/src/report.py",
+ "content": "def render(rows):\n header = 'name,amount'\n body = [f'{r.name},{r.amount}' for r in rows]\n return '\\n'.join([header, *body])\n"
+ },
+ "tool_response": {
+ "type": "create",
+ "filePath": "/work/demo/src/report.py",
+ "content": "def render(rows):\n header = 'name,amount'\n body = [f'{r.name},{r.amount}' for r in rows]\n return '\\n'.join([header, *body])\n",
+ "structuredPatch": [],
+ "originalFile": null,
+ "userModified": false
+ }
+}
diff --git a/tests/fixtures/attribution_capture/codex_apply_patch.json b/tests/fixtures/attribution_capture/codex_apply_patch.json
new file mode 100644
index 000000000..43339cc3d
--- /dev/null
+++ b/tests/fixtures/attribution_capture/codex_apply_patch.json
@@ -0,0 +1,15 @@
+{
+ "session_id": "019a0000-0000-7000-8000-00000000c0de",
+ "transcript_path": "/home/dev/.codex/sessions/2026/10/14/rollout-2026-10-14T10-00-00-019a0000.jsonl",
+ "cwd": "/work/demo",
+ "hook_event_name": "PostToolUse",
+ "model": "gpt-5.5-codex",
+ "permission_mode": "default",
+ "turn_id": "turn-7",
+ "tool_use_id": "call_apply_1",
+ "tool_name": "apply_patch",
+ "tool_input": {
+ "command": "*** Begin Patch\n*** Update File: src/billing.py\n@@ def total(items):\n- return 0\n+ subtotal = sum(item.price for item in items)\n+ return round(subtotal * 1.2, 2)\n*** Add File: src/report.py\n+def render(rows):\n+ header = 'name,amount'\n*** Delete File: src/legacy.py\n*** End Patch"
+ },
+ "tool_response": "Exit code: 0\nWall time: 0.1 seconds\nOutput:\nSuccess. Updated the following files:\nM src/billing.py\nA src/report.py\nD src/legacy.py\n"
+}
diff --git a/tests/fixtures/attribution_capture/codex_apply_patch_failed.json b/tests/fixtures/attribution_capture/codex_apply_patch_failed.json
new file mode 100644
index 000000000..e98d7701d
--- /dev/null
+++ b/tests/fixtures/attribution_capture/codex_apply_patch_failed.json
@@ -0,0 +1,15 @@
+{
+ "session_id": "019a0000-0000-7000-8000-00000000c0de",
+ "transcript_path": "/home/dev/.codex/sessions/2026/10/14/rollout-2026-10-14T10-00-00-019a0000.jsonl",
+ "cwd": "/work/demo",
+ "hook_event_name": "PostToolUse",
+ "model": "gpt-5.5-codex",
+ "permission_mode": "default",
+ "turn_id": "turn-7",
+ "tool_use_id": "call_apply_1",
+ "tool_name": "apply_patch",
+ "tool_input": {
+ "command": "*** Begin Patch\n*** Update File: src/billing.py\n@@ def total(items):\n- return 0\n+ subtotal = sum(item.price for item in items)\n+ return round(subtotal * 1.2, 2)\n*** Add File: src/report.py\n+def render(rows):\n+ header = 'name,amount'\n*** Delete File: src/legacy.py\n*** End Patch"
+ },
+ "tool_response": "Exit code: 1\nOutput:\napply_patch verification failed: Failed to find expected lines\n"
+}
diff --git a/tests/fixtures/attribution_capture/codex_apply_patch_move.json b/tests/fixtures/attribution_capture/codex_apply_patch_move.json
new file mode 100644
index 000000000..f80033207
--- /dev/null
+++ b/tests/fixtures/attribution_capture/codex_apply_patch_move.json
@@ -0,0 +1,15 @@
+{
+ "session_id": "019a0000-0000-7000-8000-00000000c0de",
+ "transcript_path": "/home/dev/.codex/sessions/2026/10/14/rollout-2026-10-14T10-00-00-019a0000.jsonl",
+ "cwd": "/work/demo",
+ "hook_event_name": "PostToolUse",
+ "model": "gpt-5.5-codex",
+ "permission_mode": "default",
+ "turn_id": "turn-7",
+ "tool_use_id": "call_apply_1",
+ "tool_name": "apply_patch",
+ "tool_input": {
+ "command": "*** Begin Patch\r\n*** Update File: src/old_name.py\r\n*** Move to: src/new_name.py\r\n@@\r\n-VALUE = 1\r\n+VALUE = compute_default_value()\r\n+LIMIT = compute_default_limit()\r\n*** End Patch\r\n"
+ },
+ "tool_response": "Exit code: 0\nOutput:\nSuccess. Updated the following files:\nM src/new_name.py\n"
+}
diff --git a/tests/fixtures/attribution_capture/cursor_after_file_edit.json b/tests/fixtures/attribution_capture/cursor_after_file_edit.json
new file mode 100644
index 000000000..ac2956dcd
--- /dev/null
+++ b/tests/fixtures/attribution_capture/cursor_after_file_edit.json
@@ -0,0 +1,21 @@
+{
+ "conversation_id": "c0ffee00-0000-4000-8000-0000000000aa",
+ "generation_id": "gen-42",
+ "model": "claude-sonnet-4-5",
+ "model_id": "claude-sonnet-4-5",
+ "model_params": [],
+ "hook_event_name": "afterFileEdit",
+ "cursor_version": "2.0.0",
+ "workspace_roots": [
+ "/work/demo"
+ ],
+ "user_email": "[email protected]",
+ "transcript_path": null,
+ "file_path": "/work/demo/src/billing.py",
+ "edits": [
+ {
+ "old_string": "def total(items):\n return 0\n",
+ "new_string": "def total(items):\n subtotal = sum(item.price for item in items)\n return round(subtotal * 1.2, 2)\n"
+ }
+ ]
+}
diff --git a/tests/fixtures/attribution_capture/git_ai_v3_spec_example.txt b/tests/fixtures/attribution_capture/git_ai_v3_spec_example.txt
new file mode 100644
index 000000000..3aec0fa65
--- /dev/null
+++ b/tests/fixtures/attribution_capture/git_ai_v3_spec_example.txt
@@ -0,0 +1,39 @@
+src/main.rs
+ s_c9883b05a2487d::t_9f8e7d6c5b4a32 1-10,15-20
+ s_c9883b05a2487d::t_a1b2c3d4e5f678 25,30-35
+ h_31dce776f88375 42-50
+src/lib.rs
+ s_e7f2a90b31cc48::t_deadbeef012345 1-50
+---
+{
+ "schema_version": "authorship/3.0.0",
+ "git_ai_version": "1.4.5",
+ "base_commit_sha": "7734793b756b3921c88db5375a8c156e9532447b",
+ "prompts": {},
+ "humans": {
+ "h_31dce776f88375": {
+ "author": "Developer <[email protected]>"
+ }
+ },
+ "sessions": {
+ "s_c9883b05a2487d": {
+ "agent_id": {
+ "tool": "cursor",
+ "id": "6ef2299e-a67f-432b-aa80-3d2fb4d28999",
+ "model": "claude-sonnet-4-5-20250514"
+ },
+ "human_author": "[email protected]"
+ },
+ "s_e7f2a90b31cc48": {
+ "agent_id": {
+ "tool": "claude",
+ "id": "conv_abc123def456",
+ "model": "claude-sonnet-4-5-20250514"
+ },
+ "human_author": "[email protected]",
+ "custom_attributes": {
+ "team": "backend"
+ }
+ }
+ }
+}
diff --git a/tests/unit/cli/test_agent_identity.py b/tests/unit/cli/test_agent_identity.py
index 8f7b8019a..f0c1c4796 100644
--- a/tests/unit/cli/test_agent_identity.py
+++ b/tests/unit/cli/test_agent_identity.py
@@ -72,6 +72,7 @@ def test_a_descriptor_does_not_restate_what_its_identity_says(target_id: str) ->
assert target.display_name == agent.display_name
assert target.hook_adapter == agent.hook_adapter
assert target.session_adapter == agent.session_adapter
+ assert target.capture_adapter == agent.capture_adapter
@pytest.mark.parametrize("target_id", ALL_IDS)
@@ -120,6 +121,7 @@ class _WindsurfTarget:
docs_url = None
hook_adapter = SEVENTH.hook_adapter
session_adapter = SEVENTH.session_adapter
+ capture_adapter = SEVENTH.capture_adapter
methods = ()
project_file_id = "windsurf_rules"
diff --git a/tests/unit/cli/test_agent_targets.py b/tests/unit/cli/test_agent_targets.py
index 81cbd9116..313476fd2 100644
--- a/tests/unit/cli/test_agent_targets.py
+++ b/tests/unit/cli/test_agent_targets.py
@@ -159,6 +159,21 @@ def test_a_target_cannot_reach_full_without_a_session_adapter() -> None:
assert derive_tier(_HooksOnly()) is Tier.GOOD
+def test_a_capture_adapter_does_not_move_the_tier() -> None:
+ """Capture is opt-in and off by default, so it is no depth an agent always has."""
+
+ class _Captured:
+ id = "captured"
+ display_name = "Captured"
+ docs_url = None
+ hook_adapter = "cursor"
+ session_adapter = None
+ capture_adapter = "cursor"
+ methods = get_target("cursor").methods
+
+ assert derive_tier(_Captured()) is derive_tier(get_target("cursor")) is Tier.GOOD
+
+
@pytest.mark.parametrize(
("provides", "tier"),
[
diff --git a/tests/unit/cli/test_attribution_capture_cli.py b/tests/unit/cli/test_attribution_capture_cli.py
new file mode 100644
index 000000000..930c0c6fe
--- /dev/null
+++ b/tests/unit/cli/test_attribution_capture_cli.py
@@ -0,0 +1,138 @@
+"""Edit capture on the CLI: status per agent, purge, the doctor notes check, Cursor's hook."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.attribution_cmd import attribution_group
+from repowise.cli.commands.doctor_cmd.repo_checks import _attribution_notes_check
+from repowise.core import attribution
+from repowise.core.edit_capture.binder import bind_pending
+from repowise.core.edit_capture.edits import CapturedCall, FileEdit
+from repowise.core.edit_capture.store import record_call, sidecar_dir
+
+BODY = [
+ "def settle(ledger):",
+ " balance = sum(entry.amount for entry in ledger)",
+ " fees = compute_fees(balance, ledger.currency)",
+ " return balance - fees",
+]
+
+
+def user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = tmp_path / "home" / ".repowise" / "config.yaml"
+ path.parent.mkdir(parents=True)
+ monkeypatch.setattr(attribution, "user_config_path", lambda: path)
+ for var in ("DO_NOT_TRACK", "REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"):
+ monkeypatch.delenv(var, raising=False)
+ return path
+
+
+def _git(root: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=root, check=True, capture_output=True, text=True
+ ).stdout
+
+
+def repo(tmp_path: Path, user_config: Path) -> Path:
+ root = (tmp_path / "repo").resolve()
+ (root / ".repowise").mkdir(parents=True)
+ _git(root, "init", "-q")
+ for key, value in (("user.email", "[email protected]"), ("user.name", "D"), ("commit.gpgsign", "false")):
+ _git(root, "config", key, value)
+ (root / ".gitignore").write_text(".repowise/\n", encoding="utf-8")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-q", "-m", "init")
+ return root
+
+
+def _opt_in(root: Path, user_config: Path, level: str, agents: str = "[claude-code]") -> None:
+ cfg = f"attribution:\n capture: {level}\n agents: {agents}\n"
+ (root / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
+ user_config.write_text(cfg, encoding="utf-8")
+
+
+def test_status_shows_capture_per_agent(repo: Path, user_config: Path) -> None:
+ _opt_in(repo, user_config, "local")
+ result = CliRunner().invoke(attribution_group, ["status", str(repo), "--format", "json"])
+ assert result.exit_code == 0, result.output
+ by_agent = json.loads(result.output)["capture_by_agent"]
+ assert by_agent["claude-code"] == "local"
+ assert by_agent["codex"] == "off (not in attribution.agents)"
+ assert by_agent["vscode"].startswith("no capture adapter")
+
+ text = CliRunner().invoke(attribution_group, ["status", str(repo)]).output
+ assert "capture claude-code" in text
+
+
+def test_purge_deletes_sidecar_and_our_notes_only(repo: Path, user_config: Path) -> None:
+ _opt_in(repo, user_config, "notes")
+ (repo / "other.py").write_text("print('x')\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "other")
+ other = _git(repo, "rev-parse", "HEAD").strip()
+ _git(repo, "notes", "--ref=ai", "add", "-m", "foreign\n---\n{}", other)
+
+ call = CapturedCall(tool="Edit", edits=[FileEdit("a.py", BODY)], session_id="s", cwd=str(repo))
+ record_call(repo, "claude_code", call)
+ (repo / "a.py").write_text("\n".join(BODY) + "\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", "agent")
+ ours = _git(repo, "rev-parse", "HEAD").strip()
+ assert len(bind_pending(repo, capture="notes")) == 1
+
+ result = CliRunner().invoke(attribution_group, ["purge", str(repo), "--yes"])
+ assert result.exit_code == 0, result.output
+ assert not sidecar_dir(repo).exists()
+ listing = _git(repo, "notes", "--ref=ai", "list")
+ assert other in listing and ours not in listing
+ assert "1 git-ai note(s)" in result.output
+
+
+def test_doctor_notes_check_only_at_notes_level(repo: Path, user_config: Path) -> None:
+ _opt_in(repo, user_config, "local")
+ assert _attribution_notes_check(repo) is None
+
+ _opt_in(repo, user_config, "notes")
+ no_remote = _attribution_notes_check(repo)
+ assert no_remote is not None and no_remote.ok and "no origin remote" in no_remote.detail
+
+ _git(repo, "remote", "add", "origin", "https://example.invalid/demo.git")
+ missing = _attribution_notes_check(repo)
+ assert missing is not None and not missing.ok
+ assert "remote.origin.fetch" in missing.detail and "notes.rewriteRef" in missing.detail
+
+ _git(repo, "config", "--add", "remote.origin.fetch", "+refs/notes/ai:refs/notes/ai")
+ _git(repo, "config", "--add", "notes.rewriteRef", "refs/notes/ai")
+ fine = _attribution_notes_check(repo)
+ assert fine is not None and fine.ok and "git push origin refs/notes/ai" in fine.detail
+
+
+def test_cursor_capture_hook_needs_the_user_to_opt_in(
+ user_config: Path, cursor_hooks_json: Path
+) -> None:
+ from repowise.cli.agent_targets.registry import get_target
+ from repowise.cli.agent_targets.types import Scope
+
+ target = get_target("cursor")
+ target.install(Scope.USER)
+ hooks = json.loads(cursor_hooks_json.read_text(encoding="utf-8"))["hooks"]
+ assert "afterFileEdit" not in hooks and "preToolUse" in hooks
+
+ user_config.write_text(
+ "attribution:\n capture: local\n agents: [cursor]\n", encoding="utf-8"
+ )
+ target.install(Scope.USER)
+ target.install(Scope.USER)
+ hooks = json.loads(cursor_hooks_json.read_text(encoding="utf-8"))["hooks"]
+ assert hooks["afterFileEdit"] == [{"command": "repowise augment --client cursor", "timeout": 5}]
+
+ target.uninstall(Scope.USER)
+ assert not cursor_hooks_json.exists()
diff --git a/tests/unit/edit_capture/__init__.py b/tests/unit/edit_capture/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/edit_capture/conftest.py b/tests/unit/edit_capture/conftest.py
new file mode 100644
index 000000000..edeed657b
--- /dev/null
+++ b/tests/unit/edit_capture/conftest.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core import attribution
+
+
+def user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A private user config file (absent until written), and no DO_NOT_TRACK."""
+ path = tmp_path / "home" / ".repowise" / "config.yaml"
+ path.parent.mkdir(parents=True)
+ monkeypatch.setattr(attribution, "user_config_path", lambda: path)
+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)
+ return path
+
+
+class Repo:
+ def __init__(self, root: Path) -> None:
+ self.root = root
+
+ def git(self, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=self.root, check=True, capture_output=True, text=True
+ ).stdout
+
+ def write(self, rel: str, text: str) -> None:
+ path = self.root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(text.encode("utf-8"))
+
+ def commit(self, message: str, *paths: str) -> str:
+ self.git("add", "-A", *paths) if paths else self.git("add", "-A")
+ self.git("commit", "-q", "-m", message)
+ return self.git("rev-parse", "HEAD").strip()
+
+ def configure(self, text: str) -> None:
+ self.write(".repowise/config.yaml", text)
+
+
+def repo(tmp_path: Path, user_config: Path) -> Repo:
+ root = (tmp_path / "repo").resolve()
+ root.mkdir()
+ r = Repo(root)
+ r.git("init", "-q", "-b", "main")
+ for key, value in (
+ ("user.email", "[email protected]"),
+ ("user.name", "Dev"),
+ ("commit.gpgsign", "false"),
+ ("core.autocrlf", "false"),
+ ):
+ r.git("config", key, value)
+ r.write(".gitignore", ".repowise/\n")
+ r.write("README.txt", "demo\n")
+ r.commit("init")
+ return r
diff --git a/tests/unit/edit_capture/test_binder.py b/tests/unit/edit_capture/test_binder.py
new file mode 100644
index 000000000..7a7593e26
--- /dev/null
+++ b/tests/unit/edit_capture/test_binder.py
@@ -0,0 +1,221 @@
+"""Commit binding precision: a miss always beats a false hit."""
+
+from __future__ import annotations
+
+import time
+
+from repowise.core.edit_capture.binder import bind_pending
+from repowise.core.edit_capture.edits import CapturedCall, FileEdit
+from repowise.core.edit_capture.store import (
+ EVENTS,
+ append_jsonl,
+ read_jsonl,
+ record_call,
+ sidecar_dir,
+)
+
+BODY = [
+ "def settle(ledger):",
+ " balance = sum(entry.amount for entry in ledger)",
+ " fees = compute_fees(balance, ledger.currency)",
+ " return balance - fees",
+]
+
+
+def _agent_edit(repo, path: str, lines: list[str], agent: str = "claude_code", session: str = "s1") -> None:
+ call = CapturedCall(tool="Edit", edits=[FileEdit(path, lines)], session_id=session, cwd=str(repo.root))
+ assert record_call(repo.root, agent, call) == 1
+
+
+def test_agent_lines_bind_to_the_commit(repo) -> None:
+ _agent_edit(repo, "src/settle.py", BODY)
+ repo.write("src/settle.py", "\n".join(BODY) + "\n")
+ sha = repo.commit("settle")
+ (binding,) = bind_pending(repo.root, capture="local")
+ assert binding["commit"] == sha and binding["agent"] == "claude_code"
+ assert binding["sessions"][0]["files"] == {"src/settle.py": [1, 2, 3, 4]}
+ # consumed: nothing pending any more
+ assert read_jsonl(sidecar_dir(repo.root) / EVENTS) == []
+
+
+def test_bound_commit_feeds_three_state_provenance(repo, user_config) -> None:
+ import git as gitpython
+
+ from repowise.core.ingestion.git_commit_index import load_git_ai_note_agents
+
+ _agent_edit(repo, "src/settle.py", BODY)
+ repo.write("src/settle.py", "\n".join(BODY) + "\n")
+ sha = repo.commit("settle")
+ bind_pending(repo.root, capture="local")
+ on = "attribution:\n capture: local\n agents: [claude-code]\n"
+ repo.configure(on)
+ user_config.write_text(on, encoding="utf-8")
+ notes = load_git_ai_note_agents(gitpython.Repo(repo.root), None)
+ assert notes[sha].agent == "claude" and notes[sha].source == "edit_capture"
+ # Withdrawing consent stops the stored bindings from labelling anything.
+ user_config.write_text("attribution:\n capture: off\n", encoding="utf-8")
+ assert load_git_ai_note_agents(gitpython.Repo(repo.root), None) == {}
+ user_config.write_text(on, encoding="utf-8")
+ # The init commit had no capture: absent, i.e. unknown, never human.
+ assert all(not n.human for n in notes.values()) and len(notes) == 1
+
+
+def test_capture_off_binds_nothing(repo) -> None:
+ _agent_edit(repo, "src/settle.py", BODY)
+ repo.write("src/settle.py", "\n".join(BODY) + "\n")
+ repo.commit("settle")
+ assert bind_pending(repo.root, capture="off") == []
+ assert len(read_jsonl(sidecar_dir(repo.root) / EVENTS)) == 1
+
+
+def test_boilerplate_collision_is_a_miss(repo) -> None:
+ """The agent wrote short, common lines; a human commits the same ones."""
+ _agent_edit(repo, "src/a.py", [" }", " return None", "", " pass", "else:"])
+ repo.write("src/a.py", " }\n return None\n\n pass\nelse:\n")
+ repo.commit("human")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_repeated_line_cannot_anchor(repo) -> None:
+ line = " self.assertEqual(response.status_code, 200)"
+ _agent_edit(repo, "tests/t.py", [line, line, line])
+ repo.write("tests/t.py", f"{line}\n{line}\n{line}\n")
+ repo.commit("tests")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_same_lines_in_another_file_do_not_bind(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/b.py", "\n".join(BODY) + "\n")
+ repo.commit("copy")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_a_single_line_edit_is_a_miss(repo) -> None:
+ _agent_edit(repo, "src/a.py", [BODY[1]])
+ repo.write("src/a.py", BODY[1] + "\n")
+ repo.commit("one")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_lines_two_agents_claim_are_ambiguous(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY, agent="claude_code")
+ _agent_edit(repo, "src/a.py", BODY, agent="codex")
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("both")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_human_rewrite_after_the_agent_is_not_bound(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ rewritten = [BODY[0], " total = sum(e.amount for e in ledger)", " return total"]
+ repo.write("src/a.py", "\n".join(rewritten) + "\n")
+ repo.commit("rewrote")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_crlf_capture_binds_lf_commit(repo) -> None:
+ _agent_edit(repo, "src/a.py", [line + "\r" for line in BODY])
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("lf")
+ assert len(bind_pending(repo.root, capture="local")) == 1
+
+
+def test_lf_capture_binds_crlf_commit(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\r\n".join(BODY) + "\r\n")
+ repo.commit("crlf")
+ assert len(bind_pending(repo.root, capture="local")) == 1
+
+
+def test_windows_absolute_path_lands_repo_relative(repo) -> None:
+ win = str(repo.root / "src" / "a.py").replace("/", "\\")
+ _agent_edit(repo, win, BODY)
+ (event,) = read_jsonl(sidecar_dir(repo.root) / EVENTS)
+ assert event["path"] == "src/a.py"
+
+
+def test_renamed_file_binds_through_the_rename(repo) -> None:
+ base = "".join(f"value_{i} = {i}\n" for i in range(20))
+ repo.write("src/old.py", base)
+ repo.commit("old")
+ _agent_edit(repo, "src/old.py", BODY)
+ repo.git("mv", "src/old.py", "src/new.py")
+ repo.write("src/new.py", base + "\n".join(BODY) + "\n")
+ sha = repo.commit("rename")
+ (binding,) = bind_pending(repo.root, capture="local")
+ assert binding["commit"] == sha
+ assert list(binding["sessions"][0]["files"]) == ["src/new.py"]
+
+
+def test_a_bound_hash_cannot_bind_twice(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("first")
+ assert len(bind_pending(repo.root, capture="local")) == 1
+ repo.write("src/a.py", "\n".join(BODY) + "\n\n" + "\n".join(BODY) + "\n")
+ repo.commit("human duplicate")
+ assert bind_pending(repo.root, capture="local") == []
+
+
+def test_an_event_from_after_the_commit_does_not_bind(repo) -> None:
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("human first")
+ _agent_edit(repo, "src/a.py", BODY)
+ path = sidecar_dir(repo.root) / EVENTS
+ (event,) = read_jsonl(path)
+ event["ts"] = time.time() + 3600
+ path.unlink()
+ append_jsonl(path, [event])
+ assert bind_pending(repo.root, capture="local", now=time.time() + 3600) == []
+
+
+def test_expired_events_are_dropped(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("late")
+ assert bind_pending(repo.root, capture="local", now=time.time() + 30 * 86400) == []
+ assert read_jsonl(sidecar_dir(repo.root) / EVENTS) == []
+
+
+def test_binding_stops_at_the_cursor(repo) -> None:
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("bound")
+ assert len(bind_pending(repo.root, capture="local")) == 1
+ other = [line.replace("ledger", "journal") for line in BODY]
+ _agent_edit(repo, "src/b.py", other)
+ repo.write("src/b.py", "\n".join(other) + "\n")
+ sha = repo.commit("second")
+ (binding,) = bind_pending(repo.root, capture="local")
+ assert binding["commit"] == sha
+
+
+def test_capped_run_resumes_past_the_first_batch(repo) -> None:
+ from repowise.core.edit_capture.binder import MAX_COMMITS
+
+ _agent_edit(repo, "src/a.py", BODY)
+ for i in range(MAX_COMMITS):
+ repo.git("commit", "-q", "--allow-empty", "-m", f"filler {i}")
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ sha = repo.commit("agent")
+ for i in range(3):
+ repo.git("commit", "-q", "--allow-empty", "-m", f"after {i}")
+ # The first run spends its budget on the oldest commits and stops there.
+ assert bind_pending(repo.root, capture="local") == []
+ assert len(read_jsonl(sidecar_dir(repo.root) / EVENTS)) == 1
+ (binding,) = bind_pending(repo.root, capture="local")
+ assert binding["commit"] == sha
+
+
+def test_bind_repo_uses_the_effective_level(repo, user_config) -> None:
+ from repowise.core.edit_capture.binder import bind_repo
+
+ _agent_edit(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("agent")
+ assert bind_repo(repo.root) == [] # nobody opted in
+ cfg = "attribution:\n capture: local\n agents: [claude-code]\n"
+ repo.configure(cfg)
+ user_config.write_text(cfg, encoding="utf-8")
+ assert len(bind_repo(repo.root)) == 1
diff --git a/tests/unit/edit_capture/test_edits.py b/tests/unit/edit_capture/test_edits.py
new file mode 100644
index 000000000..d1953c3c1
--- /dev/null
+++ b/tests/unit/edit_capture/test_edits.py
@@ -0,0 +1,174 @@
+"""Per-agent capture adapters on real hook payload shapes, and the transcript seam.
+
+Fixtures live in ``tests/fixtures/attribution_capture``; code and ids are
+synthetic, shapes are real. Sources: Claude Code from the 2.1.280 binary's
+PostToolUse builder plus local transcripts (``MultiEdit`` is the documented
+legacy shape, not a tool in that build); Codex from openai/codex
+``post-tool-use.command.input.schema.json`` and ``core/tests/suite/hooks.rs``;
+Cursor from cursor.com/docs/agent/hooks (``afterFileEdit``).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.agents.identity import all_identities
+from repowise.core.edit_capture.edits import CAPTURE_ADAPTERS, EXTRACTORS
+from repowise.core.edit_capture.hashing import line_hash
+from repowise.core.sessions.adapters import get_adapter, registered_adapters
+from repowise.core.sessions.events import ToolResult, ToolUse
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "attribution_capture"
+
+BILLING = [
+ " subtotal = sum(item.price for item in items)",
+ " return round(subtotal * 1.2, 2)",
+]
+
+
+def _payload(name: str) -> dict:
+ return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
+
+
+def _call(adapter: str, name: str):
+ return CAPTURE_ADAPTERS[adapter](_payload(name))
+
+
+def test_claude_code_edit_reads_the_structured_patch() -> None:
+ call = _call("claude_code", "claude_code_edit.json")
+ assert call is not None and call.tool == "Edit"
+ (edit,) = call.edits
+ assert edit.path == "/work/demo/src/billing.py"
+ assert edit.added == BILLING
+ assert call.session_id and call.call_id == "toolu_01EXAMPLE" and call.model is None
+ assert call.cwd == "/work/demo"
+
+
+def test_claude_code_windows_crlf_edit_hashes_like_the_lf_one() -> None:
+ call = _call("claude_code", "claude_code_edit_windows_crlf.json")
+ assert call is not None
+ (edit,) = call.edits
+ assert edit.path == "C:\\work\\demo\\src\\billing.py"
+ # No structuredPatch: falls back to new_string minus old_string, CR dropped.
+ assert edit.added == BILLING
+ lf = _call("claude_code", "claude_code_edit.json").edits[0]
+ assert [line_hash(x) for x in edit.added] == [line_hash(x) for x in lf.added]
+
+
+def test_claude_code_write_takes_the_whole_content() -> None:
+ (edit,) = _call("claude_code", "claude_code_write.json").edits
+ assert edit.path.endswith("report.py") and len(edit.added) == 4
+
+
+def test_claude_code_multiedit_takes_each_replacement() -> None:
+ (edit,) = _call("claude_code", "claude_code_multiedit.json").edits
+ assert edit.added == [
+ "TAX_RATE = Decimal('0.20')",
+ " return sum(item.price for item in items) * (1 + TAX_RATE)",
+ ]
+
+
+def test_a_user_modified_edit_is_not_captured() -> None:
+ assert _call("claude_code", "claude_code_edit_user_modified.json") is None
+
+
+def test_codex_apply_patch_splits_files_and_skips_deletes() -> None:
+ call = _call("codex", "codex_apply_patch.json")
+ assert call is not None and call.model == "gpt-5.5-codex"
+ assert {e.path: e.added for e in call.edits} == {
+ "src/billing.py": BILLING,
+ "src/report.py": ["def render(rows):", " header = 'name,amount'"],
+ }
+
+
+def test_codex_apply_patch_move_lands_on_the_new_path_with_crlf_stripped() -> None:
+ (edit,) = _call("codex", "codex_apply_patch_move.json").edits
+ assert edit.path == "src/new_name.py"
+ assert edit.added == ["VALUE = compute_default_value()", "LIMIT = compute_default_limit()"]
+
+
+def test_a_failed_apply_patch_wrote_nothing() -> None:
+ assert _call("codex", "codex_apply_patch_failed.json") is None
+
+
+def test_cursor_after_file_edit() -> None:
+ call = _call("cursor", "cursor_after_file_edit.json")
+ assert call is not None
+ (edit,) = call.edits
+ assert edit.path == "/work/demo/src/billing.py" and edit.added == BILLING
+ assert call.session_id.startswith("c0ffee00") and call.model == "claude-sonnet-4-5"
+ assert call.cwd == "/work/demo" and call.call_id.startswith("gen-42:")
+
+
+ ("adapter", "fixture"),
+ [
+ ("claude_code", "codex_apply_patch.json"),
+ ("codex", "cursor_after_file_edit.json"),
+ ("cursor", "claude_code_edit.json"),
+ ],
+)
+def test_an_adapter_ignores_another_agents_payload(adapter: str, fixture: str) -> None:
+ assert _call(adapter, fixture) is None
+
+
+def test_every_declared_capture_adapter_exists_and_matches_its_transcript_adapter() -> None:
+ for identity in all_identities():
+ if identity.capture_adapter is None:
+ continue
+ assert identity.capture_adapter in CAPTURE_ADAPTERS
+ assert identity.capture_adapter in EXTRACTORS
+ if identity.session_adapter:
+ assert identity.session_adapter == identity.capture_adapter
+
+
+def test_claude_transcript_tool_call_goes_through_the_same_extractor() -> None:
+ """One parser: a transcript's tool_use and toolUseResult are the hook's input and response."""
+ payload = _payload("claude_code_edit.json")
+ adapter = get_adapter("claude_code")
+ use = ToolUse(id="toolu_01EXAMPLE", name="Edit", input=payload["tool_input"])
+ result = ToolResult(tool_use_id=use.id, payload=payload["tool_response"])
+ from_transcript = adapter.file_edits(use, result)
+ from_hook = _call("claude_code", "claude_code_edit.json").edits
+ assert [(e.path, e.added) for e in from_transcript] == [(e.path, e.added) for e in from_hook]
+ assert adapter.file_edits(ToolUse(id="x", name="Read", input={"file_path": "a"})) == []
+
+
+def test_codex_rollout_apply_patch_goes_through_the_same_extractor() -> None:
+ patch = _payload("codex_apply_patch.json")["tool_input"]["command"]
+ line = json.dumps(
+ {
+ "timestamp": "2026-10-14T10:00:00Z",
+ "type": "response_item",
+ "payload": {
+ "type": "custom_tool_call",
+ "call_id": "call_apply_1",
+ "name": "apply_patch",
+ "input": patch,
+ },
+ }
+ )
+ adapter = get_adapter("codex")
+ event = adapter.normalize(line)
+ assert event is not None
+ (use,) = event.tool_uses
+ edits = adapter.file_edits(use)
+ assert {e.path for e in edits} == {"src/billing.py", "src/report.py"}
+ assert "codex" in registered_adapters()
+
+
+def test_write_overwrite_without_patch_is_a_miss() -> None:
+ from repowise.core.edit_capture.edits import claude_code_edits
+
+ same = {"file_path": "a.py", "content": "keep this line\nand this one\n"}
+ assert claude_code_edits("Write", same, {"type": "update", "structuredPatch": []}) == []
+ assert claude_code_edits("Write", same, None) == []
+
+
+def test_form_feed_stays_inside_one_line() -> None:
+ from repowise.core.edit_capture.hashing import split_lines
+
+ assert split_lines("a\x0cb\r\nc\n") == ["a\x0cb", "c"]
diff --git a/tests/unit/edit_capture/test_gate.py b/tests/unit/edit_capture/test_gate.py
new file mode 100644
index 000000000..24ed52beb
--- /dev/null
+++ b/tests/unit/edit_capture/test_gate.py
@@ -0,0 +1,130 @@
+"""The capture consent gate: enabled x capture x agents x DO_NOT_TRACK, and the hook."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.augment_cmd.edit_capture import capture_edit
+from repowise.core.edit_capture.store import EVENTS, capture_level, sidecar_dir
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "attribution_capture"
+
+_ON = "attribution:\n capture: {level}\n agents: [claude-code, codex]\n"
+
+
+ ("repo_cfg", "user_cfg", "dnt", "agent", "expected"),
+ [
+ (_ON.format(level="local"), _ON.format(level="local"), False, "claude_code", "local"),
+ (_ON.format(level="notes"), _ON.format(level="notes"), False, "codex", "notes"),
+ # stricter wins
+ (_ON.format(level="notes"), _ON.format(level="local"), False, "codex", "local"),
+ # the user never opted in
+ (_ON.format(level="local"), None, False, "claude_code", "off"),
+ # the repo never opted in
+ (None, _ON.format(level="local"), False, "claude_code", "off"),
+ # agent not listed
+ (_ON.format(level="local"), _ON.format(level="local"), False, "cursor", "off"),
+ # DO_NOT_TRACK beats everything
+ (_ON.format(level="notes"), _ON.format(level="notes"), True, "claude_code", "off"),
+ # attribution switched off
+ (
+ "attribution:\n enabled: false\n capture: local\n agents: [claude-code]\n",
+ _ON.format(level="local"),
+ False,
+ "claude_code",
+ "off",
+ ),
+ ],
+)
+def test_capture_level_matrix(
+ tmp_path: Path,
+ user_config: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ repo_cfg: str | None,
+ user_cfg: str | None,
+ dnt: bool,
+ agent: str,
+ expected: str,
+) -> None:
+ root = tmp_path / "r"
+ (root / ".repowise").mkdir(parents=True)
+ if repo_cfg is not None:
+ (root / ".repowise" / "config.yaml").write_text(repo_cfg, encoding="utf-8")
+ if user_cfg is not None:
+ user_config.write_text(user_cfg, encoding="utf-8")
+ if dnt:
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ assert capture_level(root, agent) == expected
+
+
+def _payload_in(root: Path, fixture: str) -> dict:
+ payload = json.loads((FIXTURES / fixture).read_text(encoding="utf-8"))
+ payload["cwd"] = str(root)
+ payload["tool_input"]["file_path"] = str(root / "src" / "billing.py")
+ return payload
+
+
+def test_hook_writes_nothing_when_capture_is_off(tmp_path: Path, user_config: Path) -> None:
+ root = tmp_path / "r"
+ (root / ".repowise").mkdir(parents=True)
+ assert capture_edit("claude-code", _payload_in(root, "claude_code_edit.json")) == 0
+ assert not sidecar_dir(root).exists()
+
+
+def test_hook_records_hashes_only(tmp_path: Path, user_config: Path) -> None:
+ root = (tmp_path / "r").resolve()
+ (root / ".repowise").mkdir(parents=True)
+ (root / ".repowise" / "config.yaml").write_text(_ON.format(level="local"), encoding="utf-8")
+ user_config.write_text(_ON.format(level="local"), encoding="utf-8")
+ payload = _payload_in(root, "claude_code_edit.json")
+ assert capture_edit("claude-code", payload) == 1
+ raw = (sidecar_dir(root) / EVENTS).read_text(encoding="utf-8")
+ (event,) = [json.loads(line) for line in raw.splitlines()]
+ assert event["agent"] == "claude_code" and event["path"] == "src/billing.py"
+ assert len(event["hashes"]) == 2 and event["session"] and event["call"]
+ # Never code, never the raw session id, never a prompt.
+ assert "subtotal" not in raw and payload["session_id"] not in raw
+
+
+def test_cursor_payload_never_stores_the_email(tmp_path: Path, user_config: Path) -> None:
+ root = (tmp_path / "r").resolve()
+ (root / ".repowise").mkdir(parents=True)
+ cfg = "attribution:\n capture: local\n agents: [cursor]\n"
+ (root / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
+ user_config.write_text(cfg, encoding="utf-8")
+ payload = json.loads((FIXTURES / "cursor_after_file_edit.json").read_text(encoding="utf-8"))
+ payload["workspace_roots"] = [str(root)]
+ payload["file_path"] = str(root / "src" / "billing.py")
+ assert capture_edit("cursor", payload) == 1
+ raw = (sidecar_dir(root) / EVENTS).read_text(encoding="utf-8")
+ assert "[email protected]" not in raw and '"agent":"cursor"' in raw
+
+
+def test_augment_routes_edit_payloads_to_capture(
+ tmp_path: Path, user_config: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import io
+
+ from repowise.cli.commands.augment_cmd.command import _run_augment
+
+ root = (tmp_path / "r").resolve()
+ (root / ".repowise").mkdir(parents=True)
+ cfg = "attribution:\n capture: local\n agents: [cursor, codex]\n"
+ (root / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
+ user_config.write_text(cfg, encoding="utf-8")
+
+ cursor = json.loads((FIXTURES / "cursor_after_file_edit.json").read_text(encoding="utf-8"))
+ cursor["workspace_roots"] = [str(root)]
+ cursor["file_path"] = str(root / "src" / "billing.py")
+ codex = json.loads((FIXTURES / "codex_apply_patch.json").read_text(encoding="utf-8"))
+ codex["cwd"] = str(root)
+ for client, payload in (("cursor", cursor), ("codex", codex)):
+ monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(payload)))
+ _run_augment(client=client)
+ events = [json.loads(x) for x in (sidecar_dir(root) / EVENTS).read_text().splitlines()]
+ assert sorted(e["path"] for e in events) == ["src/billing.py", "src/billing.py", "src/report.py"]
+ assert {e["agent"] for e in events} == {"cursor", "codex"}
diff --git a/tests/unit/edit_capture/test_notes.py b/tests/unit/edit_capture/test_notes.py
new file mode 100644
index 000000000..fb61a89cf
--- /dev/null
+++ b/tests/unit/edit_capture/test_notes.py
@@ -0,0 +1,131 @@
+"""git-ai v3 notes: format, rewriteRef, never overwrite, purge only ours.
+
+The format is checked against the spec's own example
+(``tests/fixtures/attribution_capture/git_ai_v3_spec_example.txt``, Git AI
+Standard v3.0.0 section 1.2.5, git-ai-project/git-ai commit ``e2411d98``).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+from repowise.core.edit_capture.binder import bind_pending
+from repowise.core.edit_capture.edits import CapturedCall, FileEdit
+from repowise.core.edit_capture.notes import (
+ NOTES_REF,
+ format_ranges,
+ purge_notes,
+ refspec_status,
+ render_note,
+ session_key,
+)
+from repowise.core.edit_capture.store import record_call
+from repowise.core.ingestion.git_indexer.agent_provenance import parse_git_ai_note
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "attribution_capture"
+BODY = [
+ "def settle(ledger):",
+ " balance = sum(entry.amount for entry in ledger)",
+ " fees = compute_fees(balance, ledger.currency)",
+ " return balance - fees",
+]
+_KEY_LINE = re.compile(r"^ s_[0-9a-f]{14}::t_[0-9a-f]{14} [0-9,-]+$")
+
+
+def _shape(note: str) -> tuple[list[str], dict]:
+ attestation, divider, metadata = note.partition("\n---\n")
+ assert divider
+ return attestation.splitlines(), json.loads(metadata)
+
+
+def test_rendered_note_has_the_spec_shape() -> None:
+ spec_lines, spec_meta = _shape(
+ (FIXTURES / "git_ai_v3_spec_example.txt").read_text(encoding="utf-8")
+ )
+ note = render_note(
+ "a" * 40,
+ [{"tool": "claude", "session": "0123456789abcdef", "model": None, "files": {"src/my file.py": [1, 2, 3, 7]}}],
+ )
+ lines, meta = _shape(note)
+ assert lines[0] == '"src/my file.py"'
+ assert _KEY_LINE.match(lines[1]) and lines[1].endswith(" 1-3,7")
+ assert meta["schema_version"] == spec_meta["schema_version"] == "authorship/3.0.0"
+ assert {"base_commit_sha", "prompts"} <= set(spec_meta) & set(meta)
+ (session,) = meta["sessions"].values()
+ assert set(session["agent_id"]) == set(next(iter(spec_meta["sessions"].values()))["agent_id"])
+ # Narrower than the spec allows: no person identity, no custom attributes.
+ assert "human_author" not in session and "humans" not in meta
+ assert all(_KEY_LINE.match(line) for line in spec_lines if line.startswith(" s_"))
+ assert parse_git_ai_note(note).agent == "claude"
+
+
+def test_session_key_and_ranges_follow_the_spec() -> None:
+ assert re.fullmatch(r"s_[0-9a-f]{14}", session_key("claude", "abc"))
+ assert format_ranges([5, 1, 2, 3, 9, 10]) == "1-3,5,9-10"
+
+
+def _capture(repo, path: str, lines: list[str]) -> None:
+ call = CapturedCall(tool="Edit", edits=[FileEdit(path, lines)], session_id="sess", cwd=str(repo.root))
+ record_call(repo.root, "claude_code", call)
+
+
+def test_notes_level_writes_a_note_and_sets_rewrite_ref(repo) -> None:
+ _capture(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ sha = repo.commit("agent")
+ assert len(bind_pending(repo.root, capture="notes")) == 1
+ note = repo.git("notes", f"--ref={NOTES_REF}", "show", sha)
+ assert note.startswith("src/a.py\n s_") and " 1-4\n" in note
+ assert parse_git_ai_note(note).agent == "claude"
+ assert NOTES_REF in repo.git("config", "--get-all", "notes.rewriteRef")
+ assert refspec_status(repo.root)["rewrite_ref"]
+
+ # The note follows an amend because of notes.rewriteRef.
+ repo.git("commit", "--amend", "-q", "-m", "agent, reworded")
+ amended = repo.git("rev-parse", "HEAD").strip()
+ assert amended != sha
+ assert "src/a.py" in repo.git("notes", f"--ref={NOTES_REF}", "show", amended)
+
+
+def test_local_level_writes_no_note(repo) -> None:
+ _capture(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ repo.commit("agent")
+ assert len(bind_pending(repo.root, capture="local")) == 1
+ assert repo.git("notes", f"--ref={NOTES_REF}", "list") == ""
+
+
+def test_a_foreign_note_is_never_overwritten_or_purged(repo) -> None:
+ _capture(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ sha = repo.commit("agent")
+ foreign = 'src/a.py\n h_0123456789abcd 1\n---\n{"schema_version": "authorship/3.0.0", "base_commit_sha": "x", "prompts": {}}'
+ repo.git("notes", f"--ref={NOTES_REF}", "add", "-m", foreign, sha)
+ assert len(bind_pending(repo.root, capture="notes")) == 1
+ assert "h_0123456789abcd" in repo.git("notes", f"--ref={NOTES_REF}", "show", sha)
+ assert purge_notes(repo.root) == 0
+ assert "h_0123456789abcd" in repo.git("notes", f"--ref={NOTES_REF}", "show", sha)
+
+
+def test_purge_removes_only_our_notes_and_our_rewrite_ref(repo) -> None:
+ repo.write("other.py", "print('x')\n")
+ other = repo.commit("other")
+ repo.git("notes", f"--ref={NOTES_REF}", "add", "-m", "foreign\n---\n{}", other)
+ _capture(repo, "src/a.py", BODY)
+ repo.write("src/a.py", "\n".join(BODY) + "\n")
+ ours = repo.commit("agent")
+ bind_pending(repo.root, capture="notes")
+ assert purge_notes(repo.root) == 1
+ listing = repo.git("notes", f"--ref={NOTES_REF}", "list")
+ assert other in listing and ours not in listing
+ assert not refspec_status(repo.root)["rewrite_ref"]
+
+
+def test_refspec_status_reads_fetch_and_push(repo) -> None:
+ assert refspec_status(repo.root) == {"remote": False, "fetch": False, "push": False, "rewrite_ref": False}
+ repo.git("remote", "add", "origin", "https://example.invalid/demo.git")
+ repo.git("config", "--add", "remote.origin.fetch", f"+{NOTES_REF}:{NOTES_REF}")
+ status = refspec_status(repo.root)
+ assert status["remote"] and status["fetch"] and not status["push"]