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.
- fibcheck/__init__.py +6 -0
- fibcheck/checks/__init__.py +12 -0
- fibcheck/checks/_common.py +142 -0
- fibcheck/checks/deps.py +86 -0
- fibcheck/checks/scope.py +50 -0
- fibcheck/checks/stubs.py +66 -0
- fibcheck/checks/symbols.py +137 -0
- fibcheck/checks/tests_guard.py +41 -0
- fibcheck/claims/__init__.py +1 -0
- fibcheck/claims/extract.py +90 -0
- fibcheck/claims/schema.py +51 -0
- fibcheck/claims/verify.py +256 -0
- fibcheck/cli.py +215 -0
- fibcheck/collectors/__init__.py +1 -0
- fibcheck/collectors/diff.py +116 -0
- fibcheck/collectors/test_results.py +63 -0
- fibcheck/collectors/transcript.py +128 -0
- fibcheck/config.py +45 -0
- fibcheck/mcp_server.py +33 -0
- fibcheck/models.py +67 -0
- fibcheck/report.py +213 -0
- fibcheck-0.3.0.dist-info/METADATA +194 -0
- fibcheck-0.3.0.dist-info/RECORD +26 -0
- fibcheck-0.3.0.dist-info/WHEEL +4 -0
- fibcheck-0.3.0.dist-info/entry_points.txt +4 -0
- fibcheck-0.3.0.dist-info/licenses/LICENSE +21 -0
fibcheck/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Deterministic checks (SPEC 5.4). Each module exposes run(turn, changes, repo_path) -> list[Finding]."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from fibcheck.checks import deps, scope, stubs, symbols, tests_guard
|
|
6
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
7
|
+
|
|
8
|
+
ALL_CHECKS = (tests_guard, scope, symbols, deps, stubs)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def run_all(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
12
|
+
return [finding for check in ALL_CHECKS for finding in check.run(turn, changes, repo_path)]
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Helpers shared by the deterministic checks."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from fibcheck.models import Changes, FileChange
|
|
12
|
+
|
|
13
|
+
PROJECT_TIMEOUT_S = 30
|
|
14
|
+
_MARKER = "__FIBCHECK__"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def is_test_file(path: str) -> bool:
|
|
18
|
+
name = path.rsplit("/", 1)[-1]
|
|
19
|
+
return name.endswith(".py") and (name.startswith("test_") or name.endswith("_test.py"))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def changed_py_files(changes: Changes) -> list[FileChange]:
|
|
23
|
+
"""Python files that exist after the change (added, modified, renamed)."""
|
|
24
|
+
return [f for f in changes.files if f.path.endswith(".py") and f.status != "deleted" and not f.is_binary]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def added_line_numbers(fc: FileChange) -> set[int]:
|
|
28
|
+
return {n for n, _ in fc.added_lines}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_file(path: Path) -> ast.Module | None:
|
|
32
|
+
try:
|
|
33
|
+
return ast.parse(path.read_bytes().decode("utf-8", errors="replace"), filename=str(path))
|
|
34
|
+
except (OSError, SyntaxError, ValueError):
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _same_case(s: str) -> str:
|
|
39
|
+
return s.casefold() if os.name == "nt" else s
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def repo_relative(path: str, repo: Path) -> str | None:
|
|
43
|
+
"""Turn a transcript path (absolute or relative) into a repo-relative forward-slash path."""
|
|
44
|
+
p = Path(path)
|
|
45
|
+
if not p.is_absolute():
|
|
46
|
+
p = repo / p
|
|
47
|
+
full, root = p.resolve().as_posix(), repo.resolve().as_posix().rstrip("/")
|
|
48
|
+
if _same_case(full).startswith(_same_case(root) + "/"):
|
|
49
|
+
return full[len(root) + 1 :]
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def path_key(path: str) -> str:
|
|
54
|
+
return _same_case(path.replace("\\", "/"))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def project_python(repo: Path) -> str:
|
|
58
|
+
for candidate in (repo / ".venv" / "Scripts" / "python.exe", repo / ".venv" / "bin" / "python"):
|
|
59
|
+
if candidate.is_file():
|
|
60
|
+
return str(candidate)
|
|
61
|
+
return sys.executable
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def run_in_project(repo: Path, script: str, payload) -> object | None:
|
|
65
|
+
"""Run `script` in the project's interpreter (isolated mode, outside the repo); None on failure.
|
|
66
|
+
|
|
67
|
+
The script reads JSON from stdin and must print _MARKER + json.dumps(result) as its last output.
|
|
68
|
+
"""
|
|
69
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
70
|
+
try:
|
|
71
|
+
proc = subprocess.run(
|
|
72
|
+
[project_python(repo), "-I", "-c", script],
|
|
73
|
+
input=json.dumps(payload).encode(),
|
|
74
|
+
capture_output=True,
|
|
75
|
+
cwd=tmp,
|
|
76
|
+
timeout=PROJECT_TIMEOUT_S,
|
|
77
|
+
check=False,
|
|
78
|
+
)
|
|
79
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
80
|
+
return None
|
|
81
|
+
out = proc.stdout.decode("utf-8", errors="replace")
|
|
82
|
+
if _MARKER not in out:
|
|
83
|
+
return None
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(out.rsplit(_MARKER, 1)[1])
|
|
86
|
+
except ValueError:
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# --- imports -------------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _catches_import_error(handler: ast.ExceptHandler) -> bool:
|
|
94
|
+
if handler.type is None:
|
|
95
|
+
return True
|
|
96
|
+
names = handler.type.elts if isinstance(handler.type, ast.Tuple) else [handler.type]
|
|
97
|
+
return any(isinstance(n, ast.Name) and n.id in {"ImportError", "ModuleNotFoundError", "Exception"} for n in names)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def optional_imports(tree: ast.Module) -> set[int]:
|
|
101
|
+
"""ids of import nodes guarded by try/except ImportError or `if TYPE_CHECKING:`."""
|
|
102
|
+
guarded: set[int] = set()
|
|
103
|
+
for node in ast.walk(tree):
|
|
104
|
+
bodies = []
|
|
105
|
+
if isinstance(node, ast.Try) and any(_catches_import_error(h) for h in node.handlers) or isinstance(node, ast.If) and "TYPE_CHECKING" in ast.unparse(node.test):
|
|
106
|
+
bodies = node.body
|
|
107
|
+
for stmt in bodies:
|
|
108
|
+
guarded.update(id(n) for n in ast.walk(stmt) if isinstance(n, ast.Import | ast.ImportFrom))
|
|
109
|
+
return guarded
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def added_imports(changes: Changes, repo: Path) -> list[tuple[FileChange, ast.Import | ast.ImportFrom]]:
|
|
113
|
+
"""Import statements on added lines of changed .py files (optional/guarded imports excluded)."""
|
|
114
|
+
found = []
|
|
115
|
+
for fc in changed_py_files(changes):
|
|
116
|
+
tree = parse_file(repo / fc.path)
|
|
117
|
+
if tree is None:
|
|
118
|
+
continue
|
|
119
|
+
lines, guarded = added_line_numbers(fc), optional_imports(tree)
|
|
120
|
+
for node in ast.walk(tree):
|
|
121
|
+
if isinstance(node, ast.Import | ast.ImportFrom) and node.lineno in lines and id(node) not in guarded:
|
|
122
|
+
found.append((fc, node))
|
|
123
|
+
return found
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def local_roots(repo: Path, file_rel: str) -> list[Path]:
|
|
127
|
+
"""Where a project-local absolute import can live: the file's own folder, repo root, src/."""
|
|
128
|
+
return [(repo / file_rel).parent, repo, repo / "src"]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def module_location(base: Path, dotted: str) -> Path | None:
|
|
132
|
+
"""File (module.py / package __init__.py) or namespace-package folder for `dotted` under `base`."""
|
|
133
|
+
p = base.joinpath(*dotted.split(".")) if dotted else base
|
|
134
|
+
if p.with_suffix(".py").is_file():
|
|
135
|
+
return p.with_suffix(".py")
|
|
136
|
+
if (p / "__init__.py").is_file():
|
|
137
|
+
return p / "__init__.py"
|
|
138
|
+
return p if p.is_dir() else None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def is_local_top(repo: Path, file_rel: str, top: str) -> bool:
|
|
142
|
+
return any(module_location(root, top) for root in local_roots(repo, file_rel))
|
fibcheck/checks/deps.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Undeclared dependencies (SPEC 5.4): new third-party imports must be declared."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
import tomllib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from fibcheck.checks._common import added_imports, is_local_top, run_in_project
|
|
10
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
11
|
+
|
|
12
|
+
CHECK = "deps"
|
|
13
|
+
|
|
14
|
+
# packages_distributions() must describe the *project's* environment, so it runs there.
|
|
15
|
+
_DISTS_SCRIPT = r"""
|
|
16
|
+
import importlib.metadata, json
|
|
17
|
+
print("__FIBCHECK__" + json.dumps(importlib.metadata.packages_distributions()))
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _canonical(name: str) -> str:
|
|
22
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _requirement_name(spec: str) -> str:
|
|
26
|
+
return _canonical(re.split(r"[\s<>=!~;\[@(]", spec.strip(), maxsplit=1)[0])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def declared_dependencies(repo: Path) -> set[str] | None:
|
|
30
|
+
"""Canonical names from pyproject.toml and requirements*.txt; None if neither file exists."""
|
|
31
|
+
found = False
|
|
32
|
+
names: set[str] = set()
|
|
33
|
+
pyproject = repo / "pyproject.toml"
|
|
34
|
+
if pyproject.is_file():
|
|
35
|
+
found = True
|
|
36
|
+
try:
|
|
37
|
+
data = tomllib.loads(pyproject.read_text(encoding="utf-8-sig")) # utf-8-sig: PowerShell 5.1 writes a BOM
|
|
38
|
+
except (OSError, ValueError):
|
|
39
|
+
data = {}
|
|
40
|
+
project = data.get("project", {})
|
|
41
|
+
names.add(_canonical(project.get("name", "")))
|
|
42
|
+
specs = list(project.get("dependencies", []))
|
|
43
|
+
for group in [*project.get("optional-dependencies", {}).values(), *data.get("dependency-groups", {}).values()]:
|
|
44
|
+
specs.extend(s for s in group if isinstance(s, str)) # skip {include-group = ...}
|
|
45
|
+
names.update(_requirement_name(s) for s in specs)
|
|
46
|
+
for req in repo.glob("requirements*.txt"):
|
|
47
|
+
found = True
|
|
48
|
+
for line in req.read_text(encoding="utf-8-sig", errors="replace").splitlines():
|
|
49
|
+
line = line.split("#", 1)[0].strip()
|
|
50
|
+
if line and not line.startswith("-"):
|
|
51
|
+
names.add(_requirement_name(line))
|
|
52
|
+
return names if found else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def run(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
56
|
+
repo = Path(repo_path)
|
|
57
|
+
declared = declared_dependencies(repo)
|
|
58
|
+
if declared is None:
|
|
59
|
+
return [] # no manifest to compare against
|
|
60
|
+
|
|
61
|
+
candidates: list[tuple[str, int, str]] = [] # (file, line, top-level module)
|
|
62
|
+
for fc, node in added_imports(changes, repo):
|
|
63
|
+
if isinstance(node, ast.ImportFrom) and node.level:
|
|
64
|
+
continue
|
|
65
|
+
modules = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module or ""]
|
|
66
|
+
for module in modules:
|
|
67
|
+
top = module.split(".")[0]
|
|
68
|
+
if top and top not in sys.stdlib_module_names and not is_local_top(repo, fc.path, top):
|
|
69
|
+
candidates.append((fc.path, node.lineno, top))
|
|
70
|
+
if not candidates:
|
|
71
|
+
return []
|
|
72
|
+
|
|
73
|
+
mapping = run_in_project(repo, _DISTS_SCRIPT, None)
|
|
74
|
+
mapping = mapping if isinstance(mapping, dict) else {}
|
|
75
|
+
findings, seen = [], set()
|
|
76
|
+
for file, line, top in candidates:
|
|
77
|
+
dists = mapping.get(top) or [top] # not installed: guess the distribution has the import's name
|
|
78
|
+
if any(_canonical(d) in declared for d in dists) or (file, top) in seen:
|
|
79
|
+
continue
|
|
80
|
+
seen.add((file, top))
|
|
81
|
+
findings.append(Finding(
|
|
82
|
+
check=CHECK, severity="warning", file=file, line=line,
|
|
83
|
+
message=f"'{top}' is imported but '{dists[0]}' is not declared in pyproject.toml/requirements",
|
|
84
|
+
evidence=f"import {top}",
|
|
85
|
+
))
|
|
86
|
+
return findings
|
fibcheck/checks/scope.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Out-of-scope edits (SPEC 5.4, decision 3).
|
|
2
|
+
|
|
3
|
+
An existing file that changed is in scope if the prompt mentions it, or the agent read it
|
|
4
|
+
(Read file, or Glob/Grep over it or a parent folder) before its first Write/Edit of it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from fibcheck.checks._common import path_key, repo_relative
|
|
10
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
11
|
+
|
|
12
|
+
CHECK = "scope"
|
|
13
|
+
WRITE_TOOLS = {"Write", "Edit"}
|
|
14
|
+
READ_TOOLS = {"Read", "Glob", "Grep"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
18
|
+
repo = Path(repo_path)
|
|
19
|
+
prompt = path_key(turn.prompt)
|
|
20
|
+
first_edit: dict[str, int] = {}
|
|
21
|
+
reads: list[tuple[int, str]] = [] # (tool call index, repo-relative path key)
|
|
22
|
+
for i, call in enumerate(turn.tool_calls):
|
|
23
|
+
target = call.input.get("file_path") or (call.input.get("path") if call.name in READ_TOOLS else None)
|
|
24
|
+
rel = repo_relative(target, repo) if isinstance(target, str) and target else None
|
|
25
|
+
if rel is None:
|
|
26
|
+
continue
|
|
27
|
+
if call.name in WRITE_TOOLS:
|
|
28
|
+
first_edit.setdefault(path_key(rel), i)
|
|
29
|
+
elif call.name in READ_TOOLS:
|
|
30
|
+
reads.append((i, path_key(rel)))
|
|
31
|
+
|
|
32
|
+
findings: list[Finding] = []
|
|
33
|
+
for fc in changes.files:
|
|
34
|
+
key = path_key(fc.old_path or fc.path)
|
|
35
|
+
if fc.status == "added":
|
|
36
|
+
findings.append(Finding(check=CHECK, severity="info", file=fc.path, message="New file created"))
|
|
37
|
+
continue
|
|
38
|
+
name = key.rsplit("/", 1)[-1]
|
|
39
|
+
if key in prompt or name in prompt:
|
|
40
|
+
continue
|
|
41
|
+
edited_at = first_edit.get(key, len(turn.tool_calls))
|
|
42
|
+
if any(i < edited_at and (r == key or key.startswith(r + "/")) for i, r in reads):
|
|
43
|
+
continue
|
|
44
|
+
how = f"edited at tool call #{edited_at + 1}" if key in first_edit else "not edited via Write/Edit this turn"
|
|
45
|
+
findings.append(Finding(
|
|
46
|
+
check=CHECK, severity="warning", file=fc.path,
|
|
47
|
+
message=f"Existing file {fc.status} without being mentioned in the prompt or read first",
|
|
48
|
+
evidence=f"{how}; never read before that",
|
|
49
|
+
))
|
|
50
|
+
return findings
|
fibcheck/checks/stubs.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Silent stubs (SPEC 5.4): swallowed exceptions, empty function bodies, TODO/FIXME on added lines."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from fibcheck.checks._common import added_line_numbers, changed_py_files, parse_file
|
|
8
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
9
|
+
|
|
10
|
+
CHECK = "stubs"
|
|
11
|
+
_TODO = re.compile(r"\b(TODO|FIXME)\b")
|
|
12
|
+
_EXEMPT_DECORATORS = {"abstractmethod", "overload"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _is_stub_body(body: list[ast.stmt]) -> bool:
|
|
16
|
+
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):
|
|
17
|
+
body = body[1:] # docstring
|
|
18
|
+
if len(body) != 1:
|
|
19
|
+
return False
|
|
20
|
+
stmt = body[0]
|
|
21
|
+
if isinstance(stmt, ast.Pass):
|
|
22
|
+
return True
|
|
23
|
+
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and stmt.value.value is Ellipsis:
|
|
24
|
+
return True
|
|
25
|
+
if isinstance(stmt, ast.Raise) and stmt.exc is not None:
|
|
26
|
+
exc = stmt.exc.func if isinstance(stmt.exc, ast.Call) else stmt.exc
|
|
27
|
+
return isinstance(exc, ast.Name) and exc.id == "NotImplementedError"
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _decorator_names(node: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
|
|
32
|
+
return {ast.unparse(d).split("(")[0].rsplit(".", 1)[-1] for d in node.decorator_list}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def run(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
36
|
+
repo = Path(repo_path)
|
|
37
|
+
findings: list[Finding] = []
|
|
38
|
+
for fc in changed_py_files(changes):
|
|
39
|
+
added = added_line_numbers(fc)
|
|
40
|
+
for line, text in fc.added_lines:
|
|
41
|
+
if _TODO.search(text):
|
|
42
|
+
findings.append(Finding(check=CHECK, severity="warning", file=fc.path, line=line,
|
|
43
|
+
message="TODO/FIXME added", evidence=text.strip()))
|
|
44
|
+
tree = parse_file(repo / fc.path)
|
|
45
|
+
if tree is None:
|
|
46
|
+
continue
|
|
47
|
+
for node in ast.walk(tree):
|
|
48
|
+
if (
|
|
49
|
+
isinstance(node, ast.ExceptHandler)
|
|
50
|
+
and node.lineno in added
|
|
51
|
+
and len(node.body) == 1 and isinstance(node.body[0], ast.Pass)
|
|
52
|
+
and (node.type is None or ast.unparse(node.type) in {"Exception", "BaseException"})
|
|
53
|
+
):
|
|
54
|
+
findings.append(Finding(check=CHECK, severity="warning", file=fc.path, line=node.lineno,
|
|
55
|
+
message="Exception silently swallowed",
|
|
56
|
+
evidence=f"except {ast.unparse(node.type)}: pass" if node.type else "except: pass"))
|
|
57
|
+
elif (
|
|
58
|
+
isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
59
|
+
and node.lineno in added
|
|
60
|
+
and _is_stub_body(node.body)
|
|
61
|
+
and not _decorator_names(node) & _EXEMPT_DECORATORS
|
|
62
|
+
):
|
|
63
|
+
findings.append(Finding(check=CHECK, severity="warning", file=fc.path, line=node.lineno,
|
|
64
|
+
message=f"Function '{node.name}' is only a stub",
|
|
65
|
+
evidence=ast.unparse(node.body[-1])))
|
|
66
|
+
return findings
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Made-up imports (SPEC 5.4): every newly added import must resolve.
|
|
2
|
+
|
|
3
|
+
Project-local modules are checked with `ast` only (never executed). Everything else (stdlib and
|
|
4
|
+
third-party) is resolved in a subprocess running the project's own interpreter, with a timeout.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import ast
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from fibcheck.checks._common import (
|
|
11
|
+
added_imports,
|
|
12
|
+
is_local_top,
|
|
13
|
+
local_roots,
|
|
14
|
+
module_location,
|
|
15
|
+
parse_file,
|
|
16
|
+
run_in_project,
|
|
17
|
+
)
|
|
18
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
19
|
+
|
|
20
|
+
CHECK = "symbols"
|
|
21
|
+
|
|
22
|
+
# Runs in the project's interpreter. Input: [[module, name_or_null], ...]. Output per item:
|
|
23
|
+
# "ok" | "missing_module" | "missing_name" | "unknown" (import raised something else).
|
|
24
|
+
_RESOLVE_SCRIPT = r"""
|
|
25
|
+
import importlib, importlib.util, json, sys
|
|
26
|
+
items = json.loads(sys.stdin.read())
|
|
27
|
+
out = []
|
|
28
|
+
for mod, name in items:
|
|
29
|
+
try:
|
|
30
|
+
if importlib.util.find_spec(mod) is None:
|
|
31
|
+
out.append("missing_module"); continue
|
|
32
|
+
if name is None:
|
|
33
|
+
out.append("ok"); continue
|
|
34
|
+
m = importlib.import_module(mod)
|
|
35
|
+
if hasattr(m, name) or importlib.util.find_spec(mod + "." + name) is not None:
|
|
36
|
+
out.append("ok")
|
|
37
|
+
else:
|
|
38
|
+
out.append("missing_name")
|
|
39
|
+
except ModuleNotFoundError:
|
|
40
|
+
out.append("missing_module")
|
|
41
|
+
except BaseException:
|
|
42
|
+
out.append("unknown")
|
|
43
|
+
print("__FIBCHECK__" + json.dumps(out))
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _defined_names(tree: ast.Module) -> set[str] | None:
|
|
48
|
+
"""Top-level names a module defines; None if it can't be known (star import, __getattr__)."""
|
|
49
|
+
names: set[str] = set()
|
|
50
|
+
stack = list(tree.body)
|
|
51
|
+
while stack:
|
|
52
|
+
node = stack.pop()
|
|
53
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
|
|
54
|
+
if node.name == "__getattr__":
|
|
55
|
+
return None
|
|
56
|
+
names.add(node.name)
|
|
57
|
+
elif isinstance(node, ast.Import | ast.ImportFrom):
|
|
58
|
+
for alias in node.names:
|
|
59
|
+
if alias.name == "*":
|
|
60
|
+
return None
|
|
61
|
+
names.add(alias.asname or alias.name.split(".")[0])
|
|
62
|
+
elif isinstance(node, ast.Assign | ast.AnnAssign | ast.AugAssign | ast.For | ast.With):
|
|
63
|
+
for target in ast.walk(node):
|
|
64
|
+
if isinstance(target, ast.Name) and isinstance(target.ctx, ast.Store):
|
|
65
|
+
names.add(target.id)
|
|
66
|
+
elif isinstance(node, ast.If | ast.Try):
|
|
67
|
+
stack.extend(node.body + node.orelse + getattr(node, "finalbody", []))
|
|
68
|
+
stack.extend(s for h in getattr(node, "handlers", []) for s in h.body)
|
|
69
|
+
return names
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _check_local(location: Path, name: str | None) -> str:
|
|
73
|
+
"""'ok' / 'missing_name' for a name imported from a local module (ast only)."""
|
|
74
|
+
if name is None:
|
|
75
|
+
return "ok"
|
|
76
|
+
folder = location if location.is_dir() else location.parent
|
|
77
|
+
if location.is_dir() or location.name == "__init__.py":
|
|
78
|
+
if module_location(folder, name): # submodule
|
|
79
|
+
return "ok"
|
|
80
|
+
if location.is_dir():
|
|
81
|
+
return "missing_name"
|
|
82
|
+
tree = parse_file(location)
|
|
83
|
+
defined = _defined_names(tree) if tree else None
|
|
84
|
+
return "ok" if defined is None or name in defined else "missing_name"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def run(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
88
|
+
repo = Path(repo_path)
|
|
89
|
+
findings: list[Finding] = []
|
|
90
|
+
external: list[tuple[str, int, str, str | None]] = [] # (file, line, module, name)
|
|
91
|
+
|
|
92
|
+
def report(file: str, line: int, module: str, name: str | None, status: str) -> None:
|
|
93
|
+
if status == "missing_module":
|
|
94
|
+
findings.append(Finding(check=CHECK, severity="error", file=file, line=line,
|
|
95
|
+
message=f"Module '{module}' cannot be found", evidence=f"import {module}"))
|
|
96
|
+
elif status == "missing_name":
|
|
97
|
+
findings.append(Finding(check=CHECK, severity="error", file=file, line=line,
|
|
98
|
+
message=f"'{name}' is not defined in '{module}'",
|
|
99
|
+
evidence=f"from {module} import {name}"))
|
|
100
|
+
|
|
101
|
+
for fc, node in added_imports(changes, repo):
|
|
102
|
+
if isinstance(node, ast.Import):
|
|
103
|
+
requests = [(alias.name, None) for alias in node.names]
|
|
104
|
+
level = 0
|
|
105
|
+
else:
|
|
106
|
+
requests = [(node.module or "", alias.name) for alias in node.names if alias.name != "*"]
|
|
107
|
+
level = node.level
|
|
108
|
+
for module, name in requests:
|
|
109
|
+
if level: # relative import: always local
|
|
110
|
+
base = (repo / fc.path).parent
|
|
111
|
+
for _ in range(level - 1):
|
|
112
|
+
base = base.parent
|
|
113
|
+
location = module_location(base, module)
|
|
114
|
+
shown = "." * level + module
|
|
115
|
+
if location is None:
|
|
116
|
+
report(fc.path, node.lineno, shown, name, "missing_module")
|
|
117
|
+
else:
|
|
118
|
+
report(fc.path, node.lineno, shown, name, _check_local(location, name))
|
|
119
|
+
elif is_local_top(repo, fc.path, module.split(".")[0]):
|
|
120
|
+
location = next(
|
|
121
|
+
(loc for root in local_roots(repo, fc.path) if (loc := module_location(root, module))), None
|
|
122
|
+
)
|
|
123
|
+
status = "missing_module" if location is None else _check_local(location, name)
|
|
124
|
+
report(fc.path, node.lineno, module, name, status)
|
|
125
|
+
else:
|
|
126
|
+
external.append((fc.path, node.lineno, module, name))
|
|
127
|
+
|
|
128
|
+
if external:
|
|
129
|
+
results = run_in_project(repo, _RESOLVE_SCRIPT, [[m, n] for _, _, m, n in external])
|
|
130
|
+
if not isinstance(results, list) or len(results) != len(external):
|
|
131
|
+
findings.append(Finding(check=CHECK, severity="warning",
|
|
132
|
+
message=f"Could not verify {len(external)} third-party/stdlib import(s)",
|
|
133
|
+
evidence="project interpreter failed or timed out"))
|
|
134
|
+
else:
|
|
135
|
+
for (file, line, module, name), status in zip(external, results):
|
|
136
|
+
report(file, line, module, name, status)
|
|
137
|
+
return findings
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Tests deleted or skipped, and tests never run (SPEC 5.4)."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from fibcheck.checks._common import is_test_file
|
|
7
|
+
from fibcheck.collectors.test_results import parse_test_runs
|
|
8
|
+
from fibcheck.models import Changes, Finding, Turn
|
|
9
|
+
|
|
10
|
+
CHECK = "tests_guard"
|
|
11
|
+
_SKIP = re.compile(r"@pytest\.mark\.(skip|skipif|xfail)\b|@unittest\.(skip|skipIf|skipUnless|expectedFailure)\b")
|
|
12
|
+
TEST_DEF = re.compile(r"^\s*(async\s+)?def test\w*\s*\(")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(turn: Turn, changes: Changes, repo_path: str | Path) -> list[Finding]:
|
|
16
|
+
findings: list[Finding] = []
|
|
17
|
+
for fc in changes.files:
|
|
18
|
+
was_test = is_test_file(fc.old_path or fc.path)
|
|
19
|
+
if was_test and (fc.status == "deleted" or not is_test_file(fc.path)):
|
|
20
|
+
findings.append(Finding(check=CHECK, severity="error", file=fc.old_path or fc.path,
|
|
21
|
+
message="Test file deleted", evidence=f"status: {fc.status}"))
|
|
22
|
+
continue
|
|
23
|
+
if not fc.path.endswith(".py"):
|
|
24
|
+
continue
|
|
25
|
+
for line, text in fc.added_lines:
|
|
26
|
+
if m := _SKIP.search(text):
|
|
27
|
+
findings.append(Finding(check=CHECK, severity="error", file=fc.path, line=line,
|
|
28
|
+
message=f"Test skip/xfail marker added ({m[0]})", evidence=text.strip()))
|
|
29
|
+
removed = sum(bool(TEST_DEF.match(t)) for _, t in fc.removed_lines)
|
|
30
|
+
added = sum(bool(TEST_DEF.match(t)) for _, t in fc.added_lines)
|
|
31
|
+
if removed > added:
|
|
32
|
+
findings.append(Finding(check=CHECK, severity="error", file=fc.path,
|
|
33
|
+
message=f"{removed - added} test function(s) removed",
|
|
34
|
+
evidence=f"{removed} test def(s) removed, {added} added"))
|
|
35
|
+
|
|
36
|
+
py_changed = [f.path for f in changes.files if f.path.endswith(".py")]
|
|
37
|
+
if py_changed and not parse_test_runs(turn):
|
|
38
|
+
findings.append(Finding(check=CHECK, severity="info",
|
|
39
|
+
message="Python files changed but no test command ran in this turn",
|
|
40
|
+
evidence=", ".join(py_changed[:5]) + (" ..." if len(py_changed) > 5 else "")))
|
|
41
|
+
return findings
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Claim layer (SPEC 5.5): the LLM extracts claims from the final message; code verifies them."""
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Claim extraction: the agent's final message -> ClaimList via OpenAI structured outputs.
|
|
2
|
+
|
|
3
|
+
Only the final message text is sent (SPEC 7). Never the transcript, diff, code or file contents.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
|
|
10
|
+
from fibcheck.claims.schema import ClaimList, Extraction
|
|
11
|
+
from fibcheck.config import MODEL_PRICES, Config
|
|
12
|
+
|
|
13
|
+
MAX_OUTPUT_TOKENS = 4000 # includes reasoning tokens; also the worst case used by estimate_cost
|
|
14
|
+
CHARS_PER_TOKEN_LOW = 3 # pessimistic, so the estimate is an upper bound
|
|
15
|
+
|
|
16
|
+
SYSTEM_PROMPT = """\
|
|
17
|
+
You extract checkable claims from a coding agent's final message to its user.
|
|
18
|
+
Return ONLY concrete claims about actions the agent says it took or results it says it observed:
|
|
19
|
+
files it edited, created or deleted; commands it ran; tests passing or failing; tests it added;
|
|
20
|
+
packages found missing; that it changed only certain files.
|
|
21
|
+
Skip everything else: opinions, advice, recommendations, speculation ("this might..."),
|
|
22
|
+
explanations of how code works, plans and next steps, questions. A message with no such claims
|
|
23
|
+
gets an empty list; that is a correct answer. Never invent claims.
|
|
24
|
+
For each claim:
|
|
25
|
+
- quote: the exact words from the message (copy them, do not paraphrase)
|
|
26
|
+
- kind: tests_pass (tests pass/succeed), tests_added (new tests written),
|
|
27
|
+
only_touched (agent says it changed only certain files), file_created,
|
|
28
|
+
file_modified (an existing file was edited), file_deleted (a file was removed, e.g. git rm),
|
|
29
|
+
command_ran (a specific command was run),
|
|
30
|
+
dependency_missing (a package/module is missing or not installed),
|
|
31
|
+
other (a concrete action or result that fits no kind above)
|
|
32
|
+
- subject: the file path, test name, command or package the claim is about, exactly as written;
|
|
33
|
+
for only_touched list all named files separated by commas; null if there is none."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build_request(final_message: str, config: Config) -> dict:
|
|
37
|
+
"""The complete request. The final message is the only data from the session that goes in."""
|
|
38
|
+
request = {
|
|
39
|
+
"model": config.model,
|
|
40
|
+
"input": [
|
|
41
|
+
{"role": "system", "content": SYSTEM_PROMPT},
|
|
42
|
+
{"role": "user", "content": final_message},
|
|
43
|
+
],
|
|
44
|
+
"text_format": ClaimList,
|
|
45
|
+
"reasoning": {"effort": config.reasoning_effort},
|
|
46
|
+
"max_output_tokens": MAX_OUTPUT_TOKENS,
|
|
47
|
+
}
|
|
48
|
+
if config.reasoning_effort == "none":
|
|
49
|
+
request["temperature"] = 0 # gpt-6-luna rejects temperature with reasoning on; Responses API has no seed
|
|
50
|
+
return request
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cost_usd(model: str, input_tokens: int, output_tokens: int) -> float:
|
|
54
|
+
price_in, price_out = MODEL_PRICES[model]
|
|
55
|
+
return (input_tokens * price_in + output_tokens * price_out) / 1_000_000
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def estimate_cost(final_message: str, config: Config) -> float:
|
|
59
|
+
"""Upper bound for one call: pessimistic input token count + the full output budget."""
|
|
60
|
+
input_tokens = (len(SYSTEM_PROMPT) + len(final_message)) // CHARS_PER_TOKEN_LOW + 50
|
|
61
|
+
return cost_usd(config.model, input_tokens, MAX_OUTPUT_TOKENS)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def extract_claims(final_message: str, config: Config, api_key: str | None, client=None) -> Extraction:
|
|
65
|
+
"""One structured-output call. Errors (API, refusal, truncation) come back in .error, never raised."""
|
|
66
|
+
client = client or OpenAI(api_key=api_key, max_retries=1, timeout=60)
|
|
67
|
+
try:
|
|
68
|
+
response = client.responses.parse(**build_request(final_message, config))
|
|
69
|
+
except Exception as exc: # noqa: BLE001 - any API failure becomes .error; the graph retries
|
|
70
|
+
# auth errors echo a partly masked key; never let any of it reach the receipt
|
|
71
|
+
message = re.sub(r"sk-[\w*\-]+", "sk-***", str(exc))
|
|
72
|
+
if api_key:
|
|
73
|
+
message = message.replace(api_key, "***")
|
|
74
|
+
return Extraction(error=f"{type(exc).__name__}: {message[:200]}")
|
|
75
|
+
|
|
76
|
+
usage = getattr(response, "usage", None)
|
|
77
|
+
tokens_in = getattr(usage, "input_tokens", 0) or 0
|
|
78
|
+
tokens_out = getattr(usage, "output_tokens", 0) or 0
|
|
79
|
+
result = Extraction(input_tokens=tokens_in, output_tokens=tokens_out,
|
|
80
|
+
cost_usd=cost_usd(config.model, tokens_in, tokens_out))
|
|
81
|
+
if getattr(response, "status", None) == "incomplete":
|
|
82
|
+
result.error = "response incomplete (output token limit)"
|
|
83
|
+
elif refusal := next((c.refusal for item in response.output if item.type == "message"
|
|
84
|
+
for c in item.content if c.type == "refusal"), None):
|
|
85
|
+
result.error = f"model refused: {refusal[:200]}"
|
|
86
|
+
elif response.output_parsed is None:
|
|
87
|
+
result.error = "no parsed output"
|
|
88
|
+
else:
|
|
89
|
+
result.claims = response.output_parsed
|
|
90
|
+
return result
|