fibcheck 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ """Claim schema (SPEC 5.5). Claim/ClaimList are what the LLM returns; the rest is decided by code."""
2
+
3
+ from typing import Literal
4
+
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+
8
+ class Claim(BaseModel):
9
+ model_config = ConfigDict(extra="forbid") # structured outputs requires additionalProperties: false
10
+
11
+ quote: str # exact words from the final message
12
+ kind: Literal[
13
+ "tests_pass", "tests_added", "only_touched",
14
+ "file_created", "file_modified", "file_deleted", "command_ran",
15
+ "dependency_missing", "other",
16
+ ]
17
+ subject: str | None # file path, test name, command, or package
18
+
19
+
20
+ class ClaimList(BaseModel):
21
+ model_config = ConfigDict(extra="forbid")
22
+
23
+ claims: list[Claim]
24
+
25
+
26
+ class ClaimResult(BaseModel):
27
+ claim: Claim
28
+ status: Literal["verified", "false", "unverified"]
29
+ evidence: str
30
+
31
+
32
+ class Extraction(BaseModel):
33
+ """One LLM call: parsed claims or an error, plus usage."""
34
+
35
+ claims: ClaimList | None = None
36
+ error: str | None = None
37
+ input_tokens: int = 0
38
+ output_tokens: int = 0
39
+ cost_usd: float = 0.0
40
+
41
+
42
+ class ClaimLayerResult(BaseModel):
43
+ ran: bool = False # False = skipped before any LLM call (see skipped_reason)
44
+ skipped_reason: str | None = None
45
+ error: str | None = None # extraction failed after the retry
46
+ attempts: int = 0
47
+ results: list[ClaimResult] = []
48
+ model: str | None = None
49
+ input_tokens: int = 0
50
+ output_tokens: int = 0
51
+ cost_usd: float = 0.0
@@ -0,0 +1,256 @@
1
+ r"""Claim verification graph (SPEC 5.5), built with LangGraph.
2
+
3
+ extract --(claims)--> verify --> aggregate
4
+ ^ \--(failed, 1st try)--/
5
+ \----(failed, 2nd try)-----------> aggregate ("extraction failed")
6
+ An empty claim list is not a failure: it goes to verify (nothing to verify).
7
+
8
+ The LLM only extracts. Every status below is decided by deterministic code from the evidence.
9
+ """
10
+
11
+ import re
12
+ from collections.abc import Callable
13
+ from functools import partial
14
+ from typing import TypedDict
15
+
16
+ from langgraph.graph import END, START, StateGraph
17
+
18
+ from fibcheck.checks.tests_guard import TEST_DEF
19
+ from fibcheck.claims.extract import estimate_cost, extract_claims
20
+ from fibcheck.claims.schema import Claim, ClaimLayerResult, ClaimResult, Extraction
21
+ from fibcheck.config import MODEL_PRICES, Config
22
+ from fibcheck.models import Changes, TestRun, Turn
23
+
24
+ MAX_ATTEMPTS = 2 # first try + one retry
25
+ SHELL_TOOLS = {"Bash", "PowerShell"}
26
+ Extractor = Callable[[str], Extraction]
27
+
28
+
29
+ class Evidence(TypedDict):
30
+ turn: Turn
31
+ changes: Changes
32
+ test_runs: list[TestRun]
33
+
34
+
35
+ class State(TypedDict, total=False):
36
+ final_message: str
37
+ evidence: Evidence
38
+ attempts: int
39
+ extraction: Extraction
40
+ input_tokens: int
41
+ output_tokens: int
42
+ cost_usd: float
43
+ results: list[ClaimResult]
44
+ error: str | None
45
+
46
+
47
+ # --- verifiers: (claim, evidence) -> (status, evidence text) -------------------------------------
48
+
49
+ def _norm(path: str) -> str:
50
+ return path.strip().strip("`'\"").replace("\\", "/").removeprefix("./")
51
+
52
+
53
+ def _matches(changed: str, subject: str) -> bool:
54
+ s = _norm(subject)
55
+ return bool(s) and (changed == s or changed.endswith("/" + s) or s.endswith("/" + changed))
56
+
57
+
58
+ def _find(changes: Changes, subject: str):
59
+ return next((f for f in changes.files if _matches(f.path, subject)), None)
60
+
61
+
62
+ def _tests_pass(claim: Claim, ev: Evidence) -> tuple[str, str]:
63
+ if not ev["test_runs"]:
64
+ return "unverified", "no test command ran in this turn"
65
+ last = ev["test_runs"][-1]
66
+ summary = f"last run `{last.command}`: {last.passed or 0} passed, {last.failed or 0} failed, {last.errors or 0} errors"
67
+ if last.verdict == "pass":
68
+ return "verified", summary
69
+ if last.verdict == "fail":
70
+ return "false", summary
71
+ return "unverified", f"last run `{last.command}` result could not be read"
72
+
73
+
74
+ def _tests_added(claim: Claim, ev: Evidence) -> tuple[str, str]:
75
+ if not ev["changes"].is_git_repo:
76
+ return "unverified", "not a git repository"
77
+ new = []
78
+ for f in ev["changes"].files:
79
+ removed = {m[0] for _, t in f.removed_lines if (m := re.search(r"def (test\w*)", t))}
80
+ new += [f"{f.path}::{m[1]}" for _, t in f.added_lines
81
+ if TEST_DEF.match(t) and (m := re.search(r"def (test\w*)", t)) and m[1] not in removed]
82
+ if claim.subject:
83
+ named = [n for n in new if _norm(claim.subject) in n]
84
+ new = named or new
85
+ if new:
86
+ return "verified", "new test functions: " + ", ".join(new[:5]) + (" ..." if len(new) > 5 else "")
87
+ return "false", "no new test functions in the diff"
88
+
89
+
90
+ def _only_touched(claim: Claim, ev: Evidence) -> tuple[str, str]:
91
+ if not ev["changes"].is_git_repo:
92
+ return "unverified", "not a git repository"
93
+ if not claim.subject:
94
+ return "unverified", "no files named in the claim"
95
+ claimed = [s for s in re.split(r"[,\s]+(?:and\s+)?", claim.subject) if s]
96
+ extra = [f.path for f in ev["changes"].files if not any(_matches(f.path, c) for c in claimed)]
97
+ if extra:
98
+ return "false", "also changed: " + ", ".join(extra[:8]) + (" ..." if len(extra) > 8 else "")
99
+ return "verified", f"changed files: {', '.join(f.path for f in ev['changes'].files) or 'none'}"
100
+
101
+
102
+ def _file_created(claim: Claim, ev: Evidence) -> tuple[str, str]:
103
+ if not claim.subject:
104
+ return "unverified", "no file named in the claim"
105
+ if not ev["changes"].is_git_repo:
106
+ return "unverified", "not a git repository"
107
+ f = _find(ev["changes"], claim.subject)
108
+ if f is None:
109
+ return "false", f"no new file matching '{claim.subject}' in the diff"
110
+ if f.status == "added":
111
+ return "verified", f"{f.path} is new (+{len(f.added_lines)} lines)"
112
+ return "false", f"{f.path} already existed; status: {f.status}"
113
+
114
+
115
+ def _file_modified(claim: Claim, ev: Evidence) -> tuple[str, str]:
116
+ if not claim.subject:
117
+ return "unverified", "no file named in the claim"
118
+ if not ev["changes"].is_git_repo:
119
+ return "unverified", "not a git repository"
120
+ f = _find(ev["changes"], claim.subject)
121
+ if f is None:
122
+ return "false", f"'{claim.subject}' is unchanged since HEAD"
123
+ if f.status not in ("modified", "renamed"):
124
+ return "false", f"{f.path} was {'deleted' if f.status == 'deleted' else 'newly created'}, not modified"
125
+ edited = any(_matches(_norm(str(c.input.get("file_path", ""))), f.path)
126
+ for c in ev["turn"].tool_calls if c.name in {"Write", "Edit"})
127
+ note = "" if edited else " (not via Write/Edit in this turn)"
128
+ return "verified", f"{f.path} {f.status} (+{len(f.added_lines)} -{len(f.removed_lines)}){note}"
129
+
130
+
131
+ def _file_deleted(claim: Claim, ev: Evidence) -> tuple[str, str]:
132
+ if not claim.subject:
133
+ return "unverified", "no file named in the claim"
134
+ if not ev["changes"].is_git_repo:
135
+ return "unverified", "not a git repository"
136
+ f = _find(ev["changes"], claim.subject)
137
+ if f is None:
138
+ return "false", f"'{claim.subject}' is unchanged since HEAD"
139
+ if f.status == "deleted":
140
+ return "verified", f"{f.path} deleted (-{len(f.removed_lines)} lines)"
141
+ return "false", f"{f.path} still exists; status: {f.status}"
142
+
143
+
144
+ def _squash(text: str) -> str:
145
+ return " ".join(text.split()).casefold().strip("`")
146
+
147
+
148
+ def _command_ran(claim: Claim, ev: Evidence) -> tuple[str, str]:
149
+ if not claim.subject:
150
+ return "unverified", "no command named in the claim"
151
+ want = _squash(claim.subject)
152
+ for call in ev["turn"].tool_calls:
153
+ command = call.input.get("command")
154
+ if call.name in SHELL_TOOLS and isinstance(command, str) and want in _squash(command):
155
+ return "verified", f"ran: `{command[:120]}`"
156
+ return "false", f"no shell command containing `{claim.subject}` in this turn"
157
+
158
+
159
+ def _dependency_missing(claim: Claim, ev: Evidence) -> tuple[str, str]:
160
+ if not claim.subject:
161
+ return "unverified", "no package named in the claim"
162
+ name = re.escape(claim.subject.strip())
163
+ pattern = re.compile(rf"No module named ['\"]?{name}\b|ModuleNotFoundError.*\b{name}\b|"
164
+ rf"PackageNotFoundError.*\b{name}\b", re.IGNORECASE)
165
+ for call in ev["turn"].tool_calls:
166
+ if call.result and (m := pattern.search(f"{call.result.stdout}\n{call.result.stderr}")):
167
+ return "verified", f"tool output: {m[0][:120]}"
168
+ return "unverified", f"no 'missing module' error for '{claim.subject}' in tool output"
169
+
170
+
171
+ VERIFIERS = {
172
+ "tests_pass": _tests_pass,
173
+ "tests_added": _tests_added,
174
+ "only_touched": _only_touched,
175
+ "file_created": _file_created,
176
+ "file_modified": _file_modified,
177
+ "file_deleted": _file_deleted,
178
+ "command_ran": _command_ran,
179
+ "dependency_missing": _dependency_missing,
180
+ }
181
+
182
+
183
+ def verify_claim(claim: Claim, ev: Evidence) -> ClaimResult:
184
+ verifier = VERIFIERS.get(claim.kind)
185
+ status, text = verifier(claim, ev) if verifier else ("unverified", "kind 'other' is not verified in v1")
186
+ return ClaimResult(claim=claim, status=status, evidence=text)
187
+
188
+
189
+ # --- graph ------------------------------------------------------------------------------------
190
+
191
+ def _extract_node(state: State, extractor: Extractor) -> State:
192
+ result = extractor(state["final_message"])
193
+ return {
194
+ "attempts": state.get("attempts", 0) + 1,
195
+ "extraction": result,
196
+ "input_tokens": state.get("input_tokens", 0) + result.input_tokens,
197
+ "output_tokens": state.get("output_tokens", 0) + result.output_tokens,
198
+ "cost_usd": state.get("cost_usd", 0.0) + result.cost_usd,
199
+ }
200
+
201
+
202
+ def _after_extract(state: State) -> str:
203
+ if state["extraction"].claims is not None:
204
+ return "verify" # an empty list is a valid answer: the message made no concrete claims
205
+ return "extract" if state["attempts"] < MAX_ATTEMPTS else "aggregate"
206
+
207
+
208
+ def _verify_node(state: State) -> State:
209
+ return {"results": [verify_claim(c, state["evidence"]) for c in state["extraction"].claims.claims]}
210
+
211
+
212
+ def _aggregate_node(state: State) -> State:
213
+ if "results" in state:
214
+ return {"error": None}
215
+ extraction = state["extraction"]
216
+ return {"error": extraction.error or "no parsed output", "results": []}
217
+
218
+
219
+ def build_graph(extractor: Extractor):
220
+ graph = StateGraph(State)
221
+ graph.add_node("extract", partial(_extract_node, extractor=extractor))
222
+ graph.add_node("verify", _verify_node)
223
+ graph.add_node("aggregate", _aggregate_node)
224
+ graph.add_edge(START, "extract")
225
+ graph.add_conditional_edges("extract", _after_extract, ["verify", "extract", "aggregate"])
226
+ graph.add_edge("verify", "aggregate")
227
+ graph.add_edge("aggregate", END)
228
+ return graph.compile()
229
+
230
+
231
+ def run_claim_layer(turn: Turn, changes: Changes, test_runs: list[TestRun], config: Config,
232
+ api_key: str | None, extractor: Extractor | None = None) -> ClaimLayerResult:
233
+ """Gate (no message / unknown price / cost cap), then run the graph."""
234
+ base = ClaimLayerResult(model=config.model)
235
+ if turn.final_message is None:
236
+ base.skipped_reason = "no final message (turn interrupted or unfinished)"
237
+ return base
238
+ if config.model not in MODEL_PRICES:
239
+ base.skipped_reason = f"no price known for model '{config.model}', so the cost cap can't be enforced"
240
+ return base
241
+ estimate = estimate_cost(turn.final_message, config)
242
+ if estimate > config.max_llm_cost_per_run:
243
+ base.skipped_reason = (f"estimated cost ${estimate:.4f} exceeds max_llm_cost_per_run "
244
+ f"${config.max_llm_cost_per_run:.4f}")
245
+ return base
246
+
247
+ extractor = extractor or partial(extract_claims, config=config, api_key=api_key)
248
+ state = build_graph(extractor).invoke({
249
+ "final_message": turn.final_message,
250
+ "evidence": Evidence(turn=turn, changes=changes, test_runs=test_runs),
251
+ })
252
+ return ClaimLayerResult(
253
+ ran=True, error=state.get("error"), attempts=state["attempts"], results=state.get("results", []),
254
+ model=config.model, input_tokens=state["input_tokens"], output_tokens=state["output_tokens"],
255
+ cost_usd=state["cost_usd"],
256
+ )
fibcheck/cli.py ADDED
@@ -0,0 +1,215 @@
1
+ """FibCheck command-line interface."""
2
+
3
+ import json
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ import time
8
+ from fnmatch import fnmatch
9
+ from pathlib import Path
10
+ from typing import Annotated
11
+
12
+ import typer
13
+
14
+ from fibcheck import __version__
15
+ from fibcheck.checks import run_all
16
+ from fibcheck.claims.verify import run_claim_layer
17
+ from fibcheck.collectors.diff import collect_changes
18
+ from fibcheck.collectors.test_results import parse_test_runs
19
+ from fibcheck.collectors.transcript import find_latest_session, load_turn
20
+ from fibcheck.config import DEFAULT_IGNORE, Config, load_api_key, load_config
21
+ from fibcheck.report import (
22
+ Receipt,
23
+ build_receipt,
24
+ problems_text,
25
+ render_terminal,
26
+ save_markdown,
27
+ summary_line,
28
+ )
29
+
30
+ # Exit codes (SPEC 5.6)
31
+ EXIT_OK = 0 # clean
32
+ EXIT_PROBLEMS = 1 # false claim or error-level finding
33
+ EXIT_INTERNAL_ERROR = 2 # FibCheck itself failed
34
+
35
+ NO_KEY_NOTE = "OPENAI_API_KEY not set"
36
+
37
+ app = typer.Typer(
38
+ no_args_is_help=True,
39
+ help="FibCheck: catch your coding agent's fibs. Verifies what it claimed against what it actually did.",
40
+ )
41
+
42
+
43
+ def run_check(cwd: Path, session: Path, prompt_index: int | None = None, no_llm: bool = False,
44
+ final_message: str | None = None) -> tuple[Receipt, Config, Path]:
45
+ """One full check, shared by the CLI, the Stop hook and the MCP server. Raises on failure; never prints."""
46
+ started = time.perf_counter()
47
+ turn = load_turn(session, prompt_index)
48
+ # Stop hook: the transcript may not hold the final message yet (SPEC 5.7)
49
+ turn.final_message = turn.final_message or final_message or None
50
+ changes = collect_changes(cwd)
51
+ repo = Path(changes.root) if changes.root else cwd
52
+ config = load_config(repo)
53
+ ignore = [*DEFAULT_IGNORE, *config.ignore]
54
+ changes.files = [f for f in changes.files if not any(fnmatch(f.path, pattern) for pattern in ignore)]
55
+ test_runs = parse_test_runs(turn)
56
+ findings = run_all(turn, changes, repo)
57
+
58
+ claims, note = None, None
59
+ if no_llm:
60
+ note = "--no-llm"
61
+ elif (api_key := load_api_key(repo)) is None:
62
+ note = NO_KEY_NOTE
63
+ else:
64
+ claims = run_claim_layer(turn, changes, test_runs, config, api_key)
65
+
66
+ receipt = build_receipt(session, turn, changes, test_runs, findings, claims, note,
67
+ duration_s=time.perf_counter() - started)
68
+ return receipt, config, save_markdown(receipt, repo)
69
+
70
+
71
+ def blocks(receipt: Receipt, config: Config, strict: bool) -> bool:
72
+ """Strict mode (flag or config) blocks on a false claim or an error-level finding."""
73
+ return (strict or config.strict) and receipt.exit_code == EXIT_PROBLEMS
74
+
75
+
76
+ @app.command()
77
+ def version() -> None:
78
+ """Print the FibCheck version."""
79
+ typer.echo(__version__)
80
+
81
+
82
+ @app.command()
83
+ def check(
84
+ session: Annotated[
85
+ Path | None,
86
+ typer.Option(help="Path to a Claude Code session .jsonl file."),
87
+ ] = None,
88
+ prompt_index: Annotated[
89
+ int | None,
90
+ typer.Option(help="Which human prompt's turn to analyse (default: last)."),
91
+ ] = None,
92
+ strict: Annotated[
93
+ bool, typer.Option("--strict", help="Treat failures as blocking.")
94
+ ] = False,
95
+ json_output: Annotated[
96
+ bool, typer.Option("--json", help="Output the receipt as JSON.")
97
+ ] = False,
98
+ no_llm: Annotated[
99
+ bool,
100
+ typer.Option("--no-llm", help="Run deterministic checks only (free, offline)."),
101
+ ] = False,
102
+ ) -> None:
103
+ """Check the agent's last turn and print a receipt."""
104
+ # `strict` changes nothing in the CLI: exit code 1 already signals failure; it decides blocking in the hook.
105
+ try:
106
+ cwd = Path.cwd()
107
+ session = session or find_latest_session(cwd)
108
+ if session is None:
109
+ typer.echo("No Claude Code session found for this folder; pass --session PATH.", err=True)
110
+ raise typer.Exit(EXIT_INTERNAL_ERROR)
111
+ receipt, _, _ = run_check(cwd, session, prompt_index, no_llm)
112
+ except typer.Exit:
113
+ raise
114
+ except Exception as exc: # exit code 2 = FibCheck itself failed
115
+ typer.echo(f"fibcheck failed: {type(exc).__name__}: {exc}", err=True)
116
+ raise typer.Exit(EXIT_INTERNAL_ERROR) from exc
117
+ if receipt.claims_note == NO_KEY_NOTE:
118
+ typer.echo(f"{NO_KEY_NOTE}; running deterministic checks only", err=True)
119
+ typer.echo(receipt.model_dump_json(indent=2) if json_output else render_terminal(receipt))
120
+ raise typer.Exit(receipt.exit_code)
121
+
122
+
123
+ @app.command()
124
+ def hook(
125
+ strict: Annotated[
126
+ bool, typer.Option("--strict", help="Block Claude from stopping on a false claim or error.")
127
+ ] = False,
128
+ ) -> None:
129
+ """Claude Code Stop hook: hook JSON on stdin, hook JSON on stdout. Always exits 0."""
130
+ try:
131
+ payload = json.loads(sys.stdin.buffer.read().decode("utf-8", errors="replace") or "{}")
132
+ if payload.get("stop_hook_active"):
133
+ return # Claude is already continuing because of a block: never loop
134
+ receipt, config, saved = run_check(
135
+ Path(payload["cwd"]), Path(payload["transcript_path"]),
136
+ final_message=payload.get("last_assistant_message"),
137
+ )
138
+ if blocks(receipt, config, strict):
139
+ out = {"decision": "block", "reason": problems_text(receipt)}
140
+ else:
141
+ out = {"systemMessage": summary_line(receipt, saved)}
142
+ except Exception as exc: # noqa: BLE001 - a broken hook must never break Claude Code
143
+ out = {"systemMessage": f"FibCheck hook skipped: {type(exc).__name__}: {exc}"}
144
+ typer.echo(json.dumps(out))
145
+
146
+
147
+ # --- Claude Code plugin setup (decision 60) ------------------------------------------------------
148
+
149
+ MARKETPLACE_REPO = "zeyad4231/FibCheck"
150
+ MARKETPLACE = "fibcheck"
151
+ PLUGIN = "fibcheck@fibcheck"
152
+
153
+
154
+ def _claude(claude: str, *args: str) -> subprocess.CompletedProcess:
155
+ return subprocess.run([claude, "plugin", *args], check=False, capture_output=True, text=True,
156
+ encoding="utf-8", errors="replace", timeout=300)
157
+
158
+
159
+ def _listed(claude: str, *args: str) -> list[dict]:
160
+ """`claude plugin ... --json` as a list; anything unreadable counts as empty."""
161
+ result = _claude(claude, *args, "--json")
162
+ try:
163
+ data = json.loads(result.stdout) if result.returncode == 0 else []
164
+ except ValueError:
165
+ return []
166
+ return data if isinstance(data, list) else []
167
+
168
+
169
+ def _step(claude: str, done_msg: str, *args: str) -> None:
170
+ result = _claude(claude, *args)
171
+ if result.returncode != 0:
172
+ detail = (result.stderr or result.stdout).strip()
173
+ typer.echo(f"Failed: claude plugin {' '.join(args)}\n{detail}", err=True)
174
+ raise typer.Exit(1)
175
+ typer.echo(done_msg)
176
+
177
+
178
+ def _find_claude() -> str:
179
+ claude = shutil.which("claude")
180
+ if claude is None:
181
+ typer.echo("Claude Code CLI `claude` not found on PATH. Install it first: "
182
+ "https://code.claude.com/docs/en/setup", err=True)
183
+ raise typer.Exit(1)
184
+ return claude
185
+
186
+
187
+ @app.command("install-plugin")
188
+ def install_plugin() -> None:
189
+ """Add the FibCheck marketplace and install the Claude Code plugin (safe to run twice)."""
190
+ claude = _find_claude()
191
+ if any(m.get("name") == MARKETPLACE for m in _listed(claude, "marketplace", "list")):
192
+ typer.echo(f"Marketplace '{MARKETPLACE}' already added.")
193
+ else:
194
+ _step(claude, f"Added marketplace '{MARKETPLACE}' ({MARKETPLACE_REPO}).",
195
+ "marketplace", "add", MARKETPLACE_REPO)
196
+ if any(p.get("id") == PLUGIN for p in _listed(claude, "list")):
197
+ typer.echo(f"Plugin {PLUGIN} already installed.")
198
+ else:
199
+ _step(claude, f"Installed plugin {PLUGIN}.", "install", PLUGIN)
200
+ typer.echo("Done. Restart Claude Code; a FibCheck line appears after each turn, and /fibcheck:receipt shows the full receipt.")
201
+
202
+
203
+ @app.command("uninstall-plugin")
204
+ def uninstall_plugin() -> None:
205
+ """Uninstall the Claude Code plugin and remove the FibCheck marketplace (safe to run twice)."""
206
+ claude = _find_claude()
207
+ if any(p.get("id") == PLUGIN for p in _listed(claude, "list")):
208
+ _step(claude, f"Uninstalled plugin {PLUGIN}.", "uninstall", PLUGIN)
209
+ else:
210
+ typer.echo(f"Plugin {PLUGIN} not installed.")
211
+ if any(m.get("name") == MARKETPLACE for m in _listed(claude, "marketplace", "list")):
212
+ _step(claude, f"Removed marketplace '{MARKETPLACE}'.", "marketplace", "remove", MARKETPLACE)
213
+ else:
214
+ typer.echo(f"Marketplace '{MARKETPLACE}' not configured.")
215
+ typer.echo("The fibcheck CLI itself stays installed (remove it with `uv tool uninstall fibcheck` or `pipx uninstall fibcheck`).")
@@ -0,0 +1 @@
1
+ """Evidence collectors: git diff, session transcript, test results."""
@@ -0,0 +1,116 @@
1
+ """Diff collector (SPEC 5.2): what actually changed in the working tree since HEAD."""
2
+
3
+ import os
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from fibcheck.models import Changes, FileChange
11
+
12
+ MAX_LINES_PER_FILE = 2000
13
+ _STATUS = {"A": "added", "M": "modified", "T": "modified", "D": "deleted", "R": "renamed", "C": "added"}
14
+ _HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")
15
+
16
+
17
+ def _git(repo: Path, *args: str, env: dict | None = None, stdin: bytes = b"") -> tuple[int, str]:
18
+ proc = subprocess.run(
19
+ ["git", "-C", str(repo), "-c", "core.quotepath=off", *args],
20
+ check=False, # callers inspect the return code
21
+ input=stdin,
22
+ capture_output=True,
23
+ env=env,
24
+ )
25
+ return proc.returncode, proc.stdout.decode("utf-8", errors="replace")
26
+
27
+
28
+ def collect_changes(repo_path: str | Path) -> Changes:
29
+ repo = Path(repo_path)
30
+ try:
31
+ code, out = _git(repo, "rev-parse", "--is-inside-work-tree")
32
+ except FileNotFoundError:
33
+ return Changes(is_git_repo=False, has_commits=False, warnings=["git is not installed; diff checks skipped."])
34
+ if code != 0 or out.strip() != "true":
35
+ return Changes(is_git_repo=False, has_commits=False, warnings=["Not a git repository; diff checks skipped."])
36
+
37
+ has_commits = _git(repo, "rev-parse", "--verify", "-q", "HEAD")[0] == 0
38
+ # No commits: diff against the empty tree (hash-object gives the right hash for SHA-1 or SHA-256 repos).
39
+ base = "HEAD" if has_commits else _git(repo, "hash-object", "-t", "tree", "--stdin")[1].strip()
40
+ root = _git(repo, "rev-parse", "--show-toplevel")[1].strip()
41
+ changes = Changes(is_git_repo=True, has_commits=has_commits, root=root)
42
+
43
+ # Stage everything into a throwaway copy of the index, so untracked files and plain `mv`
44
+ # renames show up in git's own diff without touching the user's real index.
45
+ # shortcut: `git add -A` writes unreachable blobs into .git/objects (gc removes them);
46
+ # switch to per-file `git hash-object` if that ever matters.
47
+ with tempfile.TemporaryDirectory() as tmp:
48
+ tmp_index = Path(tmp) / "index"
49
+ real_index = repo / _git(repo, "rev-parse", "--git-path", "index")[1].strip()
50
+ if real_index.exists():
51
+ # copy2 keeps the index mtime; a fresh mtime defeats git's racy-entry check and
52
+ # same-size edits made right after the index was written would look unchanged.
53
+ shutil.copy2(real_index, tmp_index)
54
+ env = {**os.environ, "GIT_INDEX_FILE": str(tmp_index)}
55
+ if _git(repo, "add", "-A", env=env)[0] != 0:
56
+ changes.warnings.append("git add into a temporary index failed; diff checks skipped.")
57
+ return changes
58
+ _, names = _git(repo, "diff", "--cached", "-M", "--name-status", "-z", base, env=env)
59
+ _, patch = _git(repo, "diff", "--cached", "-M", "--no-color", "--no-ext-diff", "-U0", base, env=env)
60
+
61
+ tokens = names.split("\0")
62
+ i = 0
63
+ while i < len(tokens) and tokens[i]:
64
+ letter = tokens[i][0]
65
+ if letter in "RC":
66
+ old, new = tokens[i + 1], tokens[i + 2]
67
+ i += 3
68
+ else:
69
+ old, new = None, tokens[i + 1]
70
+ i += 2
71
+ status = _STATUS.get(letter, "modified")
72
+ changes.files.append(
73
+ FileChange(
74
+ path=new.replace("\\", "/"),
75
+ status=status,
76
+ old_path=old.replace("\\", "/") if status == "renamed" else None,
77
+ )
78
+ )
79
+
80
+ sections = re.split(r"^diff --git ", patch, flags=re.MULTILINE)[1:]
81
+ if len(sections) != len(changes.files):
82
+ changes.warnings.append("Could not match the patch to the file list; line content skipped.")
83
+ return changes
84
+ for fc, section in zip(changes.files, sections):
85
+ _fill_lines(fc, section)
86
+ if fc.truncated:
87
+ changes.warnings.append(f"{fc.path}: over {MAX_LINES_PER_FILE} changed lines, truncated.")
88
+ return changes
89
+
90
+
91
+ def _fill_lines(fc: FileChange, section: str) -> None:
92
+ old_ln = new_ln = 0
93
+ in_hunk = False
94
+ for line in section.split("\n"):
95
+ if not in_hunk:
96
+ if line.startswith("Binary files ") or line == "GIT binary patch":
97
+ fc.is_binary = True
98
+ return
99
+ if not line.startswith("@@"):
100
+ continue
101
+ if m := _HUNK.match(line):
102
+ in_hunk = True
103
+ old_ln, new_ln = int(m[1]), int(m[2])
104
+ continue
105
+ if line[:1] not in ("+", "-"):
106
+ continue # "" or trailing empty string
107
+ if len(fc.added_lines) + len(fc.removed_lines) >= MAX_LINES_PER_FILE:
108
+ fc.truncated = True
109
+ return
110
+ text = line[1:].removesuffix("\r")
111
+ if line[0] == "+":
112
+ fc.added_lines.append((new_ln, text))
113
+ new_ln += 1
114
+ else:
115
+ fc.removed_lines.append((old_ln, text))
116
+ old_ln += 1