fixfirst 0.1.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.
fixfirst/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
fixfirst/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from fixfirst.cli import main
2
+
3
+ main()
fixfirst/cli.py ADDED
@@ -0,0 +1,777 @@
1
+ """fixfirst — makes coding agents fix their code instead of cheating around your checks.
2
+
3
+ fixfirst install once per machine: git shim + hooks for Claude Code / Codex
4
+ fixfirst verify [--ci REF] full check (the git shim runs it on `git commit`; CI: --ci <target>)
5
+ fixfirst hook post|stop called by harness hooks after a tool call / when the agent stops
6
+ fixfirst env PATH line for harness launchers, never for your own shell
7
+ fixfirst doctor wiring, base, trust
8
+
9
+ Checks: ruff always. ty, coverage, Hypothesis evidence and bandit switch on through your
10
+ committed config. Config is read from git (HEAD; --ci: the target), never from disk.
11
+ Suppressions count only if present at the base. One line per problem, nothing on success.
12
+ -v shows raw tool output.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import fnmatch
18
+ import io
19
+ import json
20
+ import os
21
+ import re
22
+ import secrets
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ import sysconfig
27
+ import tempfile
28
+ import time
29
+ import tokenize
30
+ import tomllib
31
+ import urllib.parse
32
+ import xml.etree.ElementTree as ET
33
+ from importlib import resources
34
+ from pathlib import Path
35
+
36
+ _SEP = sys.argv.index("--", 1) if "--" in sys.argv[1:] else len(sys.argv)
37
+ OWN_ARGS, PASSED_ARGS = sys.argv[1:_SEP], sys.argv[_SEP + 1 :] # after `--`: the agent's `git commit` args
38
+ VERBOSE = "-v" in OWN_ARGS
39
+ CFG_FILES = (".ruff.toml", "ruff.toml", "ty.toml", "pytest.ini", ".coveragerc")
40
+ CFG_TABLES = ("ruff", "ty", "pytest", "coverage")
41
+ DIAG = re.compile(r"^\S+?:\d+(:\d+)?: ")
42
+ SHIM_DIR = Path.home() / ".local/share/fixfirst/shim"
43
+ CLEAN_ENV = {
44
+ "PYTEST_ADDOPTS",
45
+ "PYTEST_PLUGINS",
46
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD",
47
+ "COVERAGE_RCFILE",
48
+ "COVERAGE_PROCESS_START",
49
+ "HYPOTHESIS_PROFILE",
50
+ }
51
+ NOT_NUMERICAL = frozenset({"tests", "test", "docs", "scripts", "notebooks", "migrations"})
52
+ TID_CODES = frozenset({"TID251", "TID", "ALL"})
53
+ STOP_MAX_IN_A_ROW = 2
54
+ NOTICE_INTERVAL = 86400
55
+ # ADR-0007 covered forms. ruff honours every `ruff:` form below and `flake8: noqa` (tested, ruff 0.17.5).
56
+ SUPPRESSION = re.compile(
57
+ r"\b(noqa|ruff\s*:\s*(?:ignore|file-ignore|disable)|(?:type|ty|pyright)\s*:\s*ignore|nosec"
58
+ r"|pragma\s*:\s*no\s*cover|fmt\s*:\s*(?:off|skip))\b",
59
+ re.IGNORECASE,
60
+ )
61
+ PY = ("*.py", "*.pyi")
62
+
63
+
64
+ class ConfigError(Exception):
65
+ """Committed config unusable: fail closed (ADR-0011)."""
66
+
67
+
68
+ # ------------------------------------------------------------------- helpers
69
+ def run(*cmd: str, **kw) -> subprocess.CompletedProcess[str]:
70
+ r = subprocess.run(cmd, text=True, capture_output=True, check=False, **kw)
71
+ if VERBOSE:
72
+ sys.stderr.write(f"$ {' '.join(cmd)}\n{r.stdout}{r.stderr}")
73
+ return r
74
+
75
+
76
+ def git(*args: str, **kw) -> str | None:
77
+ r = run("git", *args, **kw)
78
+ return r.stdout if r.returncode == 0 else None
79
+
80
+
81
+ def git_list(*args: str) -> list[str]:
82
+ return [f for f in (git(*args) or "").split("\0") if f]
83
+
84
+
85
+ def data(name: str) -> str:
86
+ return resources.files("fixfirst").joinpath("data", name).read_text(encoding="utf-8")
87
+
88
+
89
+ def tool_bin(name: str) -> str:
90
+ """ruff/ty from the CLI's own environment: no uvx, no network (ADR-0014)."""
91
+ for d in (Path(sys.executable).parent, Path(sysconfig.get_path("scripts"))):
92
+ if (d / name).is_file():
93
+ return str(d / name)
94
+ if found := shutil.which(name):
95
+ return found
96
+ raise RuntimeError(f"{name} not found next to {sys.executable}")
97
+
98
+
99
+ def chdir_root() -> Path | None:
100
+ out = git("rev-parse", "--show-toplevel")
101
+ if out is None:
102
+ return None
103
+ root = Path(out.strip())
104
+ os.chdir(root)
105
+ return root
106
+
107
+
108
+ def state_dir() -> Path:
109
+ d = Path((git("rev-parse", "--git-path", "fixfirst") or ".git/fixfirst").strip())
110
+ d.mkdir(parents=True, exist_ok=True)
111
+ return d
112
+
113
+
114
+ def head() -> str | None:
115
+ out = git("rev-parse", "--verify", "-q", "HEAD^{commit}")
116
+ return out.strip() if out else None
117
+
118
+
119
+ def empty_tree() -> str:
120
+ return run("git", "hash-object", "-t", "tree", "--stdin", input="").stdout.strip()
121
+
122
+
123
+ def resolve_base() -> tuple[str, str]:
124
+ """Suppression/changed-files base, fixed order (ADR-0007). Never fetches."""
125
+ if head() is None:
126
+ return empty_tree(), "empty tree (no commits)"
127
+ for ref in ("@{upstream}", "origin/HEAD"):
128
+ if out := git("merge-base", "HEAD", ref):
129
+ return out.strip(), f"merge-base with {ref}"
130
+ return head() or "HEAD", "HEAD (no upstream, no origin/HEAD)"
131
+
132
+
133
+ def changed_files(base: str) -> list[str]:
134
+ tracked = git_list("diff", "-z", "--name-only", "--no-renames", "--diff-filter=d", base, "--", *PY)
135
+ untracked = git_list("ls-files", "-z", "--others", "--exclude-standard", "--", *PY)
136
+ return sorted({f for f in tracked + untracked if Path(f).is_file()})
137
+
138
+
139
+ def diag_lines(text: str) -> list[str]:
140
+ return [line for line in text.splitlines() if DIAG.match(line)]
141
+
142
+
143
+ # ------------------------------------------------------------------- committed config
144
+ def toml(text: str | None, name: str) -> dict:
145
+ try:
146
+ return tomllib.loads(text or "")
147
+ except tomllib.TOMLDecodeError as e:
148
+ raise ConfigError(f"{name}:1: fixfirst committed {name} is not valid TOML ({e}); fix it in a commit") from e
149
+
150
+
151
+ class Config:
152
+ """Committed configuration of one ref (HEAD locally, the target in CI), written to a temp dir."""
153
+
154
+ def __init__(self, ref: str | None, tmp: Path) -> None:
155
+ self.ref, self.tmp = ref, tmp
156
+ self.pyproject_text = self.show("pyproject.toml")
157
+ self.pyproject = toml(self.pyproject_text, "pyproject.toml")
158
+ tool = self.pyproject.get("tool", {})
159
+
160
+ self.ruff_args, lint = ["--isolated"], {}
161
+ for name in (".ruff.toml", "ruff.toml"):
162
+ if (text := self.show(name)) is not None:
163
+ self.ruff_args = ["--config", str(self.write(name, text))]
164
+ parsed = toml(text, name)
165
+ lint = parsed.get("lint", parsed)
166
+ break
167
+ else:
168
+ if "ruff" in tool:
169
+ self.ruff_args = ["--config", str(self.write("ruff/pyproject.toml", self.pyproject_text))]
170
+ lint = tool["ruff"].get("lint", tool["ruff"])
171
+ self.numerical = numerical_paths(lint)
172
+
173
+ self.ty_cfg = self.write("ty.toml", text) if (text := self.show("ty.toml")) is not None else None
174
+
175
+ self.cov_cfg, self.cov_min = None, None
176
+ if (text := self.show(".coveragerc")) is not None:
177
+ self.cov_cfg = self.write("cov/.coveragerc", text)
178
+ m = re.search(r"^\s*fail_under\s*=\s*([\d.]+)", text, re.MULTILINE)
179
+ self.cov_min = m and m.group(1)
180
+ elif "coverage" in tool:
181
+ self.cov_cfg = self.write("cov/pyproject.toml", self.pyproject_text)
182
+ fu = tool["coverage"].get("report", {}).get("fail_under")
183
+ self.cov_min = None if fu is None else str(fu)
184
+
185
+ if (text := self.show("pytest.ini")) is not None:
186
+ self.pytest_cfg, self.has_pytest_cfg = self.write("pytest/pytest.ini", text), True
187
+ elif "pytest" in tool:
188
+ self.pytest_cfg, self.has_pytest_cfg = self.write("pytest/pyproject.toml", self.pyproject_text), True
189
+ else: # explicit empty config: pytest must not discover one the agent wrote
190
+ self.pytest_cfg, self.has_pytest_cfg = self.write("pytest/pytest.ini", "[pytest]\n"), False
191
+ self.testpaths = bool(tool.get("pytest", {}).get("ini_options", {}).get("testpaths"))
192
+ self.has_tests_dir = self.ref is not None and git("cat-file", "-e", f"{self.ref}:tests") is not None
193
+
194
+ def show(self, path: str) -> str | None:
195
+ return None if self.ref is None else git("show", f"{self.ref}:{path}")
196
+
197
+ def write(self, name: str, text: str | None) -> Path:
198
+ p = self.tmp / name
199
+ p.parent.mkdir(parents=True, exist_ok=True)
200
+ p.write_text(text or "", encoding="utf-8")
201
+ return p
202
+
203
+
204
+ def numerical_paths(lint: dict) -> tuple[str, ...]:
205
+ """The numerical boundary: TID251 per-file-ignores, minus non-production paths."""
206
+ pfi = {**(lint.get("per-file-ignores") or {}), **(lint.get("extend-per-file-ignores") or {})}
207
+ paths = []
208
+ for pattern, codes in pfi.items():
209
+ if not isinstance(codes, (list, tuple)) or not TID_CODES & {str(c) for c in codes}:
210
+ continue
211
+ if pattern.startswith("**"):
212
+ continue
213
+ cleaned = pattern.lstrip("./")
214
+ if cleaned.split("/")[0] in NOT_NUMERICAL:
215
+ continue
216
+ for suffix in ("/**/*.py", "/**", "/*.py", "/*"):
217
+ if cleaned.endswith(suffix):
218
+ cleaned = cleaned[: -len(suffix)]
219
+ break
220
+ paths.append(cleaned.rstrip("/"))
221
+ return tuple(paths)
222
+
223
+
224
+ # ------------------------------------------------------------------- checks
225
+ def config_changes(cfg: Config) -> list[str]:
226
+ """Config is read from git; any change on disk or in the index is reported (ADR-0003)."""
227
+ msg = "fixfirst config is read from git; your change has no effect and blocks the commit"
228
+ out = []
229
+ for name in CFG_FILES:
230
+ committed = cfg.show(name)
231
+ disk = Path(name).read_text(encoding="utf-8", errors="replace") if Path(name).is_file() else None
232
+ if disk != committed or git("show", f":{name}") != committed:
233
+ out.append(f"{name}:1: {msg}")
234
+ committed_tool = cfg.pyproject.get("tool", {})
235
+ versions = []
236
+ if Path("pyproject.toml").is_file():
237
+ versions.append(Path("pyproject.toml").read_text(encoding="utf-8", errors="replace"))
238
+ if (staged := git("show", ":pyproject.toml")) is not None:
239
+ versions.append(staged)
240
+ for text in versions:
241
+ try:
242
+ tool = tomllib.loads(text).get("tool", {})
243
+ except tomllib.TOMLDecodeError:
244
+ out.append("pyproject.toml:1: fixfirst pyproject.toml is not valid TOML")
245
+ continue
246
+ out += [
247
+ f"pyproject.toml:1: fixfirst [tool.{t}] {msg[9:]}"
248
+ for t in CFG_TABLES
249
+ if tool.get(t) != committed_tool.get(t)
250
+ ]
251
+ return out
252
+
253
+
254
+ def lint(cfg: Config, files: list[str], fix: bool) -> list[str]:
255
+ if not files:
256
+ return []
257
+ ruff = tool_bin("ruff")
258
+ common = [*cfg.ruff_args, "--force-exclude"]
259
+ if fix: # agent-changed files only (ADR-0008)
260
+ run(ruff, "check", "--fix", "-q", *common, *files)
261
+ run(ruff, "format", "-q", *common, *files)
262
+ out = diag_lines(run(ruff, "check", "--output-format", "concise", *common, *files).stdout)
263
+ out += diag_lines(run(ruff, "format", "--check", "--output-format", "concise", *common, *files).stdout)
264
+ if cfg.ty_cfg:
265
+ venv = ["--python", ".venv"] if Path(".venv").is_dir() else []
266
+ r = run(
267
+ tool_bin("ty"),
268
+ "check",
269
+ "--config-file",
270
+ str(cfg.ty_cfg),
271
+ "--output-format",
272
+ "concise",
273
+ "--force-exclude",
274
+ *venv,
275
+ *files,
276
+ )
277
+ out += [line for line in diag_lines(r.stdout) if re.search(r": (error|fatal)\b", line)]
278
+ return out
279
+
280
+
281
+ def comments(text: str) -> dict[int, str]:
282
+ """Comment text per line; falls back to a rough split for files that do not tokenize."""
283
+ found: dict[int, str] = {}
284
+ try:
285
+ for tok in tokenize.generate_tokens(io.StringIO(text).readline):
286
+ if tok.type == tokenize.COMMENT:
287
+ found[tok.start[0]] = found.get(tok.start[0], "") + tok.string
288
+ except (tokenize.TokenError, SyntaxError):
289
+ found = {n: line[line.index("#") :] for n, line in enumerate(text.splitlines(), 1) if "#" in line}
290
+ return found
291
+
292
+
293
+ def added_lines(base: str, path: str) -> set[int] | None:
294
+ """Line numbers added vs base; None = the whole file is new."""
295
+ if git("cat-file", "-e", f"{base}:{path}") is None:
296
+ return None
297
+ diff = git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", base, "--", path) or ""
298
+ lines: set[int] = set()
299
+ for start, count in re.findall(r"^@@ -\S+ \+(\d+)(?:,(\d+))? @@", diff, re.MULTILINE):
300
+ n = 1 if count == "" else int(count)
301
+ lines.update(range(int(start), int(start) + n))
302
+ return lines
303
+
304
+
305
+ def suppressions(base: str, files: list[str]) -> list[str]:
306
+ """Every suppression comment not present at the base (ADR-0007). The single judge: no --ignore-noqa."""
307
+ out = []
308
+ for f in files:
309
+ text = Path(f).read_text(encoding="utf-8", errors="replace")
310
+ added = added_lines(base, f)
311
+ for n, comment in sorted(comments(text).items()):
312
+ if (added is None or n in added) and (m := SUPPRESSION.search(comment)):
313
+ out.append(f"{f}:{n}: fixfirst suppression added (# {m.group(0)}), fix the code instead")
314
+ return out
315
+
316
+
317
+ def normalize_remote(url: str) -> str:
318
+ """`host/path` for any remote form: https/ssh/git URLs, scp-style `user@host:path`.
319
+
320
+ Drops scheme, user, port, trailing `/` and `.git`; lowercases the host. Patterns get the same
321
+ treatment, so `https://github.com/org/*` and `github.com/org/*` mean the same.
322
+ """
323
+ url = url.strip()
324
+ if "://" in url:
325
+ parts = urllib.parse.urlsplit(url)
326
+ host, path = (parts.hostname or "").lower(), parts.path
327
+ elif m := re.match(r"^(?:[^@/]+@)?([^:/]+):(.*)$", url): # scp-style
328
+ host, path = m.group(1).lower(), m.group(2)
329
+ else:
330
+ host, _, path = url.partition("/")
331
+ host = host.lower()
332
+ path = path.strip("/").removesuffix(".git").rstrip("/")
333
+ return f"{host}/{path}" if host else path
334
+
335
+
336
+ def trusted() -> bool:
337
+ """FIXFIRST_TRUST: whitespace-separated fnmatch patterns on the normalized origin URL (ADR-0013)."""
338
+ url = (git("remote", "get-url", "origin") or "").strip()
339
+ patterns = [normalize_remote(p) for p in os.environ.get("FIXFIRST_TRUST", "").split()]
340
+ return bool(url) and any(fnmatch.fnmatchcase(normalize_remote(url), p) for p in patterns)
341
+
342
+
343
+ def due(stamp: str) -> bool:
344
+ p = state_dir() / stamp
345
+ return not p.exists() or time.time() - p.stat().st_mtime > NOTICE_INTERVAL
346
+
347
+
348
+ def python_cmd() -> list[str] | None:
349
+ """The project's own `.venv` interpreter; never creates or syncs one (ADR-0014)."""
350
+ venv = Path(".venv/bin/python")
351
+ if venv.is_file() and run(str(venv), "-c", "pass").returncode == 0:
352
+ return [str(venv)]
353
+ return None
354
+
355
+
356
+ def tests(cfg: Config, base: str, ci: bool, notices: list[tuple[str, str]]) -> list[str]:
357
+ if not (cfg.has_tests_dir or cfg.has_pytest_cfg):
358
+ return []
359
+ if not ci and not trusted():
360
+ if due("notice-untrusted"):
361
+ notices.append(("notice-untrusted", "fixfirst: tests skipped, repo not trusted (FIXFIRST_TRUST)"))
362
+ return []
363
+ py = python_cmd()
364
+ if py is None:
365
+ return ["pyproject.toml:1: fixfirst project venv missing, run uv sync"]
366
+ use_cov = cfg.cov_min is not None or bool(cfg.numerical)
367
+ need = {"pytest": "tests"}
368
+ if use_cov:
369
+ need["pytest_cov"] = "coverage policy" if cfg.cov_min is not None else "Hypothesis policy"
370
+ if cfg.numerical:
371
+ need["hypothesis"] = "Hypothesis policy"
372
+ probe = "import importlib.util as u, sys; print(' '.join(m for m in sys.argv[1:] if u.find_spec(m) is None))"
373
+ missing = run(*py, "-c", probe, *need).stdout.split()
374
+ if missing:
375
+ return [
376
+ f"pyproject.toml:1: fixfirst {m.replace('_', '-')} is not installed in the project venv "
377
+ f"({need[m]} is on); add it to the dev dependencies"
378
+ for m in missing
379
+ ]
380
+
381
+ t = cfg.tmp
382
+ (t / "plugin").mkdir(exist_ok=True)
383
+ (t / "plugin/fixfirst_gate.py").write_text(resources.files("fixfirst").joinpath("policy.py").read_text())
384
+ report, receipt, junit, nonce = t / "report", t / "receipt", t / "junit.xml", secrets.token_hex(16)
385
+ env = {k: v for k, v in os.environ.items() if k not in CLEAN_ENV and not k.startswith("FIXFIRST_")}
386
+ env |= {
387
+ "PYTHONPATH": os.pathsep.join(filter(None, [str(t / "plugin"), env.get("PYTHONPATH")])),
388
+ "FIXFIRST_BASE": base,
389
+ "FIXFIRST_REPORT": str(report),
390
+ "FIXFIRST_RECEIPT": str(receipt),
391
+ "FIXFIRST_NONCE": nonce,
392
+ "FIXFIRST_COVERAGE_MIN": cfg.cov_min or "",
393
+ "FIXFIRST_NUMERICAL": "\n".join(cfg.numerical),
394
+ "FIXFIRST_HYPOTHESIS_PROFILE": "ci" if ci else "dev",
395
+ }
396
+ cmd = [
397
+ *py,
398
+ "-m",
399
+ "pytest",
400
+ "-c",
401
+ str(cfg.pytest_cfg),
402
+ "--rootdir",
403
+ str(Path.cwd()),
404
+ "-p",
405
+ "fixfirst_gate",
406
+ "-p",
407
+ "no:fixfirst",
408
+ "-p",
409
+ "no:cacheprovider",
410
+ "-q",
411
+ "--tb=short",
412
+ f"--junitxml={junit}",
413
+ "-o",
414
+ "junit_family=xunit1",
415
+ ]
416
+ if use_cov:
417
+ cmd += ["--cov", "--cov-report=", "--cov-fail-under=0"]
418
+ if cfg.cov_cfg:
419
+ cmd.append(f"--cov-config={cfg.cov_cfg}")
420
+ if not cfg.testpaths and Path("tests").is_dir():
421
+ cmd.append("tests")
422
+ r = run(*cmd, env=env)
423
+
424
+ out = [line for line in (report.read_text().splitlines() if report.exists() else []) if line]
425
+ if junit.exists():
426
+ for case in ET.parse(junit).getroot().iter("testcase"):
427
+ for kind in ("failure", "error"):
428
+ el = case.find(kind)
429
+ if el is None:
430
+ continue
431
+ msg = ((el.get("message") or kind).strip().splitlines() or [kind])[0][:200]
432
+ path = case.get("file") or case.get("classname", "").replace(".", "/") + ".py"
433
+ hits = [
434
+ (f, n)
435
+ for f, n in re.findall(r"([\w./-]+\.py):(\d+)", el.text or "")
436
+ if not f.startswith("/") and Path(f).is_file()
437
+ ]
438
+ f, n = hits[-1] if hits else (path, str(int(case.get("line", "0")) + 1))
439
+ out.append(f"{f}:{n}: test {case.get('name')}: {msg}")
440
+ if r.returncode == 5 and cfg.cov_min is not None:
441
+ out.append("tests:1: fixfirst no tests collected")
442
+ if not out and (not receipt.exists() or receipt.read_text() != nonce):
443
+ tail = (r.stdout + r.stderr).strip().splitlines()[-1:] or ["pytest did not finish"]
444
+ out.append(f"tests:1: fixfirst test run failed: {tail[0][:200]}")
445
+ return out
446
+
447
+
448
+ COMMIT_VALUE_SHORT = set("mFCct")
449
+ COMMIT_VALUE_LONG = {
450
+ "--message",
451
+ "--file",
452
+ "--reuse-message",
453
+ "--reedit-message",
454
+ "--template",
455
+ "--author",
456
+ "--date",
457
+ "--cleanup",
458
+ "--fixup",
459
+ "--squash",
460
+ "--trailer",
461
+ }
462
+
463
+
464
+ def parse_commit(args: list[str]) -> dict:
465
+ """What a `git commit` takes from where: -a, -i, -o, interactive, pathspecs."""
466
+ flags = {"all": False, "include": False, "interactive": False, "pathspecs": []}
467
+ long_flags = {
468
+ "--all": "all",
469
+ "--include": "include",
470
+ "--patch": "interactive",
471
+ "--interactive": "interactive",
472
+ "--pathspec-from-file": "interactive",
473
+ } # pathspec files cannot be predicted: like -p
474
+ i = 0
475
+ while i < len(args):
476
+ a = args[i]
477
+ if a == "--":
478
+ flags["pathspecs"] += args[i + 1 :]
479
+ break
480
+ if a.startswith("--"):
481
+ name = a.split("=", 1)[0]
482
+ if name in long_flags:
483
+ flags[long_flags[name]] = True
484
+ i += 2 if name in COMMIT_VALUE_LONG and "=" not in a else 1
485
+ continue
486
+ if a.startswith("-") and len(a) > 1:
487
+ step = 1
488
+ for j, c in enumerate(a[1:], 2):
489
+ if c in "aip":
490
+ flags[{"a": "all", "i": "include", "p": "interactive"}[c]] = True
491
+ if c in COMMIT_VALUE_SHORT:
492
+ step = 1 if j < len(a) else 2 # value attached (-mmsg) or the next arg
493
+ break
494
+ i += step
495
+ continue
496
+ flags["pathspecs"].append(a)
497
+ i += 1
498
+ return flags
499
+
500
+
501
+ def outside_commit(args: list[str], cwd: Path) -> list[str]:
502
+ """`.py` changes this commit would leave out. verify checked the whole working tree, so the commit must
503
+ contain all of it: checked tree == committed tree (ADR-0002)."""
504
+ c = parse_commit(args)
505
+ if c["interactive"]:
506
+ return [".:1: fixfirst interactive or pathspec-file commits cannot be checked; git add, then git commit"]
507
+ ref = head() or empty_tree()
508
+ untracked = set(git_list("ls-files", "-z", "--others", "--exclude-standard", "--", *PY))
509
+ unstaged = set(git_list("diff", "-z", "--name-only", "--", *PY))
510
+ if c["all"]:
511
+ outside = untracked
512
+ elif c["pathspecs"]: # pathspecs are relative to where `git commit` ran; git output is root-relative
513
+ named = set(git_list("-C", str(cwd), "diff", "-z", "--name-only", ref, "--", *c["pathspecs"]))
514
+ if c["include"]:
515
+ outside = (unstaged - named) | untracked
516
+ else: # --only (default with pathspecs): staged changes of other paths are not committed either
517
+ staged = set(git_list("diff", "-z", "--cached", "--name-only", "--", *PY))
518
+ outside = ((unstaged | staged) - named) | untracked
519
+ else:
520
+ outside = unstaged | untracked
521
+ return [f"{f}:1: fixfirst changed but not in this commit: git add it or commit -a" for f in sorted(outside)]
522
+
523
+
524
+ # ------------------------------------------------------------------- entry points
525
+ def verify(ci: str | None = None, notices: list | None = None, commit_args: list[str] | None = None) -> list[str]:
526
+ """Full check. Locally: configs from HEAD, files and suppressions vs the base. --ci: vs the target."""
527
+ notices = [] if notices is None else notices
528
+ cwd = Path.cwd()
529
+ if chdir_root() is None:
530
+ return []
531
+ if ci:
532
+ cfg_ref = ci
533
+ base = (git("merge-base", "HEAD", ci) or ci).strip()
534
+ else:
535
+ cfg_ref, (base, _) = head(), resolve_base()
536
+ files = changed_files(base)
537
+ with tempfile.TemporaryDirectory() as t:
538
+ try:
539
+ cfg = Config(cfg_ref, Path(t))
540
+ except ConfigError as e:
541
+ return [str(e)]
542
+ out = [] if ci else config_changes(cfg)
543
+ out += lint(cfg, files, fix=not ci)
544
+ out += suppressions(base, files)
545
+ out += tests(cfg, base, bool(ci), notices)
546
+ if commit_args is not None:
547
+ out += outside_commit(commit_args, cwd) # after autofix, so autofixed-but-unstaged files count
548
+ if not out and not ci:
549
+ save_stop_state({"hashes": [], "in_a_row": 0}) # verify passed (also: commit via shim)
550
+ return out
551
+
552
+
553
+ def check_changed() -> list[str]:
554
+ """Per-edit hook: files changed since the last call; report only, no rewrites (ADR-0008)."""
555
+ if chdir_root() is None:
556
+ return []
557
+ stamp = state_dir() / "post-stamp"
558
+ since = stamp.stat().st_mtime if stamp.exists() else 0
559
+ now = time.time()
560
+ base, _ = resolve_base()
561
+ files = [f for f in changed_files(base) if Path(f).stat().st_mtime > since]
562
+ out: list[str] = []
563
+ if files:
564
+ with tempfile.TemporaryDirectory() as t:
565
+ try:
566
+ cfg = Config(head(), Path(t))
567
+ except ConfigError as e:
568
+ return [str(e)]
569
+ out = config_changes(cfg) + lint(cfg, files, fix=False) + suppressions(base, files)
570
+ stamp.touch()
571
+ os.utime(stamp, (now, now)) # edits during this run are picked up next time
572
+ return out
573
+
574
+
575
+ def load_stop_state() -> dict:
576
+ try:
577
+ return json.loads((state_dir() / "stop.json").read_text())
578
+ except (OSError, ValueError):
579
+ return {"hashes": [], "in_a_row": 0}
580
+
581
+
582
+ def save_stop_state(state: dict) -> None:
583
+ (state_dir() / "stop.json").write_text(json.dumps(state))
584
+
585
+
586
+ def tree_hash() -> str:
587
+ """Hash of working tree incl. untracked files, via a throwaway index."""
588
+ with tempfile.TemporaryDirectory() as t:
589
+ idx = Path(t) / "index"
590
+ src = Path((git("rev-parse", "--git-path", "index") or "").strip())
591
+ if src.is_file():
592
+ shutil.copy(src, idx)
593
+ env = os.environ | {"GIT_INDEX_FILE": str(idx)}
594
+ run("git", "add", "-A", env=env)
595
+ return run("git", "write-tree", env=env).stdout.strip()
596
+
597
+
598
+ def stop(notices: list[tuple[str, str]]) -> list[str]:
599
+ """Stop gate with skip and cap (ADR-0011): never block one tree twice, never more than 2 in a row."""
600
+ if chdir_root() is None:
601
+ return []
602
+ untracked = git_list("ls-files", "-z", "--others", "--exclude-standard", "--", *PY)
603
+ if head() and run("git", "diff", "--quiet", "HEAD").returncode == 0 and not untracked:
604
+ return []
605
+ state = load_stop_state()
606
+ before = tree_hash()
607
+ if before in state["hashes"] or state["in_a_row"] >= STOP_MAX_IN_A_ROW:
608
+ why = "this state was blocked before" if before in state["hashes"] else "blocked twice in a row"
609
+ state["in_a_row"] = 0
610
+ save_stop_state(state)
611
+ notices.append(
612
+ (
613
+ "",
614
+ f"fixfirst: let the agent stop with problems left ({why}); the commit gate still holds, "
615
+ + "run `fixfirst verify`",
616
+ )
617
+ )
618
+ return []
619
+ lines = verify(notices=notices)
620
+ if lines:
621
+ state = load_stop_state()
622
+ state["hashes"] = [*state["hashes"], tree_hash()][-50:]
623
+ state["in_a_row"] += 1
624
+ save_stop_state(state)
625
+ return lines
626
+
627
+
628
+ # ------------------------------------------------------------------- install / env / doctor
629
+ def hooks_file_targets() -> list[tuple[str, Path]]:
630
+ home = Path.home()
631
+ return [("Claude Code", home / ".claude/settings.json"), ("Codex", home / ".codex/hooks.json")]
632
+
633
+
634
+ def merge_json_hooks(path: Path) -> None:
635
+ cur = json.loads(path.read_text()) if path.exists() else {}
636
+ hooks = cur.setdefault("hooks", {})
637
+ for event, entries in json.loads(data("hooks.json"))["hooks"].items():
638
+ lst = hooks.setdefault(event, [])
639
+ lst.extend(e for e in entries if e not in lst)
640
+ path.write_text(json.dumps(cur, indent=2) + "\n")
641
+
642
+
643
+ def install() -> None:
644
+ SHIM_DIR.mkdir(parents=True, exist_ok=True)
645
+ (SHIM_DIR / "git").write_text(data("git-shim.sh"))
646
+ (SHIM_DIR / "git").chmod(0o755)
647
+ done = [f"git shim {SHIM_DIR / 'git'}"]
648
+ for name, path in hooks_file_targets():
649
+ if path.parent.is_dir():
650
+ merge_json_hooks(path)
651
+ done.append(f"{name:<12} {path}")
652
+ print("\n".join(done))
653
+ print('\nIn every harness launcher / systemd unit (NOT your own shell): eval "$(fixfirst env)"')
654
+ print(
655
+ 'Trust for running tests (fnmatch on host/path of origin): export FIXFIRST_TRUST="gitlab.example.com/group/*"'
656
+ )
657
+ print("OpenCode: wire the same hooks via opencode-cc-hooks (unverified, see ROADMAP).")
658
+
659
+
660
+ def doctor() -> None:
661
+ from fixfirst import __version__
662
+
663
+ rows = [("fixfirst", __version__)]
664
+ for name in ("ruff", "ty"):
665
+ try:
666
+ b = tool_bin(name)
667
+ rows.append((name, f"{run(b, '--version').stdout.strip()} {b}"))
668
+ except RuntimeError as e:
669
+ rows.append((name, f"MISSING: {e}"))
670
+ shim = SHIM_DIR / "git"
671
+ first = (shutil.which("git") or "").startswith(str(SHIM_DIR))
672
+ rows.append(("git shim", f"{'installed' if shim.is_file() else 'MISSING'}; {'first' if first else 'not'} on PATH"))
673
+ for name, path in hooks_file_targets():
674
+ wired = path.is_file() and "fixfirst hook stop" in path.read_text()
675
+ rows.append((name, f"{'wired' if wired else 'not wired'} {path}"))
676
+ if chdir_root() is not None:
677
+ base, how = resolve_base()
678
+ rows.append(("base", f"{base[:12]} {how}"))
679
+ url = (git("remote", "get-url", "origin") or "").strip() or "(no origin)"
680
+ rows.append(("tests", f"{'run' if trusted() else 'SKIPPED, not trusted'} origin={url}"))
681
+ rows.append(("FIXFIRST_TRUST", os.environ.get("FIXFIRST_TRUST", "(unset)")))
682
+ print("\n".join(f"{k:<15} {v}" for k, v in rows))
683
+
684
+
685
+ # ------------------------------------------------------------------- main
686
+ def show_notices(notices: list[tuple[str, str]], as_json: bool) -> None:
687
+ """Notices are for the human, never for the model."""
688
+ if not notices:
689
+ return
690
+ text = "\n".join(n for _, n in notices)
691
+ if as_json:
692
+ print(json.dumps({"systemMessage": text}))
693
+ else:
694
+ sys.stderr.write(text + "\n")
695
+ for stamp, _ in notices:
696
+ if stamp:
697
+ (state_dir() / stamp).touch()
698
+
699
+
700
+ def emit(lines: list[str], stream) -> bool:
701
+ if lines:
702
+ stream.write("\n".join(dict.fromkeys(lines)) + "\n")
703
+ return bool(lines)
704
+
705
+
706
+ def log_error(exc_type, exc, tb) -> str:
707
+ """Traceback to .git/fixfirst/error.log, never to the model; returns where it went."""
708
+ import traceback
709
+
710
+ text = f"--- {time.strftime('%Y-%m-%d %H:%M:%S')} fixfirst {' '.join(sys.argv[1:])}\n"
711
+ text += "".join(traceback.format_exception(exc_type, exc, tb))
712
+ try:
713
+ log = state_dir() / "error.log"
714
+ with log.open("a", encoding="utf-8") as f:
715
+ f.write(text)
716
+ return str(log)
717
+ except OSError: # .git/fixfirst unusable: still never to the model
718
+ log = Path(tempfile.gettempdir()) / "fixfirst-error.log"
719
+ with log.open("a", encoding="utf-8") as f:
720
+ f.write(text)
721
+ return str(log)
722
+
723
+
724
+ def fail_closed(exc_type, exc, tb) -> None:
725
+ """verify (shim, CLI, CI): any crash refuses — a crash must not be a cheap off-switch (ADR-0011)."""
726
+ if issubclass(exc_type, KeyboardInterrupt):
727
+ sys.__excepthook__(exc_type, exc, tb)
728
+ return
729
+ log_error(exc_type, exc, tb)
730
+ if "--commit" in OWN_ARGS:
731
+ print("fixfirst internal error, commit refused; a human can commit, report the bug")
732
+ else:
733
+ print("fixfirst internal error, verify failed; traceback in .git/fixfirst/error.log")
734
+ sys.stdout.flush()
735
+ os._exit(1)
736
+
737
+
738
+ def fail_open_hook(exc_type, exc, tb) -> None:
739
+ """Hooks: a crash must not brick the agent; non-2 exits are non-blocking in the harnesses (ADR-0011)."""
740
+ where = log_error(exc_type, exc, tb)
741
+ print(json.dumps({"systemMessage": f"fixfirst internal error, check skipped: {exc_type.__name__} ({where})"}))
742
+ sys.stdout.flush()
743
+ os._exit(0)
744
+
745
+
746
+ def main() -> None:
747
+ args = [a for a in OWN_ARGS if a != "-v"]
748
+ cmd = args[0] if args else ""
749
+ notices: list[tuple[str, str]] = []
750
+ sys.excepthook = fail_closed if cmd == "verify" else fail_open_hook if cmd == "hook" else sys.excepthook
751
+ if cmd == "verify":
752
+ ci = args[args.index("--ci") + 1] if "--ci" in args[:-1] else None
753
+ commit_args = PASSED_ARGS if "--commit" in args else None
754
+ failed = emit(verify(ci, notices, commit_args), sys.stdout)
755
+ show_notices(notices, as_json=False)
756
+ sys.exit(1 if failed else 0)
757
+ if cmd == "hook" and len(args) > 1 and args[1] in ("post", "stop"):
758
+ if sys.stdin is not None and not sys.stdin.isatty():
759
+ sys.stdin.read() # payload not needed
760
+ lines = check_changed() if args[1] == "post" else stop(notices)
761
+ if emit(lines, sys.stderr):
762
+ sys.exit(2) # exit 2: stderr is fed to the model; notices wait for a quiet run
763
+ show_notices(notices, as_json=True)
764
+ sys.exit(0)
765
+ if cmd == "install":
766
+ install()
767
+ elif cmd == "env":
768
+ print(f'export PATH="{SHIM_DIR}:$PATH"')
769
+ elif cmd == "doctor":
770
+ doctor()
771
+ else:
772
+ print(__doc__)
773
+ sys.exit(2)
774
+
775
+
776
+ if __name__ == "__main__":
777
+ main()
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bash
2
+ # fixfirst git shim: first on PATH for agent harnesses only. `git commit` runs `fixfirst verify`.
3
+ self=$(dirname "$(readlink -f "$0")")
4
+ PATH=$(tr ':' '\n' <<<"$PATH" | grep -vxF "$self" | paste -sd:)
5
+ real=$(command -v git) || { echo "fixfirst shim: git not found" >&2; exit 127; }
6
+ i=1; sub=""
7
+ while [ $i -le $# ]; do
8
+ a=${!i}
9
+ case $a in
10
+ -C|-c|--git-dir|--work-tree|--namespace) i=$((i+2)) ;;
11
+ -*) i=$((i+1)) ;;
12
+ *) sub=$a; break ;;
13
+ esac
14
+ done
15
+ if [[ $sub == commit || $sub == commit-tree ]]; then
16
+ mode=()
17
+ [[ $sub == commit ]] && mode=(--commit -- "${@:$((i+1))}") # verify needs to know what git will stage
18
+ if out=$(fixfirst verify "${mode[@]}" 2>&1); then
19
+ [ -n "$out" ] && printf '%s\n' "$out" >&2
20
+ else
21
+ case $out in
22
+ "fixfirst internal error"*) printf '%s\n' "$out" >&2 ;; # exactly one line, no "fix the lines above"
23
+ *) printf '%s\ncommit refused: fix the lines above, then commit again.\n' "$out" >&2 ;;
24
+ esac
25
+ exit 1
26
+ fi
27
+ fi
28
+ exec "$real" "$@"
@@ -0,0 +1,6 @@
1
+ {
2
+ "hooks": {
3
+ "PostToolUse": [{ "matcher": ".*", "hooks": [{ "type": "command", "command": "fixfirst hook post", "timeout": 120 }] }],
4
+ "Stop": [{ "hooks": [{ "type": "command", "command": "fixfirst hook stop", "timeout": 600 }] }]
5
+ }
6
+ }
fixfirst/policy.py ADDED
@@ -0,0 +1,217 @@
1
+ """fixfirst test policy. Never imported by the CLI: the gate copies this file as `fixfirst_gate.py`
2
+ onto PYTHONPATH and starts pytest with `-p fixfirst_gate -p no:fixfirst` (ADR-0020).
3
+
4
+ Opt-in parts (decided by the gate from the committed config, passed via environment):
5
+
6
+ coverage FIXFIRST_COVERAGE_MIN: per-file minimum for every touched/changed file
7
+ hypothesis FIXFIRST_NUMERICAL: lines reached under these paths must be reached by a
8
+ Hypothesis test (paths = TID251 per-file-ignores of the committed ruff config)
9
+
10
+ Always: conftest.py may hold fixtures, never pytest hooks; no code in .tmp/.
11
+ Findings go to $FIXFIRST_REPORT, one line each. Nothing is printed.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ast
17
+ import os
18
+ import subprocess
19
+ from pathlib import Path
20
+
21
+ import pytest
22
+
23
+ REPORT = Path(os.environ.get("FIXFIRST_REPORT", os.devnull))
24
+ COVERAGE_MIN = float(os.environ["FIXFIRST_COVERAGE_MIN"]) if os.environ.get("FIXFIRST_COVERAGE_MIN") else None
25
+ NUMERICAL = tuple(p for p in os.environ.get("FIXFIRST_NUMERICAL", "").split("\n") if p)
26
+ NOT_JUDGED = frozenset({"tests", "test", "docs", "scripts", "notebooks", "migrations"})
27
+ _PREFIX = "hypothesis::"
28
+ _findings: list[str] = []
29
+
30
+ try:
31
+ from hypothesis import HealthCheck, is_hypothesis_test, settings
32
+ except ImportError: # the gate reports a missing hypothesis before pytest starts
33
+ is_hypothesis_test = None
34
+ else:
35
+ settings.register_profile("dev", max_examples=25, deadline=None)
36
+ settings.register_profile(
37
+ "ci", max_examples=500, deadline=None, print_blob=True, suppress_health_check=[HealthCheck.too_slow]
38
+ )
39
+ settings.load_profile(os.environ.get("FIXFIRST_HYPOTHESIS_PROFILE", "dev"))
40
+
41
+
42
+ def _fail(line: str) -> None:
43
+ _findings.append(line)
44
+
45
+
46
+ def _abort(lines: list[str]) -> None:
47
+ REPORT.write_text("\n".join(lines) + "\n", encoding="utf-8")
48
+ pytest.exit("fixfirst policy violation", returncode=3)
49
+
50
+
51
+ def _check_conftests(config) -> None:
52
+ bad = []
53
+ for plugin in config.pluginmanager.get_plugins():
54
+ path = getattr(plugin, "__file__", "") or ""
55
+ if Path(path).name != "conftest.py":
56
+ continue
57
+ names = sorted(n for n, v in vars(plugin).items() if n.startswith("pytest_") and callable(v))
58
+ if hasattr(plugin, "pytest_plugins"):
59
+ names.append("pytest_plugins")
60
+ if names:
61
+ rel = os.path.relpath(path, config.rootpath)
62
+ bad.append(f"{rel}:1: fixfirst conftest.py may define fixtures, not hooks/plugins ({', '.join(names)})")
63
+ if bad:
64
+ _abort(bad)
65
+
66
+
67
+ def _check_scratch(rootdir: Path) -> None:
68
+ scratch = rootdir / ".tmp"
69
+ if scratch.is_dir():
70
+ bad = [
71
+ f"{p.relative_to(rootdir)}:1: fixfirst no Python code in .tmp/, move it to src/, tests/ or scripts/"
72
+ for p in sorted(scratch.rglob("*.py"))
73
+ ]
74
+ if bad:
75
+ _abort(bad)
76
+
77
+
78
+ def pytest_sessionstart(session):
79
+ _check_conftests(session.config)
80
+ _check_scratch(Path(str(session.config.rootpath)).resolve())
81
+
82
+
83
+ def pytest_collection_finish(session):
84
+ _check_conftests(session.config) # nested conftest.py files load during collection
85
+
86
+
87
+ def _cov(config):
88
+ plugin = config.pluginmanager.get_plugin("_cov")
89
+ ctrl = getattr(plugin, "cov_controller", None) if plugin else None
90
+ return getattr(ctrl, "cov", None) if ctrl else None
91
+
92
+
93
+ def _body_lines(path: Path) -> set[int]:
94
+ """Lines inside function bodies; imports and def headers run at import time, outside any test."""
95
+ try:
96
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
97
+ except (OSError, SyntaxError):
98
+ return set()
99
+ lines: set[int] = set()
100
+ for node in ast.walk(tree):
101
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
102
+ for stmt in node.body:
103
+ lines.update(range(stmt.lineno, (stmt.end_lineno or stmt.lineno) + 1))
104
+ return lines
105
+
106
+
107
+ def _ranges(nums: list[int]) -> str:
108
+ out: list[str] = []
109
+ start = prev = None
110
+ for n in [*nums, None]:
111
+ if start is not None and n == prev + 1:
112
+ prev = n
113
+ continue
114
+ if start is not None:
115
+ out.append(f"{start}" if start == prev else f"{start}-{prev}")
116
+ start = prev = n
117
+ return ",".join(out[:8]) + (" ..." if len(out) > 8 else "")
118
+
119
+
120
+ @pytest.fixture(autouse=True)
121
+ def _fixfirst_hypothesis_context(request):
122
+ """Evidence comes from Hypothesis itself, never from a marker."""
123
+ func = getattr(request.node, "function", None)
124
+ cov = _cov(request.config)
125
+ if not NUMERICAL or is_hypothesis_test is None or cov is None or func is None or not is_hypothesis_test(func):
126
+ yield
127
+ return
128
+ cov.switch_context(f"{_PREFIX}{request.node.nodeid}")
129
+ try:
130
+ yield
131
+ finally:
132
+ cov.switch_context("")
133
+
134
+
135
+ def _changed_files(rootdir: Path) -> set[str]:
136
+ base = os.environ.get("FIXFIRST_BASE", "HEAD")
137
+ git = ["git", "-C", str(rootdir)]
138
+ diff = subprocess.run(
139
+ [*git, "diff", "-z", "--name-only", "--diff-filter=d", base, "--", "*.py"],
140
+ capture_output=True,
141
+ text=True,
142
+ check=False,
143
+ )
144
+ new = subprocess.run(
145
+ [*git, "ls-files", "-z", "--others", "--exclude-standard", "--", "*.py"],
146
+ capture_output=True,
147
+ text=True,
148
+ check=False,
149
+ )
150
+ return {f for f in (diff.stdout + new.stdout).split("\0") if f}
151
+
152
+
153
+ @pytest.hookimpl(trylast=True)
154
+ def pytest_sessionfinish(session, exitstatus):
155
+ if getattr(session.config, "workerinput", None) is not None:
156
+ return # xdist worker; the controller judges
157
+ rootdir = Path(str(session.config.rootpath)).resolve()
158
+ if COVERAGE_MIN is not None or NUMERICAL:
159
+ cov = _cov(session.config)
160
+ if cov is None:
161
+ _fail("pyproject.toml:1: fixfirst pytest-cov did not run, coverage/Hypothesis policy unverifiable")
162
+ else:
163
+ _coverage_policy(cov, rootdir)
164
+ REPORT.write_text("".join(f"{f}\n" for f in _findings), encoding="utf-8")
165
+ if _findings:
166
+ session.exitstatus = 3
167
+ receipt, nonce = os.environ.get("FIXFIRST_RECEIPT"), os.environ.get("FIXFIRST_NONCE")
168
+ if receipt and nonce and session.exitstatus == 0:
169
+ Path(receipt).write_text(nonce, encoding="utf-8")
170
+
171
+
172
+ def _coverage_policy(cov, rootdir: Path) -> None:
173
+ from coverage.exceptions import NoSource, NotPython # coverage exists whenever pytest-cov ran
174
+
175
+ data = cov.get_data()
176
+ measured: dict[str, str] = {}
177
+ for fname in data.measured_files():
178
+ p = Path(fname).resolve()
179
+ if p.is_relative_to(rootdir):
180
+ measured[p.relative_to(rootdir).as_posix()] = fname
181
+
182
+ if COVERAGE_MIN is not None:
183
+ executed = {rel for rel, f in measured.items() if data.lines(f)}
184
+ for rel in sorted(_changed_files(rootdir)):
185
+ if rel.split("/")[0] in NOT_JUDGED or Path(rel).name in ("__init__.py", "conftest.py"):
186
+ continue
187
+ if (rootdir / rel).is_file() and rel not in executed:
188
+ _fail(f"{rel}:1: fixfirst no test executes this changed file")
189
+ for rel, fname in sorted(measured.items()):
190
+ if not data.lines(fname):
191
+ continue
192
+ try:
193
+ _, stmts, _, missing, _ = cov.analysis2(fname)
194
+ except (NoSource, NotPython): # file gone or not parsable: nothing to measure
195
+ continue
196
+ if stmts:
197
+ pct = 100.0 * (len(stmts) - len(missing)) / len(stmts)
198
+ if pct < COVERAGE_MIN:
199
+ _fail(
200
+ f"{rel}:{missing[0]}: fixfirst coverage {pct:.0f}% < {COVERAGE_MIN:.0f}%, "
201
+ f"untested lines {_ranges(sorted(missing))}"
202
+ )
203
+
204
+ for rel, fname in sorted(measured.items()):
205
+ if not any(rel == p or rel.startswith(p + "/") for p in NUMERICAL):
206
+ continue
207
+ covered = set(data.lines(fname) or []) & _body_lines(Path(fname))
208
+ if not covered:
209
+ continue
210
+ contexts = data.contexts_by_lineno(fname)
211
+ proven = {n for n, labels in contexts.items() if any(c and c.startswith(_PREFIX) for c in labels)}
212
+ missing = sorted(covered - proven)
213
+ if missing:
214
+ _fail(
215
+ f"{rel}:{missing[0]}: fixfirst numerical code without a Hypothesis (@given) test, "
216
+ f"lines {_ranges(missing)}"
217
+ )
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.5
2
+ Name: fixfirst
3
+ Version: 0.1.0
4
+ Summary: Makes coding agents fix their code instead of cheating around ruff, ty and your tests
5
+ Author: fixfirst contributors
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Software Development :: Quality Assurance
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: ruff==0.17.5
13
+ Requires-Dist: ty==0.0.104
14
+ Description-Content-Type: text/markdown
15
+
16
+ # fixfirst
17
+
18
+ Makes coding agents fix their code instead of cheating around ruff, ty and your tests.
19
+ One gate that only the agent hits, configured only by your committed rules, one line per problem,
20
+ silent on success. Status: alpha (0.1.0). Design: `IDEA.md`, `docs/adr/`.
21
+
22
+ ## Setup (once per machine)
23
+
24
+ ```bash
25
+ uv tool install fixfirst
26
+ fixfirst install # git shim + hooks for Claude Code (~/.claude) and Codex (~/.codex)
27
+ ```
28
+
29
+ In each harness launcher or systemd unit — **not** in your own shell:
30
+
31
+ ```bash
32
+ eval "$(fixfirst env)" # git shim first on the agent's PATH
33
+ export FIXFIRST_TRUST="gitlab.example.com/mygroup/*" # repos whose tests may run (host/path)
34
+ ```
35
+
36
+ Per repo: nothing. The project needs a `.venv` (`uv sync`) with pytest, plus pytest-cov / hypothesis
37
+ if you switch those policies on. `fixfirst doctor` shows the wiring, the base and the trust status.
38
+
39
+ ## What runs
40
+
41
+ | check | on when (committed config) |
42
+ |---|---|
43
+ | ruff | always; `.ruff.toml` / `ruff.toml` / `[tool.ruff]`, else ruff defaults |
44
+ | bandit | ruff `S` rules selected |
45
+ | ty | `ty.toml` exists |
46
+ | coverage | coverage `fail_under` set; per touched/changed file |
47
+ | Hypothesis evidence | TID251 per-file-ignores in the ruff config (numerical boundary) |
48
+ | tests | `tests/` or a pytest config exists, and the origin matches `FIXFIRST_TRUST` |
49
+ | suppressions | always: any `noqa`, `type/ty/pyright: ignore`, `nosec`, `pragma: no cover`, `fmt: off/skip` … not present at the base |
50
+
51
+ Config is read from git (`HEAD`), never from disk: agent edits to config have no effect and block
52
+ its commit. Only changed files are checked, so old problems in untouched files never block.
53
+
54
+ When: after every agent tool call (changed files, report only), when the agent stops, and on every
55
+ `git commit` through the shim (autofix of changed files, then everything). CI:
56
+ `fixfirst verify --ci origin/<target>`.
57
+
58
+ Limits: stops lazy agents, not hostile ones — root agents, `/usr/bin/git` and sabotage from test
59
+ code are out of scope (ADR-0012). Protect `main` with CI and CODEOWNERS.
60
+
61
+ ## Source and contributions
62
+ Apache-2.0. The source ships in the package on PyPI; development happens in a private repository,
63
+ so there is no public issue tracker and no pull requests.
@@ -0,0 +1,11 @@
1
+ fixfirst/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ fixfirst/__main__.py,sha256=Xip5ii4o5COB5aeUr3UTnSG2Jn_RD5SVF0FAMnxJaFk,38
3
+ fixfirst/cli.py,sha256=vDXQe5FzBYVqsJ3Qy26B6VyJPAAlicFO8nvnBtIpOss,31200
4
+ fixfirst/policy.py,sha256=oCWxkAF8ccCHjKFCxZ692LG3ok_yfhofz9qdPa5_gbU,8383
5
+ fixfirst/data/git-shim.sh,sha256=3lC5iLp2ccqGQ4ezTcDiK14TJpZYoI5VMh1nidF9WvM,1015
6
+ fixfirst/data/hooks.json,sha256=0tJH5tPeMaqOH3IDViwRhUjTcJO2wKLDjJuvly4ZLbk,246
7
+ fixfirst-0.1.0.dist-info/METADATA,sha256=BCoa7P7aaGWFarpJq7P1DmRfoS3vXnTWZYkspGxZB-A,2786
8
+ fixfirst-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ fixfirst-0.1.0.dist-info/entry_points.txt,sha256=S0684h-wAcIbQE5Lvh3L_LeZDd20AeEecS8CHkMw9bU,47
10
+ fixfirst-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ fixfirst-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fixfirst = fixfirst.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.