margin-ai-code-detector 0.2.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.
- ai_code_detector/__init__.py +15 -0
- ai_code_detector/agent.py +56 -0
- ai_code_detector/aggregate.py +183 -0
- ai_code_detector/judge/__init__.py +1 -0
- ai_code_detector/judge/llm_judge.py +358 -0
- ai_code_detector/judge/prompts/__init__.py +1 -0
- ai_code_detector/judge/prompts/judge_v1.md +28 -0
- ai_code_detector/judge/prompts/judge_v2.md +28 -0
- ai_code_detector/judge/sampler.py +40 -0
- ai_code_detector/markers/__init__.py +108 -0
- ai_code_detector/markers/v1.toml +98 -0
- ai_code_detector/methodology/__init__.py +71 -0
- ai_code_detector/methodology/v0.toml +119 -0
- ai_code_detector/methodology/v1.toml +141 -0
- ai_code_detector/models.py +197 -0
- ai_code_detector/pipeline.py +457 -0
- ai_code_detector/py.typed +1 -0
- ai_code_detector/report.py +179 -0
- ai_code_detector/signals/__init__.py +7 -0
- ai_code_detector/signals/base.py +64 -0
- ai_code_detector/signals/file.py +277 -0
- ai_code_detector/signals/repo.py +183 -0
- ai_code_detector/source/__init__.py +95 -0
- ai_code_detector/source/javascript.py +227 -0
- ai_code_detector/source/python.py +129 -0
- margin_ai_code_detector-0.2.0.dist-info/METADATA +137 -0
- margin_ai_code_detector-0.2.0.dist-info/RECORD +30 -0
- margin_ai_code_detector-0.2.0.dist-info/WHEEL +4 -0
- margin_ai_code_detector-0.2.0.dist-info/entry_points.txt +2 -0
- margin_ai_code_detector-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Input and output models of the AI Code Detector."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from margin_core import AgentInput, Evidence
|
|
9
|
+
from pydantic import BaseModel, Field, field_validator
|
|
10
|
+
|
|
11
|
+
Confidence = Literal["low", "medium", "high"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DetectorInput(AgentInput):
|
|
15
|
+
target: str = Field(
|
|
16
|
+
description="GitHub URL (https://github.com/<owner>/<repo>) or local path.",
|
|
17
|
+
examples=["https://github.com/psf/requests"],
|
|
18
|
+
)
|
|
19
|
+
paths: list[str] | None = Field(
|
|
20
|
+
default=None, description="Restrict the analysis to these files or folders."
|
|
21
|
+
)
|
|
22
|
+
branch: str | None = Field(default=None, description="Branch to analyse (GitHub only).")
|
|
23
|
+
use_llm_judge: bool | None = Field(
|
|
24
|
+
default=None,
|
|
25
|
+
description=(
|
|
26
|
+
"Ask a model to judge a sample of files. Default: when a model is configured. "
|
|
27
|
+
"Without it the estimate rests on weak signals and confidence is low."
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
max_files_for_judge: int = Field(default=20, ge=1, le=200)
|
|
31
|
+
max_judge_seconds: float = Field(default=300.0, gt=0)
|
|
32
|
+
max_cost_usd: float | None = Field(
|
|
33
|
+
default=None, ge=0, description="Judge spending limit; only matters for hosted models."
|
|
34
|
+
)
|
|
35
|
+
include_tests: bool = Field(
|
|
36
|
+
default=False, description="Score test files too (reported separately)."
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SignalHit(BaseModel):
|
|
41
|
+
"""One signal that fired, with its strength and the evidence behind it."""
|
|
42
|
+
|
|
43
|
+
signal_id: str
|
|
44
|
+
signal_version: str
|
|
45
|
+
family: str
|
|
46
|
+
strength: float = Field(ge=-1.0, le=1.0, description="Negative means evidence of a human.")
|
|
47
|
+
explanation: str
|
|
48
|
+
evidence: list[Evidence] = Field(default_factory=list)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MetadataMarker(BaseModel):
|
|
52
|
+
"""An explicit trace of an AI tool: proves the tool was used, not how much."""
|
|
53
|
+
|
|
54
|
+
kind: Literal["config_file", "commit_trailer", "bot_author", "generated_with_line"]
|
|
55
|
+
tool: str
|
|
56
|
+
location: str
|
|
57
|
+
detail: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
MAX_QUOTE_CHARS = 160
|
|
61
|
+
MAX_WHY_CHARS = 100
|
|
62
|
+
MAX_EVIDENCE_ITEMS = 3
|
|
63
|
+
MAX_NOTES_CHARS = 160
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _trim(value: object, limit: int) -> object:
|
|
67
|
+
return value[:limit] if isinstance(value, str) else value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class QuotedEvidence(BaseModel):
|
|
71
|
+
"""One quoted line. Limits keep local-model answers short (generation is the slow part);
|
|
72
|
+
they are advertised in the JSON schema for constrained decoding and enforced by trimming,
|
|
73
|
+
so an over-long answer is shortened rather than rejected."""
|
|
74
|
+
|
|
75
|
+
line_start: int
|
|
76
|
+
line_end: int
|
|
77
|
+
quote: str = Field(json_schema_extra={"maxLength": MAX_QUOTE_CHARS})
|
|
78
|
+
why: str = Field(json_schema_extra={"maxLength": MAX_WHY_CHARS})
|
|
79
|
+
|
|
80
|
+
@field_validator("quote", mode="before")
|
|
81
|
+
@classmethod
|
|
82
|
+
def _short_quote(cls, value: object) -> object:
|
|
83
|
+
if isinstance(value, str):
|
|
84
|
+
value = value.split("\n", 1)[0] # one line only
|
|
85
|
+
return _trim(value, MAX_QUOTE_CHARS)
|
|
86
|
+
|
|
87
|
+
@field_validator("why", mode="before")
|
|
88
|
+
@classmethod
|
|
89
|
+
def _short_why(cls, value: object) -> object:
|
|
90
|
+
return _trim(value, MAX_WHY_CHARS)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class JudgeVerdict(BaseModel):
|
|
94
|
+
"""A model's verdict on one file (phase 4)."""
|
|
95
|
+
|
|
96
|
+
likelihood_ai: float = Field(ge=0.0, le=1.0)
|
|
97
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
98
|
+
evidence_for: list[QuotedEvidence] = Field(
|
|
99
|
+
default_factory=list, json_schema_extra={"maxItems": MAX_EVIDENCE_ITEMS}
|
|
100
|
+
)
|
|
101
|
+
evidence_against: list[QuotedEvidence] = Field(
|
|
102
|
+
default_factory=list, json_schema_extra={"maxItems": MAX_EVIDENCE_ITEMS}
|
|
103
|
+
)
|
|
104
|
+
uncertainty_notes: str = Field(default="", json_schema_extra={"maxLength": MAX_NOTES_CHARS})
|
|
105
|
+
|
|
106
|
+
@field_validator("evidence_for", "evidence_against", mode="before")
|
|
107
|
+
@classmethod
|
|
108
|
+
def _few_items(cls, value: object) -> object:
|
|
109
|
+
return value[:MAX_EVIDENCE_ITEMS] if isinstance(value, list) else value
|
|
110
|
+
|
|
111
|
+
@field_validator("uncertainty_notes", mode="before")
|
|
112
|
+
@classmethod
|
|
113
|
+
def _short_notes(cls, value: object) -> object:
|
|
114
|
+
return _trim(value, MAX_NOTES_CHARS)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class FileScore(BaseModel):
|
|
118
|
+
path: str
|
|
119
|
+
language: str | None
|
|
120
|
+
lines: int
|
|
121
|
+
is_test: bool = False
|
|
122
|
+
probability: float = Field(ge=0.0, le=1.0)
|
|
123
|
+
signals: list[SignalHit] = Field(default_factory=list)
|
|
124
|
+
judge: JudgeVerdict | None = None
|
|
125
|
+
ai_commit_touches: int = Field(
|
|
126
|
+
default=0, description="Commits with AI markers that changed this file."
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
Side = Literal["for", "against", "context"]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class ExcerptMark(BaseModel):
|
|
134
|
+
"""A marked span in an excerpt: evidence toward AI ("for"), toward a human ("against"),
|
|
135
|
+
or a signal that is shown but not scored ("context")."""
|
|
136
|
+
|
|
137
|
+
line_start: int
|
|
138
|
+
line_end: int
|
|
139
|
+
side: Side
|
|
140
|
+
source: str = Field(description='"judge", or the id of the signal that found it.')
|
|
141
|
+
note: str
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ExcerptHunk(BaseModel):
|
|
145
|
+
start_line: int
|
|
146
|
+
lines: list[str]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Excerpt(BaseModel):
|
|
150
|
+
"""The parts of a file around its marked evidence, so a report can show the code."""
|
|
151
|
+
|
|
152
|
+
path: str
|
|
153
|
+
hunks: list[ExcerptHunk]
|
|
154
|
+
marks: list[ExcerptMark]
|
|
155
|
+
truncated: bool = Field(default=False, description="Some marked spans were left out.")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class CommitSummary(BaseModel):
|
|
159
|
+
"""One commit, as the timeline needs it. Authors are left out on purpose: the report is
|
|
160
|
+
about code, not about people."""
|
|
161
|
+
|
|
162
|
+
sha: str
|
|
163
|
+
date: datetime
|
|
164
|
+
subject: str
|
|
165
|
+
files_changed: int
|
|
166
|
+
merge: bool = False
|
|
167
|
+
tools: list[str] = Field(default_factory=list, description="AI tools its metadata names.")
|
|
168
|
+
large: bool = Field(default=False, description="Touched unusually many files.")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class UnscoredFile(BaseModel):
|
|
172
|
+
path: str
|
|
173
|
+
reason: str = Field(
|
|
174
|
+
description="Why it has no score: unsupported_language, test_file, too_small, "
|
|
175
|
+
"unparseable, unreadable, or a loader reason such as lockfile, binary or generated."
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class DetectorOutput(BaseModel):
|
|
180
|
+
methodology_version: str
|
|
181
|
+
estimate: float = Field(ge=0.0, le=1.0)
|
|
182
|
+
estimate_range: tuple[float, float]
|
|
183
|
+
confidence: Confidence
|
|
184
|
+
confidence_reasons: list[str] = Field(default_factory=list)
|
|
185
|
+
metadata_markers: list[MetadataMarker] = Field(default_factory=list)
|
|
186
|
+
repo_signals: list[SignalHit] = Field(default_factory=list)
|
|
187
|
+
files: list[FileScore] = Field(default_factory=list)
|
|
188
|
+
files_analyzed: int
|
|
189
|
+
files_skipped: int
|
|
190
|
+
languages: dict[str, int] = Field(default_factory=dict)
|
|
191
|
+
unsupported_languages: dict[str, int] = Field(default_factory=dict)
|
|
192
|
+
# for reports and the UI: the code behind the evidence, the history, the unscored files
|
|
193
|
+
excerpts: list[Excerpt] = Field(default_factory=list)
|
|
194
|
+
commits: list[CommitSummary] = Field(default_factory=list, description="Newest first.")
|
|
195
|
+
commits_total: int = 0
|
|
196
|
+
unscored_files: list[UnscoredFile] = Field(default_factory=list)
|
|
197
|
+
unscored_truncated: bool = False
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""The detector pipeline: ingest -> markers -> repo signals -> file signals -> aggregate -> report.
|
|
2
|
+
|
|
3
|
+
Steps match PLAN §9.3. The LLM judge (steps 5-6) arrives in phase 4.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import PurePosixPath
|
|
12
|
+
|
|
13
|
+
from margin_core import Evidence, Finding, RunContext
|
|
14
|
+
from margin_core.loaders import FileInfo, Workspace
|
|
15
|
+
|
|
16
|
+
from ai_code_detector.aggregate import (
|
|
17
|
+
ConfidenceFacts,
|
|
18
|
+
confidence_level,
|
|
19
|
+
estimate_range,
|
|
20
|
+
file_probability,
|
|
21
|
+
judge_shift,
|
|
22
|
+
repo_estimate,
|
|
23
|
+
repo_shift,
|
|
24
|
+
widen_range,
|
|
25
|
+
)
|
|
26
|
+
from ai_code_detector.judge.llm_judge import Judge, JudgeRun, JudgeSettings
|
|
27
|
+
from ai_code_detector.judge.sampler import sample_files
|
|
28
|
+
from ai_code_detector.markers import MarkerSet, detect_commit_markers, detect_config_files
|
|
29
|
+
from ai_code_detector.methodology import Methodology
|
|
30
|
+
from ai_code_detector.models import DetectorInput, DetectorOutput, FileScore, SignalHit
|
|
31
|
+
from ai_code_detector.report import build_excerpts, commit_summaries, unscored
|
|
32
|
+
from ai_code_detector.signals import FILE_SIGNALS, REPO_SIGNALS, RepoContext
|
|
33
|
+
from ai_code_detector.source import is_supported, parse_source
|
|
34
|
+
|
|
35
|
+
MAX_COMMITS = 5000
|
|
36
|
+
FILE_BATCH = 50
|
|
37
|
+
SUPPORTED_LANGUAGES = {"python", "javascript", "typescript"}
|
|
38
|
+
CODE_LANGUAGES = {
|
|
39
|
+
"python", "javascript", "typescript", "java", "kotlin", "scala", "go", "rust", "ruby", "php",
|
|
40
|
+
"swift", "c", "cpp", "csharp", "fsharp", "dart", "lua", "r", "objective-c", "elixir",
|
|
41
|
+
"erlang", "haskell", "clojure", "julia", "zig", "shell", "powershell", "sql", "vue", "svelte",
|
|
42
|
+
} # fmt: skip
|
|
43
|
+
CAVEAT = (
|
|
44
|
+
"This is an estimate, not proof: clean human code can look machine-made and edited AI code "
|
|
45
|
+
"can look human. Do not use it as the sole basis for accusing anyone."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Detection:
|
|
51
|
+
output: DetectorOutput
|
|
52
|
+
summary: str
|
|
53
|
+
findings: list[Finding]
|
|
54
|
+
warnings: list[str] = field(default_factory=list)
|
|
55
|
+
partial: bool = False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_test_path(path: str) -> bool:
|
|
59
|
+
p = PurePosixPath(path)
|
|
60
|
+
name = p.name
|
|
61
|
+
return (
|
|
62
|
+
any(
|
|
63
|
+
part in {"test", "tests", "testing", "__tests__", "spec", "e2e"}
|
|
64
|
+
for part in p.parts[:-1]
|
|
65
|
+
)
|
|
66
|
+
or name.startswith("test_")
|
|
67
|
+
or name.endswith("_test.py")
|
|
68
|
+
or name == "conftest.py"
|
|
69
|
+
or any(f".{kind}." in name for kind in ("test", "spec")) # foo.test.ts, bar.spec.js
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _analyse_file(ws: Workspace, info: FileInfo, methodology: Methodology) -> FileScore | str:
|
|
74
|
+
"""A scored file, or the reason it was skipped."""
|
|
75
|
+
try:
|
|
76
|
+
text = ws.read_text(info)
|
|
77
|
+
except OSError:
|
|
78
|
+
return "unreadable"
|
|
79
|
+
source = parse_source(info.path, text)
|
|
80
|
+
if source is None:
|
|
81
|
+
return "unparseable"
|
|
82
|
+
if source.code_lines < methodology.min_code_lines:
|
|
83
|
+
return "too_small"
|
|
84
|
+
hits = [hit for signal in FILE_SIGNALS for hit in signal.evaluate(source, methodology)]
|
|
85
|
+
return FileScore(
|
|
86
|
+
path=info.path,
|
|
87
|
+
language=info.language,
|
|
88
|
+
lines=source.code_lines,
|
|
89
|
+
is_test=is_test_path(info.path),
|
|
90
|
+
probability=round(file_probability(hits, methodology), 4),
|
|
91
|
+
signals=hits,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def _run_judge(
|
|
96
|
+
ws: Workspace,
|
|
97
|
+
params: DetectorInput,
|
|
98
|
+
ctx: RunContext,
|
|
99
|
+
methodology: Methodology,
|
|
100
|
+
scored: list[FileScore],
|
|
101
|
+
) -> JudgeRun:
|
|
102
|
+
"""Judge a sample of files and fold the verdicts into their probabilities."""
|
|
103
|
+
if ctx.llm is None:
|
|
104
|
+
return JudgeRun(
|
|
105
|
+
warnings=["The LLM judge was requested, but no model is configured."], partial=True
|
|
106
|
+
)
|
|
107
|
+
cfg = methodology.section("judge")
|
|
108
|
+
settings = JudgeSettings(
|
|
109
|
+
window_lines=int(cfg["window_lines"]),
|
|
110
|
+
token_budget=int(cfg["token_budget"]),
|
|
111
|
+
max_output_tokens=int(cfg["max_output_tokens"]),
|
|
112
|
+
agreement_share=float(cfg["agreement_share"]),
|
|
113
|
+
agreement_min_files=int(cfg["agreement_min_files"]),
|
|
114
|
+
disagreement_threshold=float(cfg["disagreement_threshold"]),
|
|
115
|
+
)
|
|
116
|
+
sample = sample_files(
|
|
117
|
+
scored, max_files=params.max_files_for_judge, min_lines=int(cfg["min_lines"]),
|
|
118
|
+
seed_text=ws.source,
|
|
119
|
+
) # fmt: skip
|
|
120
|
+
if not sample:
|
|
121
|
+
return JudgeRun(warnings=["No file was large enough for the LLM judge."])
|
|
122
|
+
texts = await asyncio.to_thread(lambda: [ws.read_text(f.path) for f in sample])
|
|
123
|
+
llm = ctx.llm.session(max_cost_usd=params.max_cost_usd)
|
|
124
|
+
|
|
125
|
+
def progress(index: int, total: int, path: str) -> None:
|
|
126
|
+
# the judge is the slow part (minutes), so it gets most of the bar
|
|
127
|
+
ctx.report_progress(
|
|
128
|
+
"judge", f"Judging {path} ({index + 1}/{total})", 0.35 + 0.55 * index / max(total, 1)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
run = await Judge(llm, settings).run(
|
|
132
|
+
list(zip(sample, texts, strict=True)),
|
|
133
|
+
max_seconds=params.max_judge_seconds,
|
|
134
|
+
cancelled=lambda: ctx.cancel_token.cancelled,
|
|
135
|
+
progress=progress,
|
|
136
|
+
)
|
|
137
|
+
for f in scored:
|
|
138
|
+
verdict = run.verdicts.get(f.path)
|
|
139
|
+
if verdict is not None:
|
|
140
|
+
f.judge = verdict
|
|
141
|
+
f.probability = round(
|
|
142
|
+
file_probability(f.signals, methodology, verdict.likelihood_ai, verdict.confidence),
|
|
143
|
+
4,
|
|
144
|
+
)
|
|
145
|
+
if not run.verdicts:
|
|
146
|
+
run.warnings.append("The LLM judge produced no usable verdicts.")
|
|
147
|
+
run.partial = True
|
|
148
|
+
return run
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _ranked_evidence(
|
|
152
|
+
repo_hits: list[SignalHit],
|
|
153
|
+
files: list[FileScore],
|
|
154
|
+
methodology: Methodology,
|
|
155
|
+
toward_ai: bool,
|
|
156
|
+
limit: int = 5,
|
|
157
|
+
) -> list[Evidence]:
|
|
158
|
+
weights = {**methodology.file_weights, **methodology.repo_weights}
|
|
159
|
+
candidates: list[tuple[float, SignalHit, str | None]] = []
|
|
160
|
+
for hit in repo_hits:
|
|
161
|
+
candidates.append((hit.strength * weights.get(hit.family, 0.0), hit, None))
|
|
162
|
+
for f in files:
|
|
163
|
+
for hit in f.signals:
|
|
164
|
+
candidates.append((hit.strength * weights.get(hit.family, 0.0), hit, f.path))
|
|
165
|
+
chosen = [c for c in candidates if (c[0] > 0) == toward_ai and c[0] != 0]
|
|
166
|
+
chosen.sort(key=lambda c: abs(c[0]), reverse=True)
|
|
167
|
+
evidence = []
|
|
168
|
+
for score, hit, path in chosen[:limit]:
|
|
169
|
+
first = hit.evidence[0] if hit.evidence else None
|
|
170
|
+
evidence.append(
|
|
171
|
+
Evidence(
|
|
172
|
+
kind=first.kind if first else "file",
|
|
173
|
+
location=(first.location if first else None) or path,
|
|
174
|
+
detail=hit.explanation,
|
|
175
|
+
weight=round(score, 3),
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
return evidence
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def detect(
|
|
182
|
+
ws: Workspace,
|
|
183
|
+
params: DetectorInput,
|
|
184
|
+
ctx: RunContext,
|
|
185
|
+
methodology: Methodology,
|
|
186
|
+
markers: MarkerSet,
|
|
187
|
+
methodology_version: str,
|
|
188
|
+
) -> Detection:
|
|
189
|
+
warnings: list[str] = []
|
|
190
|
+
partial = False
|
|
191
|
+
|
|
192
|
+
# 2. metadata markers and history
|
|
193
|
+
ctx.report_progress("markers", "Reading history and looking for AI tool markers", 0.1)
|
|
194
|
+
commits = []
|
|
195
|
+
changed: dict[str, list[str]] = {}
|
|
196
|
+
if ws.git is not None and ws.git.head is not None:
|
|
197
|
+
commits = await ws.git.commits(max_count=MAX_COMMITS)
|
|
198
|
+
changed = await ws.git.changed_files(max_count=MAX_COMMITS)
|
|
199
|
+
else:
|
|
200
|
+
warnings.append("No git history was available, so history signals were skipped.")
|
|
201
|
+
truncated = len(commits) >= MAX_COMMITS
|
|
202
|
+
if truncated:
|
|
203
|
+
warnings.append(f"Only the newest {MAX_COMMITS} commits were read.")
|
|
204
|
+
found_markers = detect_config_files(ws, markers)
|
|
205
|
+
commit_markers, marked_shas = detect_commit_markers(commits, markers)
|
|
206
|
+
found_markers += commit_markers
|
|
207
|
+
ctx.check_cancelled()
|
|
208
|
+
|
|
209
|
+
# 3. repository signals
|
|
210
|
+
ctx.report_progress("repo_signals", "Evaluating the repository", 0.2)
|
|
211
|
+
repo_ctx = RepoContext(ws, methodology, commits, changed, history_truncated=truncated)
|
|
212
|
+
repo_hits = [hit for signal in REPO_SIGNALS for hit in signal.evaluate(repo_ctx)]
|
|
213
|
+
ctx.check_cancelled()
|
|
214
|
+
|
|
215
|
+
# 4. file signals (in batches off the event loop, so progress and cancellation keep working)
|
|
216
|
+
candidates = [
|
|
217
|
+
f for f in ws.files
|
|
218
|
+
if f.language in SUPPORTED_LANGUAGES and is_supported(f.path)
|
|
219
|
+
and (params.include_tests or not is_test_path(f.path))
|
|
220
|
+
] # fmt: skip
|
|
221
|
+
scored: list[FileScore] = []
|
|
222
|
+
skip_reasons: Counter[str] = Counter()
|
|
223
|
+
skipped_paths: dict[str, str] = {}
|
|
224
|
+
for start in range(0, len(candidates), FILE_BATCH):
|
|
225
|
+
batch = candidates[start : start + FILE_BATCH]
|
|
226
|
+
ctx.report_progress(
|
|
227
|
+
"file_signals",
|
|
228
|
+
f"Analysing files {start + 1}-{start + len(batch)} of {len(candidates)}",
|
|
229
|
+
0.2 + 0.15 * start / max(len(candidates), 1),
|
|
230
|
+
)
|
|
231
|
+
results = await asyncio.to_thread(
|
|
232
|
+
lambda b=batch: [_analyse_file(ws, info, methodology) for info in b] # type: ignore[misc]
|
|
233
|
+
)
|
|
234
|
+
for info, outcome in zip(batch, results, strict=True):
|
|
235
|
+
if isinstance(outcome, str):
|
|
236
|
+
skip_reasons[outcome] += 1
|
|
237
|
+
skipped_paths[info.path] = outcome
|
|
238
|
+
else:
|
|
239
|
+
scored.append(outcome)
|
|
240
|
+
ctx.check_cancelled()
|
|
241
|
+
|
|
242
|
+
touches: Counter[str] = Counter()
|
|
243
|
+
for sha in marked_shas:
|
|
244
|
+
touches.update(changed.get(sha, []))
|
|
245
|
+
for f in scored:
|
|
246
|
+
f.ai_commit_touches = touches.get(f.path, 0)
|
|
247
|
+
|
|
248
|
+
if skip_reasons["unparseable"] or skip_reasons["unreadable"]:
|
|
249
|
+
n = skip_reasons["unparseable"] + skip_reasons["unreadable"]
|
|
250
|
+
warnings.append(f"{n} source files could not be read or parsed and were skipped.")
|
|
251
|
+
partial = True
|
|
252
|
+
# 5-6. LLM judge on a sample of files
|
|
253
|
+
# Explicit True: required (partial if it cannot run). None (default): run it when a model
|
|
254
|
+
# is configured, otherwise fall back to signals only. False: never.
|
|
255
|
+
judge_disagreement = False
|
|
256
|
+
explicit = params.use_llm_judge is True
|
|
257
|
+
if explicit or (params.use_llm_judge is None and ctx.llm is not None):
|
|
258
|
+
judge_outcome = await _run_judge(ws, params, ctx, methodology, scored)
|
|
259
|
+
warnings += judge_outcome.warnings
|
|
260
|
+
partial = partial or (explicit and judge_outcome.partial)
|
|
261
|
+
judge_disagreement = judge_outcome.disagreement is not None and (
|
|
262
|
+
judge_outcome.disagreement
|
|
263
|
+
> float(methodology.section("judge")["disagreement_threshold"])
|
|
264
|
+
)
|
|
265
|
+
ctx.check_cancelled() # a cancelled judge stops early; don't build a report from it
|
|
266
|
+
judged = any(f.judge is not None for f in scored if not f.is_test)
|
|
267
|
+
if not judged and "repo_model_signals_only" in methodology.data:
|
|
268
|
+
methodology = Methodology(
|
|
269
|
+
methodology.version,
|
|
270
|
+
{**methodology.data, "repo_model": methodology.data["repo_model_signals_only"]},
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
# 7. aggregate
|
|
274
|
+
ctx.report_progress("aggregate", "Combining the evidence", 0.95)
|
|
275
|
+
main_files = [f for f in scored if not f.is_test]
|
|
276
|
+
repo_level = repo_shift(repo_hits, methodology)
|
|
277
|
+
shift = repo_level + judge_shift(main_files, methodology)
|
|
278
|
+
estimate = round(repo_estimate(main_files, shift, methodology), 4)
|
|
279
|
+
low, high = estimate_range(main_files, repo_level, estimate, methodology)
|
|
280
|
+
|
|
281
|
+
languages = Counter(f.language for f in ws.files if f.language in CODE_LANGUAGES)
|
|
282
|
+
supported = {k: v for k, v in languages.items() if k in SUPPORTED_LANGUAGES}
|
|
283
|
+
unsupported = {k: v for k, v in languages.items() if k not in SUPPORTED_LANGUAGES}
|
|
284
|
+
code_bytes = sum(f.size for f in ws.files if f.language in CODE_LANGUAGES)
|
|
285
|
+
supported_bytes = sum(f.size for f in ws.files if f.language in SUPPORTED_LANGUAGES)
|
|
286
|
+
supported_share = supported_bytes / code_bytes if code_bytes else 0.0
|
|
287
|
+
families = {h.family for h in repo_hits} | {h.family for f in main_files for h in f.signals}
|
|
288
|
+
confidence, reasons = confidence_level(
|
|
289
|
+
ConfidenceFacts(
|
|
290
|
+
len(families), len(main_files), high - low, supported_share, judge_disagreement
|
|
291
|
+
),
|
|
292
|
+
methodology,
|
|
293
|
+
)
|
|
294
|
+
cap = methodology.section("confidence").get("signals_only_max")
|
|
295
|
+
if not judged and cap == "low" and confidence != "low":
|
|
296
|
+
confidence = "low"
|
|
297
|
+
reasons = [
|
|
298
|
+
"the LLM judge did not run, and the heuristic signals alone separate human from AI "
|
|
299
|
+
"code poorly"
|
|
300
|
+
]
|
|
301
|
+
low, high = widen_range(low, high, estimate, confidence, methodology)
|
|
302
|
+
|
|
303
|
+
# 8. what the report shows besides the scores
|
|
304
|
+
scored_paths = {f.path for f in scored}
|
|
305
|
+
excerpts = await asyncio.to_thread(build_excerpts, scored, methodology, ws.read_text)
|
|
306
|
+
|
|
307
|
+
def unscored_reason(info: FileInfo) -> str:
|
|
308
|
+
if info.path in skipped_paths:
|
|
309
|
+
return skipped_paths[info.path]
|
|
310
|
+
if info.language in SUPPORTED_LANGUAGES and is_supported(info.path):
|
|
311
|
+
return "test_file"
|
|
312
|
+
return "unsupported_language"
|
|
313
|
+
|
|
314
|
+
unscored_files, unscored_truncated = unscored(
|
|
315
|
+
[(f.path, unscored_reason(f)) for f in ws.files if f.path not in scored_paths]
|
|
316
|
+
+ [(s.path, s.reason) for s in ws.skipped]
|
|
317
|
+
)
|
|
318
|
+
large_files = int(methodology.thresholds_for("commit_shape")["large_commit_files"])
|
|
319
|
+
|
|
320
|
+
output = DetectorOutput(
|
|
321
|
+
methodology_version=methodology_version,
|
|
322
|
+
estimate=estimate,
|
|
323
|
+
estimate_range=(low, high),
|
|
324
|
+
confidence=confidence,
|
|
325
|
+
confidence_reasons=reasons,
|
|
326
|
+
metadata_markers=found_markers,
|
|
327
|
+
repo_signals=repo_hits,
|
|
328
|
+
files=sorted(scored, key=lambda f: f.probability, reverse=True),
|
|
329
|
+
files_analyzed=len(scored),
|
|
330
|
+
files_skipped=len(ws.skipped) + sum(skip_reasons.values()),
|
|
331
|
+
languages=dict(supported),
|
|
332
|
+
unsupported_languages=dict(unsupported),
|
|
333
|
+
excerpts=excerpts,
|
|
334
|
+
commits=commit_summaries(commits, changed, markers, large_files),
|
|
335
|
+
commits_total=len(commits),
|
|
336
|
+
unscored_files=unscored_files,
|
|
337
|
+
unscored_truncated=unscored_truncated,
|
|
338
|
+
)
|
|
339
|
+
findings = _findings(output, repo_hits, main_files, scored, methodology, supported_share)
|
|
340
|
+
summary = (
|
|
341
|
+
f"Estimated likelihood that this code was written with AI assistance: {estimate:.2f} "
|
|
342
|
+
f"(range {low:.2f}-{high:.2f}, {confidence} confidence), from {len(main_files)} source "
|
|
343
|
+
f"files and {len(commits)} commits."
|
|
344
|
+
)
|
|
345
|
+
if found_markers:
|
|
346
|
+
tools = sorted({m.tool for m in found_markers})
|
|
347
|
+
summary += f" Metadata confirms AI tool usage ({', '.join(tools)})."
|
|
348
|
+
summary += " " + CAVEAT
|
|
349
|
+
return Detection(output, summary, findings, warnings, partial)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _findings(
|
|
353
|
+
output: DetectorOutput,
|
|
354
|
+
repo_hits: list[SignalHit],
|
|
355
|
+
main_files: list[FileScore],
|
|
356
|
+
scored: list[FileScore],
|
|
357
|
+
methodology: Methodology,
|
|
358
|
+
supported_share: float,
|
|
359
|
+
) -> list[Finding]:
|
|
360
|
+
low, high = output.estimate_range
|
|
361
|
+
estimate_summary = (
|
|
362
|
+
f"{output.estimate:.2f}, plausibly between {low:.2f} and {high:.2f}; "
|
|
363
|
+
f"{output.confidence} confidence."
|
|
364
|
+
)
|
|
365
|
+
if output.confidence_reasons:
|
|
366
|
+
estimate_summary += (
|
|
367
|
+
" Confidence is limited because " + "; ".join(output.confidence_reasons) + "."
|
|
368
|
+
)
|
|
369
|
+
findings = [
|
|
370
|
+
Finding(
|
|
371
|
+
title="Estimated likelihood of AI assistance",
|
|
372
|
+
severity_or_score=output.estimate,
|
|
373
|
+
summary=estimate_summary,
|
|
374
|
+
evidence=[
|
|
375
|
+
Evidence(kind="metric", detail=f"range {low:.2f}-{high:.2f}"),
|
|
376
|
+
Evidence(kind="metric", detail=f"methodology {output.methodology_version}"),
|
|
377
|
+
],
|
|
378
|
+
)
|
|
379
|
+
]
|
|
380
|
+
if output.metadata_markers:
|
|
381
|
+
findings.append(
|
|
382
|
+
Finding(
|
|
383
|
+
title="AI tool usage confirmed by metadata",
|
|
384
|
+
summary=(
|
|
385
|
+
"These traces prove that AI tools were used in this repository. They do not "
|
|
386
|
+
"show how much of the code the tools wrote, so they are not part of the "
|
|
387
|
+
"estimate."
|
|
388
|
+
),
|
|
389
|
+
evidence=[
|
|
390
|
+
Evidence(
|
|
391
|
+
kind="config" if m.kind == "config_file" else "commit",
|
|
392
|
+
location=m.location,
|
|
393
|
+
detail=m.detail,
|
|
394
|
+
)
|
|
395
|
+
for m in output.metadata_markers
|
|
396
|
+
],
|
|
397
|
+
)
|
|
398
|
+
)
|
|
399
|
+
context = [h for h in repo_hits if not methodology.repo_weights.get(h.family, 0.0)]
|
|
400
|
+
if context:
|
|
401
|
+
findings.append(
|
|
402
|
+
Finding(
|
|
403
|
+
title="Repository context (not part of the estimate)",
|
|
404
|
+
summary=(
|
|
405
|
+
"Shown for context only. In evaluation, commit-history and README style "
|
|
406
|
+
"mostly separated old projects from new ones, not human from AI authors."
|
|
407
|
+
),
|
|
408
|
+
evidence=[
|
|
409
|
+
Evidence(
|
|
410
|
+
kind=h.evidence[0].kind if h.evidence else "metric",
|
|
411
|
+
location=h.evidence[0].location if h.evidence else None,
|
|
412
|
+
detail=h.explanation,
|
|
413
|
+
)
|
|
414
|
+
for h in context
|
|
415
|
+
],
|
|
416
|
+
)
|
|
417
|
+
)
|
|
418
|
+
toward_ai = _ranked_evidence(repo_hits, main_files, methodology, toward_ai=True)
|
|
419
|
+
toward_human = _ranked_evidence(repo_hits, main_files, methodology, toward_ai=False)
|
|
420
|
+
findings.append(
|
|
421
|
+
Finding(
|
|
422
|
+
title="Evidence toward AI assistance",
|
|
423
|
+
summary="The strongest signs of AI-written code." if toward_ai else "None found.",
|
|
424
|
+
evidence=toward_ai,
|
|
425
|
+
)
|
|
426
|
+
)
|
|
427
|
+
findings.append(
|
|
428
|
+
Finding(
|
|
429
|
+
title="Evidence toward human authorship",
|
|
430
|
+
summary="The strongest signs of people at work." if toward_human else "None found.",
|
|
431
|
+
evidence=toward_human,
|
|
432
|
+
)
|
|
433
|
+
)
|
|
434
|
+
tests = [f for f in scored if f.is_test]
|
|
435
|
+
if tests:
|
|
436
|
+
mean = sum(f.probability for f in tests) / len(tests)
|
|
437
|
+
findings.append(
|
|
438
|
+
Finding(
|
|
439
|
+
title="Test files",
|
|
440
|
+
severity_or_score=round(mean, 4),
|
|
441
|
+
summary=f"{len(tests)} test files average {mean:.2f}; they are not part of the "
|
|
442
|
+
"estimate.",
|
|
443
|
+
)
|
|
444
|
+
)
|
|
445
|
+
if output.unsupported_languages and supported_share < 0.8:
|
|
446
|
+
langs = ", ".join(f"{k} ({v})" for k, v in sorted(output.unsupported_languages.items()))
|
|
447
|
+
findings.append(
|
|
448
|
+
Finding(
|
|
449
|
+
title="Coverage",
|
|
450
|
+
summary=(
|
|
451
|
+
f"Only {supported_share:.0%} of the code is in a language analysed file by "
|
|
452
|
+
f"file (Python, JavaScript, TypeScript). Not analysed: {langs}."
|
|
453
|
+
),
|
|
454
|
+
)
|
|
455
|
+
)
|
|
456
|
+
findings.append(Finding(title="How to read this result", summary=CAVEAT))
|
|
457
|
+
return findings
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561
|