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.

fix(attribution): read YAML `capture: off`, keep hook stdout clean, skip stub lines, keep the bound model (#3765)

Raghav Chamadiya7607aa332240
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.py
index f334ee944..0083f36ae 100644
--- a/packages/cli/src/repowise/cli/augment_hook.py
+++ b/packages/cli/src/repowise/cli/augment_hook.py
@@ -24,6 +24,7 @@ hook installers should write ``repowise-augment`` instead.
from __future__ import annotations
+import contextlib
import sys
@@ -37,30 +38,39 @@ def _parse_client_arg(argv: list[str]) -> str | None:
def main() -> None:
- try:
- from repowise.cli.commands.augment_cmd import _run_augment
-
- _run_augment(
- client=_parse_client_arg(sys.argv[1:]), coverage_only="--coverage-only" in sys.argv
- )
- except (SystemExit, KeyboardInterrupt):
- raise
- except BaseException:
- pass
-
- # Best-effort self-heal for users whose only repowise invocation is
- # through this hook. Wrapped so a write failure never propagates back to
- # the agent.
- #
- # This is the fire that runs once per matched tool call, so it is where the
- # version stamp pays for itself: it used to parse ~/.claude/settings.json
- # every time to discover, almost always, that there was nothing to do.
- try:
- from repowise.cli.self_heal import run_editor_migrations
-
- run_editor_migrations()
- except BaseException:
- pass
+ # stdout is the agent's JSON channel: only the hook response goes there.
+ # Anything else that prints (structlog's default logger) goes to stderr.
+ response_stream = sys.stdout
+ with contextlib.redirect_stdout(sys.stderr):
+ try:
+ from repowise.cli.commands.augment_cmd import _run_augment, command
+
+ command._response_stream = response_stream
+ try:
+ _run_augment(
+ client=_parse_client_arg(sys.argv[1:]),
+ coverage_only="--coverage-only" in sys.argv,
+ )
+ finally:
+ command._response_stream = None
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except BaseException:
+ pass
+
+ # Best-effort self-heal for users whose only repowise invocation is
+ # through this hook. Wrapped so a write failure never propagates back to
+ # the agent.
+ #
+ # This is the fire that runs once per matched tool call, so it is where the
+ # version stamp pays for itself: it used to parse ~/.claude/settings.json
+ # every time to discover, almost always, that there was nothing to do.
+ try:
+ from repowise.cli.self_heal import run_editor_migrations
+
+ run_editor_migrations()
+ except BaseException:
+ pass
sys.exit(0)
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 bce47964f..6cb64f9b1 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -104,6 +104,7 @@ import contextlib
import json
import sys
from pathlib import Path
+from typing import TextIO
import click
@@ -136,6 +137,11 @@ from .wrong_path import _handle_tool_failure
#: contract, and ``tests/unit/cli/test_augment_hook_perf.py`` holds that.
_ADAPTERS: dict[str, object] = {}
+#: Where :func:`_emit_response` writes; ``None`` is ``sys.stdout``. The hook
+#: entry sets it and points ``sys.stdout`` at stderr, so a library that prints
+#: (structlog does by default) cannot corrupt the JSON response.
+_response_stream: TextIO | None = None
+
def _adapter(client: str | None):
"""The adapter for this invocation, memoized for the process."""
@@ -171,6 +177,11 @@ def augment_command(
) -> None:
"""Enrich AI agent tool calls with codebase graph context (hook mode)."""
configure_cli_logging(verbose=verbose)
+ # stdout carries the hook response; logs go to stderr.
+ with contextlib.suppress(ImportError):
+ import structlog
+
+ structlog.configure(logger_factory=structlog.PrintLoggerFactory(sys.stderr))
try:
_run_augment(client=client, coverage_only=coverage_only)
except (SystemExit, KeyboardInterrupt):
@@ -346,8 +357,9 @@ def _emit_response(event: str, result: HookResult | str, session_id: str = "") -
payload["additionalContext"] = result.context
if replacement:
payload["updatedToolOutput"] = replacement
- sys.stdout.write(json.dumps({"hookSpecificOutput": payload}))
- sys.stdout.flush()
+ out = _response_stream or sys.stdout
+ out.write(json.dumps({"hookSpecificOutput": payload}))
+ out.flush()
# Window within which an identical (event, context) emission is treated as a
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py b/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py
index ce26ec1dc..ed02899f3 100644
--- a/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py
@@ -15,12 +15,8 @@ from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from pathlib import Path
-from repowise.core.sessions.events import (
- Event,
- event_files,
- is_prose_user_text,
- relative_files,
-)
+from repowise.core.fsutils import relative_files
+from repowise.core.sessions.events import Event, event_files, is_prose_user_text
from repowise.core.sessions.staging import SessionStagingStore
__all__ = ["ProseSpan", "SpanCollector", "span_id_for"]
diff --git a/packages/core/src/repowise/core/attribution.py b/packages/core/src/repowise/core/attribution.py
index 19a708c61..864d46fc3 100644
--- a/packages/core/src/repowise/core/attribution.py
+++ b/packages/core/src/repowise/core/attribution.py
@@ -102,6 +102,12 @@ def _parse_layer(
errors.append(f"{source}: attribution.enabled must be true or false")
enabled = False
capture = block.get("capture")
+ # YAML reads a bare off/no/false as False (the documented ``capture: off``).
+ if capture is False:
+ capture = "off"
+ if capture is True:
+ errors.append(f"{source}: attribution.capture: true names no level; use local or notes")
+ capture = "off"
if capture is not None:
capture = str(capture).strip().lower()
if capture not in CAPTURE_LEVELS:
diff --git a/packages/core/src/repowise/core/edit_capture/hashing.py b/packages/core/src/repowise/core/edit_capture/hashing.py
index 6bcf7b2ab..b81fa4816 100644
--- a/packages/core/src/repowise/core/edit_capture/hashing.py
+++ b/packages/core/src/repowise/core/edit_capture/hashing.py
@@ -10,6 +10,7 @@ Only hashes leave this module; the text never does.
from __future__ import annotations
import hashlib
+import re
#: A line needs this many non-space characters, one of them alphanumeric, to
#: count toward a binding. Blank, brace-only and short lines (``}``, ``pass``,
@@ -17,6 +18,15 @@ import hashlib
#: anchor one.
MIN_SUBSTANTIVE_CHARS = 10
+#: Stub statements long enough to pass the length rule but written the same way
+#: everywhere (Python, JS, TS), so they never anchor a run either.
+_STUB_LINE = re.compile(
+ r"(?:return\s+(?:none|null|undefined|true|false)"
+ r"|raise\s+NotImplementedError(?:\(.*\))?"
+ r"|throw\s+new\s+Error\(\s*(['\"`])not\s+implemented\.?\1\s*\))\s*;?",
+ re.IGNORECASE,
+)
+
def normalize_line(line: str) -> str:
return line.rstrip("\r\n").rstrip()
@@ -41,7 +51,11 @@ def line_hash(line: str) -> str:
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)
+ return (
+ len(stripped) >= MIN_SUBSTANTIVE_CHARS
+ and any(ch.isalnum() for ch in stripped)
+ and not _STUB_LINE.fullmatch(stripped)
+ )
def opaque_id(value: str) -> str:
diff --git a/packages/core/src/repowise/core/edit_capture/store.py b/packages/core/src/repowise/core/edit_capture/store.py
index 82b0decd7..0e92d6099 100644
--- a/packages/core/src/repowise/core/edit_capture/store.py
+++ b/packages/core/src/repowise/core/edit_capture/store.py
@@ -82,7 +82,7 @@ def edit_event(agent_slug: str, call: CapturedCall, edit: FileEdit, ts: float) -
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
+ from repowise.core.fsutils import relative_files
path = path.replace("\\", "/")
if not (path.startswith("/") or (len(path) > 1 and path[1] == ":")):
@@ -154,13 +154,13 @@ def save_state(repo_root: Path | str, state: dict[str, Any]) -> None:
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] = {}
+def bound_commits(repo_root: Path | str) -> dict[str, dict[str, Any]]:
+ """``commit sha -> binding row`` for every commit the binder attributed to an agent."""
+ out: dict[str, dict[str, Any]] = {}
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
+ out[sha] = row
return out
diff --git a/packages/core/src/repowise/core/fsutils.py b/packages/core/src/repowise/core/fsutils.py
index 97fe72a35..9e5778557 100644
--- a/packages/core/src/repowise/core/fsutils.py
+++ b/packages/core/src/repowise/core/fsutils.py
@@ -4,7 +4,9 @@ from __future__ import annotations
import os
import tempfile
+from collections.abc import Iterable
from pathlib import Path
+from typing import Any
def atomic_write_text(
@@ -37,3 +39,40 @@ def atomic_write_text(
except Exception:
Path(tmp).unlink(missing_ok=True)
raise
+
+
+def relative_files(files: Iterable[str], repo_root: Any) -> list[str]:
+ """Repo-relative POSIX paths, in first-seen order; outsiders dropped.
+
+ Idempotent, and that is the point: a path already relative is returned as
+ it stands rather than resolved again. Resolving it would make the answer
+ depend on the process working directory, which is right only while that
+ happens to be the repository root and silently drops every file
+ otherwise, so a caller that stores relative paths and one reading rows
+ stored absolute before it get the same answer from the same call.
+
+ Compares as text rather than through :mod:`os.path`, because the store it
+ serves is written by whichever machine ran the agent: a Windows path has
+ to read as a path on any interpreter, not as a relative name that happens
+ to begin with a drive letter. The root match is case-insensitive for the
+ same reason, and to agree with the ``cwd`` scoping the miners already do;
+ the cost is two directories under a case-sensitive filesystem that differ
+ only in case, which the miner could not have told apart either.
+ """
+ import posixpath
+
+ root = str(repo_root).replace("\\", "/").rstrip("/")
+ prefix = root.lower() + "/"
+ out: list[str] = []
+ for f in files:
+ if not f:
+ continue
+ path = posixpath.normpath(f.replace("\\", "/"))
+ if path.startswith("/") or (len(path) > 1 and path[1] == ":"):
+ if not path.lower().startswith(prefix):
+ continue
+ path = path[len(prefix) :]
+ if path == ".." or path.startswith("../"):
+ continue
+ out.append(path)
+ return list(dict.fromkeys(out))
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 ac89d73cf..538c03035 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import functools
import json
+from collections import Counter
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
@@ -95,10 +96,27 @@ def _merge_capture_bindings(repo: object, notes: dict[str, GitAiNote]) -> None:
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)
+ for sha, row in bound_commits(root).items():
+ label = _normalize_agent_token(row["agent"].replace("_", " "), allow_slug=True)
if label and sha not in notes:
- notes[sha] = GitAiNote(agent=label, source="edit_capture")
+ notes[sha] = GitAiNote(
+ agent=label, source="edit_capture", model=_binding_model(row, row["agent"])
+ )
+
+
+def _binding_model(row: dict, agent: str) -> str | None:
+ """The model behind most of *agent*'s lines in a binding row; None if unrecorded or tied."""
+ from .git_indexer.agent_provenance import _MODEL_ID_MAXLEN, _dominant
+
+ lines: Counter[str] = Counter()
+ for session in row.get("sessions") or []:
+ if not isinstance(session, dict) or session.get("agent") != agent:
+ continue
+ model, files = session.get("model"), session.get("files")
+ if isinstance(model, str) and model.strip() and isinstance(files, dict):
+ count = sum(len(n) for n in files.values() if isinstance(n, list))
+ lines[model.strip()[:_MODEL_ID_MAXLEN]] += count
+ return _dominant(+lines)
def _git_ai_notes_log(repo: object, commit_limit: int | None) -> str:
@@ -371,7 +389,8 @@ class _CommitLabeler:
self._classifier, header, {t for t, _, _ in changes}, self._notes, self._trace_index
)
if self._sink is not None:
- self._sink.append(_sink_row(header, changes, prov, trace_hit))
+ note = self._notes.get(header["sha"])
+ self._sink.append(_sink_row(header, changes, prov, trace_hit, note))
return prov
@@ -380,6 +399,7 @@ def _sink_row(
changes: list[tuple[str, int, int]],
prov: AgentProvenance,
trace_hit: tuple[str, str, str | None] | None,
+ note: GitAiNote | None = None,
) -> dict:
return {
"sha": header["sha"],
@@ -394,15 +414,24 @@ def _sink_row(
"agent_channel": prov.channel,
"agent_confidence": prov.confidence,
"attribution": prov.attribution,
- # Model id only when the trace channel actually won: a note
- # or service-identity match can outrank the trace above, and
- # only the trace record carries a model.
- "agent_model_id": (
- trace_hit[2] if (trace_hit and prov.channel == "agent_trace") else None
- ),
+ # Model id only from the record whose channel won: a
+ # service-identity match carries none.
+ "agent_model_id": _winning_model(prov, trace_hit, note),
}
+def _winning_model(
+ prov: AgentProvenance,
+ trace_hit: tuple[str, str, str | None] | None,
+ note: GitAiNote | None,
+) -> str | None:
+ if trace_hit and prov.channel == "agent_trace":
+ return trace_hit[2]
+ if note and prov.agent and prov.channel == note.source:
+ return note.model
+ return None
+
+
class _FileBuckets:
"""Per-file commit records, newest first, for *files* only.
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 e8b28afba..e7f7776e2 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
@@ -240,6 +240,8 @@ class GitAiNote:
# 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"
+ # The agent's most common recorded model, ``None`` when unrecorded or tied.
+ model: str | None = None
# A note is a few KB; past this it is not read (a hostile or broken ref must
@@ -279,15 +281,22 @@ def parse_git_ai_note(note: str) -> GitAiNote:
return GitAiNote()
entries = data.get("sessions") or data.get("prompts") or {}
counts: dict[str, int] = {}
+ models: dict[str, Counter[str]] = {}
for entry in entries.values() if isinstance(entries, dict) else []:
- tool = ((entry or {}).get("agent_id") or {}).get("tool")
+ agent_id = (entry or {}).get("agent_id") or {}
+ tool = agent_id.get("tool")
agent = _normalize_agent_token(str(tool), allow_slug=True) if tool else None
if agent:
counts[agent] = counts.get(agent, 0) + 1
+ model = str(agent_id.get("model") or "").strip()
+ if model and model != "unknown":
+ models.setdefault(agent, Counter())[model[:_MODEL_ID_MAXLEN]] += 1
if counts:
top = max(counts.values())
leaders = [a for a, c in counts.items() if c == top]
- return GitAiNote(agent=leaders[0] if len(leaders) == 1 else None)
+ if len(leaders) != 1:
+ return GitAiNote()
+ return GitAiNote(agent=leaders[0], model=_dominant(models.get(leaders[0])))
human_keys = ai_keys = 0
paths: set[str] = set()
for line in lines[:div]:
diff --git a/packages/core/src/repowise/core/precedent/transcript_episodes.py b/packages/core/src/repowise/core/precedent/transcript_episodes.py
index 0e94a1fb2..10a1f2042 100644
--- a/packages/core/src/repowise/core/precedent/transcript_episodes.py
+++ b/packages/core/src/repowise/core/precedent/transcript_episodes.py
@@ -39,13 +39,14 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from repowise.core.fsutils import relative_files
from repowise.core.precedent.store import (
_IN_CHUNK,
TIER_TRANSCRIPT,
Episode,
EpisodeStore,
)
-from repowise.core.sessions.events import event_files, is_prose_user_text, relative_files
+from repowise.core.sessions.events import event_files, is_prose_user_text
_log = logging.getLogger(__name__)
diff --git a/packages/core/src/repowise/core/sessions/events.py b/packages/core/src/repowise/core/sessions/events.py
index 635672775..3f849c249 100644
--- a/packages/core/src/repowise/core/sessions/events.py
+++ b/packages/core/src/repowise/core/sessions/events.py
@@ -155,43 +155,6 @@ def is_prose_user_text(event: Event) -> bool:
return bool(text) and not text.startswith("<")
-def relative_files(files: Iterable[str], repo_root: Any) -> list[str]:
- """Repo-relative POSIX paths, in first-seen order; outsiders dropped.
-
- Idempotent, and that is the point: a path already relative is returned as
- it stands rather than resolved again. Resolving it would make the answer
- depend on the process working directory, which is right only while that
- happens to be the repository root and silently drops every file
- otherwise, so a caller that stores relative paths and one reading rows
- stored absolute before it get the same answer from the same call.
-
- Compares as text rather than through :mod:`os.path`, because the store it
- serves is written by whichever machine ran the agent: a Windows path has
- to read as a path on any interpreter, not as a relative name that happens
- to begin with a drive letter. The root match is case-insensitive for the
- same reason, and to agree with the ``cwd`` scoping the miners already do;
- the cost is two directories under a case-sensitive filesystem that differ
- only in case, which the miner could not have told apart either.
- """
- import posixpath
-
- root = str(repo_root).replace("\\", "/").rstrip("/")
- prefix = root.lower() + "/"
- out: list[str] = []
- for f in files:
- if not f:
- continue
- path = posixpath.normpath(f.replace("\\", "/"))
- if path.startswith("/") or (len(path) > 1 and path[1] == ":"):
- if not path.lower().startswith(prefix):
- continue
- path = path[len(prefix) :]
- if path == ".." or path.startswith("../"):
- continue
- out.append(path)
- return list(dict.fromkeys(out))
-
-
def iter_deduped_usage(events: Iterable[Event]) -> Iterator[Event]:
"""Events whose usage should be counted, one per API message.
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 1885bbc53..808c49eff 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -74,6 +74,7 @@ from repowise.core.analysis.decisions.scope import (
session_scope_basis,
)
from repowise.core.distill.corrections import command_anchor
+from repowise.core.fsutils import relative_files
from repowise.core.precedent.transcript_episodes import (
TranscriptEpisodeRecorder,
record_transcript_episodes,
@@ -85,7 +86,6 @@ from repowise.core.sessions.events import (
FILE_INPUT_KEYS,
event_file_touches,
is_prose_user_text,
- relative_files,
)
from repowise.core.sessions.staging import DISCOVERY_KIND, SessionStagingStore
diff --git a/tests/unit/cli/test_attribution_capture_cli.py b/tests/unit/cli/test_attribution_capture_cli.py
index 930c0c6fe..d2ade8836 100644
--- a/tests/unit/cli/test_attribution_capture_cli.py
+++ b/tests/unit/cli/test_attribution_capture_cli.py
@@ -136,3 +136,35 @@ def test_cursor_capture_hook_needs_the_user_to_opt_in(
target.uninstall(Scope.USER)
assert not cursor_hooks_json.exists()
+
+
+def test_hook_stdout_stays_json_with_an_invalid_config(repo: Path, user_config: Path) -> None:
+ """A config warning goes to stderr; stdout is the agent's JSON channel."""
+ import os
+ import sys
+
+ _opt_in(repo, user_config, "everything")
+ target = repo / "a.py"
+ target.write_text("x = 1\n", encoding="utf-8")
+ payload = {
+ "session_id": "s1",
+ "cwd": str(repo),
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Edit",
+ "tool_input": {"file_path": str(target), "old_string": "x = 1", "new_string": "x = 2"},
+ "tool_response": {"filePath": str(target), "structuredPatch": []},
+ }
+ env = dict(os.environ)
+ env["HOME"] = env["USERPROFILE"] = str(user_config.parent.parent)
+ out = subprocess.run(
+ [sys.executable, "-c", "from repowise.cli.augment_hook import main; main()"],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ env=env,
+ cwd=repo,
+ )
+ assert out.returncode == 0
+ assert "attribution_config_invalid" in out.stderr # the warning did fire
+ if out.stdout.strip():
+ json.loads(out.stdout)
diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.py
index d6e0059cf..691433b8c 100644
--- a/tests/unit/cli/test_augment_hook_perf.py
+++ b/tests/unit/cli/test_augment_hook_perf.py
@@ -603,3 +603,46 @@ def test_the_ledger_write_does_not_import_the_store(tmp_path: Path) -> None:
assert con.execute("SELECT COUNT(*) FROM savings_events").fetchone()[0] == 1
finally:
con.close()
+
+
+def test_a_captured_edit_imports_nothing_heavy(tmp_path: Path) -> None:
+ """Capture on is paid on every hooked edit, so it stays off the sessions stack too."""
+ repo = tmp_path / "repo"
+ cfg = "attribution:\n capture: local\n agents: [claude-code]\n"
+ for root in (repo, tmp_path):
+ (root / ".repowise").mkdir(parents=True, exist_ok=True)
+ (root / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
+ target = str(repo / "a.py")
+ payload = {
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Edit",
+ "cwd": str(repo),
+ "session_id": "s1",
+ "tool_input": {"file_path": target, "old_string": "x = 1", "new_string": "x = 2"},
+ "tool_response": {
+ "filePath": target,
+ "structuredPatch": [
+ {"oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1,
+ "lines": ["-x = 1", "+x = 2"]}
+ ],
+ },
+ }
+ probe = tmp_path / "payload.json"
+ probe.write_text(json.dumps(payload), encoding="utf-8")
+ prefixes = (*_HEAVY_PREFIXES, "repowise.core.sessions")
+ code = (
+ "import sys, json; "
+ "from repowise.cli.commands.augment_cmd.command import _adapter; "
+ "from repowise.cli.commands.augment_cmd.edit_capture import capture_edit; "
+ f"payload = json.loads(open({str(probe)!r}, encoding='utf-8').read()); "
+ "print(capture_edit(_adapter(None).name, payload)); "
+ f"heavy = sorted(m for m in sys.modules if m.startswith({prefixes!r})); "
+ "print('\\n'.join(heavy), file=sys.stderr)"
+ )
+ env = _fake_home(tmp_path)
+ env.pop("DO_NOT_TRACK", None)
+ out = subprocess.run(
+ [sys.executable, "-c", code], capture_output=True, text=True, check=True, env=env
+ )
+ assert out.stdout.strip() == "1", "the probe did not record the edit"
+ assert out.stderr.strip() == "", f"a captured edit pulled in:\n{out.stderr}"
diff --git a/tests/unit/edit_capture/test_binder.py b/tests/unit/edit_capture/test_binder.py
index 7a7593e26..326e1d70b 100644
--- a/tests/unit/edit_capture/test_binder.py
+++ b/tests/unit/edit_capture/test_binder.py
@@ -4,8 +4,11 @@ from __future__ import annotations
import time
+import pytest
+
from repowise.core.edit_capture.binder import bind_pending
from repowise.core.edit_capture.edits import CapturedCall, FileEdit
+from repowise.core.edit_capture.hashing import is_substantive
from repowise.core.edit_capture.store import (
EVENTS,
append_jsonl,
@@ -60,6 +63,38 @@ def test_bound_commit_feeds_three_state_provenance(repo, user_config) -> None:
assert all(not n.human for n in notes.values()) and len(notes) == 1
+def test_bound_model_reaches_the_commit_row(repo, user_config) -> None:
+ import git as gitpython
+
+ from repowise.core.ingestion.git_commit_index import _sink_row, load_git_ai_note_agents
+ from repowise.core.ingestion.git_indexer.agent_provenance import AgentProvenance
+
+ call = CapturedCall(
+ tool="apply_patch",
+ edits=[FileEdit("src/settle.py", BODY)],
+ session_id="s1",
+ model="gpt-5.5-codex",
+ cwd=str(repo.root),
+ )
+ record_call(repo.root, "codex", call)
+ 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: [codex]\n"
+ repo.configure(on)
+ user_config.write_text(on, encoding="utf-8")
+ note = load_git_ai_note_agents(gitpython.Repo(repo.root), None)[sha]
+ assert note.model == "gpt-5.5-codex"
+
+ header = {"sha": sha, "author_name": "Dev", "author_email": "[email protected]", "ts": 0}
+ header |= {"subject": "settle"}
+ won = AgentProvenance(note.agent, 2, "edit_capture", "high", "agent")
+ assert _sink_row(header, [], won, None, note)["agent_model_id"] == "gpt-5.5-codex"
+ # A channel the note did not win carries no model.
+ other = AgentProvenance(note.agent, 2, "message_footer", "high", "agent")
+ assert _sink_row(header, [], other, None, note)["agent_model_id"] is None
+
+
def test_capture_off_binds_nothing(repo) -> None:
_agent_edit(repo, "src/settle.py", BODY)
repo.write("src/settle.py", "\n".join(BODY) + "\n")
@@ -76,6 +111,47 @@ def test_boilerplate_collision_is_a_miss(repo) -> None:
assert bind_pending(repo.root, capture="local") == []
+STUBS = [
+ " return None",
+ " raise NotImplementedError('todo')",
+ " return undefined;",
+ ' throw new Error("Not implemented");',
+]
+
+
+ "line",
+ [
+ *STUBS,
+ "return null;",
+ "return False",
+ "raise NotImplementedError",
+ "throw new Error('not implemented.')",
+ ],
+)
+def test_stub_statements_are_not_substantive(line: str) -> None:
+ assert not is_substantive(line)
+
+
+ "line",
+ [
+ "return None if empty else head",
+ "raise ValueError('bad ledger')",
+ "throw new Error('ledger closed');",
+ ],
+)
+def test_real_statements_stay_substantive(line: str) -> None:
+ assert is_substantive(line)
+
+
+def test_a_stub_only_edit_is_a_miss(repo) -> None:
+ _agent_edit(repo, "src/a.py", STUBS)
+ repo.write("src/a.py", "\n".join(STUBS) + "\n")
+ repo.commit("stubs")
+ 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])
diff --git a/tests/unit/edit_capture/test_notes.py b/tests/unit/edit_capture/test_notes.py
index fb61a89cf..a40ad8fd0 100644
--- a/tests/unit/edit_capture/test_notes.py
+++ b/tests/unit/edit_capture/test_notes.py
@@ -59,6 +59,18 @@ def test_rendered_note_has_the_spec_shape() -> None:
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"
+ # render_note writes "unknown" for a missing model; that is not a model.
+ assert parse_git_ai_note(note).model is None
+
+
+def test_note_model_is_the_agents_most_common() -> None:
+ def session(sid: str, model: str | None) -> dict:
+ return {"tool": "codex", "session": sid, "model": model, "files": {"a.py": [1]}}
+
+ note = render_note("a" * 40, [session("s1", "gpt-5.5-codex"), session("s2", "gpt-5.5-codex")])
+ assert parse_git_ai_note(note).model == "gpt-5.5-codex"
+ tied = render_note("a" * 40, [session("s1", "gpt-5.5-codex"), session("s2", "o4")])
+ assert parse_git_ai_note(tied).model is None
def test_session_key_and_ranges_follow_the_spec() -> None:
diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.py
index 567ee952e..91b1478a8 100644
--- a/tests/unit/ingestion/test_agent_provenance.py
+++ b/tests/unit/ingestion/test_agent_provenance.py
@@ -332,7 +332,7 @@ def test_load_git_ai_note_agents_parses_present_ref() -> None:
note = _git_ai_note("cursor")
repo.git.log.return_value = f"\x00sha_agent\x1f{note}\n\x00sha_human\x1f\n"
agents = load_git_ai_note_agents(repo, 100)
- assert agents == {"sha_agent": GitAiNote(agent="cursor")}
+ assert agents == {"sha_agent": GitAiNote(agent="cursor", model="m")}
# ---------------------------------------------------------------------------
diff --git a/tests/unit/sessions/test_relative_files.py b/tests/unit/sessions/test_relative_files.py
index 3e5ff6a86..57da875cc 100644
--- a/tests/unit/sessions/test_relative_files.py
+++ b/tests/unit/sessions/test_relative_files.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import os
-from repowise.core.sessions.events import relative_files
+from repowise.core.fsutils import relative_files
ROOT = r"C:\Users\x\repo"
POSIX_ROOT = "/home/x/repo"
diff --git a/tests/unit/test_attribution.py b/tests/unit/test_attribution.py
index 058b60ec7..ad8b0d9b4 100644
--- a/tests/unit/test_attribution.py
+++ b/tests/unit/test_attribution.py
@@ -105,6 +105,23 @@ def test_capture_takes_the_lower_level(
assert settings.capture == effective
[email protected]("value", ["off", "no", "false", "OFF", "'off'"])
+def test_yaml_boolean_off_reads_as_off(home: Path, tmp_path: Path, value: str) -> None:
+ settings = load_attribution_settings(_repo(tmp_path, f"attribution:\n capture: {value}\n"))
+ assert settings.capture == "off"
+ assert settings.repo.capture == "off"
+ assert settings.errors == ()
+
+
[email protected]("value", ["on", "yes", "true"])
+def test_yaml_boolean_true_capture_is_invalid(home: Path, tmp_path: Path, value: str) -> None:
+ _write(home / ".repowise" / "config.yaml", "attribution:\n capture: local\n")
+ settings = load_attribution_settings(_repo(tmp_path, f"attribution:\n capture: {value}\n"))
+ assert settings.capture == "off"
+ assert len(settings.errors) == 1
+ assert "use local or notes" in settings.errors[0]
+
+
def test_agents_are_the_intersection(home: Path, tmp_path: Path) -> None:
_write(
home / ".repowise" / "config.yaml",