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.
@@ -0,0 +1,40 @@
1
+ """Choose which files the LLM judge reads.
2
+
3
+ Small files, tests and very low-information files are skipped. The rest are split into thirds
4
+ by their heuristic probability (most AI-like, most human-like, in between) and picked in
5
+ turn, so the judge also sees likely-human code and is not only asked to confirm the
6
+ heuristics. The order is seeded, so the same repository always gives the same sample.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import random
13
+ from collections.abc import Sequence
14
+
15
+ from ai_code_detector.models import FileScore
16
+
17
+
18
+ def sample_files(
19
+ files: Sequence[FileScore],
20
+ *,
21
+ max_files: int,
22
+ min_lines: int,
23
+ seed_text: str,
24
+ ) -> list[FileScore]:
25
+ eligible = [f for f in files if f.lines >= min_lines and not f.is_test]
26
+ if len(eligible) <= max_files:
27
+ return sorted(eligible, key=lambda f: f.path)
28
+ seed = int.from_bytes(hashlib.sha256(seed_text.encode("utf-8")).digest()[:8], "big")
29
+ rng = random.Random(seed)
30
+ ordered = sorted(eligible, key=lambda f: (f.probability, f.path))
31
+ third = len(ordered) // 3
32
+ groups = [ordered[2 * third :], ordered[:third], ordered[third : 2 * third]]
33
+ for group in groups:
34
+ rng.shuffle(group)
35
+ picked: list[FileScore] = []
36
+ while len(picked) < max_files and any(groups):
37
+ for group in groups:
38
+ if group and len(picked) < max_files:
39
+ picked.append(group.pop())
40
+ return sorted(picked, key=lambda f: f.path)
@@ -0,0 +1,108 @@
1
+ """Detect explicit AI-tool markers: config files, co-author trailers, bot identities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from collections import defaultdict
8
+ from dataclasses import dataclass
9
+ from importlib import resources
10
+
11
+ from margin_core.loaders import GitCommit, Workspace
12
+
13
+ from ai_code_detector.models import MetadataMarker
14
+
15
+ DEFAULT_MARKERS = "v1"
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class MarkerSet:
20
+ version: str
21
+ config_files: tuple[tuple[str, str], ...]
22
+ trailers: tuple[tuple[re.Pattern[str], str], ...]
23
+ message_lines: tuple[tuple[re.Pattern[str], str], ...]
24
+ identities: tuple[tuple[re.Pattern[str], str], ...]
25
+
26
+
27
+ def load_markers(version: str = DEFAULT_MARKERS) -> MarkerSet:
28
+ text = (
29
+ resources.files("ai_code_detector.markers")
30
+ .joinpath(f"{version}.toml")
31
+ .read_text(encoding="utf-8")
32
+ )
33
+ data = tomllib.loads(text)
34
+
35
+ def compiled(key: str) -> tuple[tuple[re.Pattern[str], str], ...]:
36
+ return tuple(
37
+ (re.compile(entry["pattern"], re.IGNORECASE), entry["tool"])
38
+ for entry in data.get(key, [])
39
+ )
40
+
41
+ return MarkerSet(
42
+ version=str(data["version"]),
43
+ config_files=tuple((e["path"], e["tool"]) for e in data.get("config_file", [])),
44
+ trailers=compiled("trailer"),
45
+ message_lines=compiled("message_line"),
46
+ identities=compiled("identity"),
47
+ )
48
+
49
+
50
+ def detect_config_files(ws: Workspace, markers: MarkerSet) -> list[MetadataMarker]:
51
+ return [
52
+ MetadataMarker(
53
+ kind="config_file",
54
+ tool=tool,
55
+ location=path,
56
+ detail=f"`{path}` is a configuration or instructions file for {tool}.",
57
+ )
58
+ for path, tool in markers.config_files
59
+ if ws.exists(path)
60
+ ]
61
+
62
+
63
+ def commit_marker_tools(commit: GitCommit, markers: MarkerSet) -> list[tuple[str, str]]:
64
+ """``(kind, tool)`` pairs for every marker found in one commit."""
65
+ found: list[tuple[str, str]] = []
66
+ lines = [line.strip() for line in commit.message.splitlines()]
67
+ for line in lines:
68
+ if line.lower().startswith("co-authored-by:"):
69
+ found += [("commit_trailer", tool) for pattern, tool in markers.trailers
70
+ if pattern.search(line)] # fmt: skip
71
+ found += [("generated_with_line", tool) for pattern, tool in markers.message_lines
72
+ if pattern.search(line)] # fmt: skip
73
+ identities = (
74
+ f"{commit.author_name} <{commit.author_email}>",
75
+ f"{commit.committer_name} <{commit.committer_email}>",
76
+ )
77
+ for pattern, tool in markers.identities:
78
+ if any(pattern.search(identity) for identity in identities):
79
+ found.append(("bot_author", tool))
80
+ return list(dict.fromkeys(found))
81
+
82
+
83
+ def detect_commit_markers(
84
+ commits: list[GitCommit], markers: MarkerSet
85
+ ) -> tuple[list[MetadataMarker], set[str]]:
86
+ """One marker per (kind, tool) with counts, plus the SHAs of every marked commit."""
87
+ by_key: dict[tuple[str, str], list[str]] = defaultdict(list)
88
+ marked: set[str] = set()
89
+ for commit in commits:
90
+ for key in commit_marker_tools(commit, markers):
91
+ by_key[key].append(commit.sha)
92
+ marked.add(commit.sha)
93
+ labels = {
94
+ "commit_trailer": "carry a co-author trailer for",
95
+ "generated_with_line": "say they were generated with",
96
+ "bot_author": "were authored or committed by",
97
+ }
98
+ result = []
99
+ for (kind, tool), shas in by_key.items():
100
+ result.append(
101
+ MetadataMarker(
102
+ kind=kind, # type: ignore[arg-type]
103
+ tool=tool,
104
+ location=shas[0],
105
+ detail=f"{len(shas)} of {len(commits)} commits {labels[kind]} {tool}.",
106
+ )
107
+ )
108
+ return result, marked
@@ -0,0 +1,98 @@
1
+ # Explicit traces of AI coding tools (methodology: "metadata markers").
2
+ #
3
+ # Markers prove that a tool was used. They never enter the statistical estimate, because they
4
+ # are trivially added or removed; they are reported separately.
5
+ #
6
+ # Every commit marker below was checked against a real public commit on 2026-10-18 (the
7
+ # `example` field). Add new markers only with a verified example.
8
+
9
+ version = "v1"
10
+
11
+ # Files or folders created or read by AI coding tools. Paths are relative to the analysed root.
12
+ [[config_file]]
13
+ path = "CLAUDE.md"
14
+ tool = "Claude Code"
15
+
16
+ [[config_file]]
17
+ path = ".claude"
18
+ tool = "Claude Code"
19
+
20
+ [[config_file]]
21
+ path = "AGENTS.md"
22
+ tool = "an AI coding agent (AGENTS.md convention)"
23
+
24
+ [[config_file]]
25
+ path = "GEMINI.md"
26
+ tool = "Gemini CLI"
27
+
28
+ [[config_file]]
29
+ path = ".cursorrules"
30
+ tool = "Cursor"
31
+
32
+ [[config_file]]
33
+ path = ".cursor/rules"
34
+ tool = "Cursor"
35
+
36
+ [[config_file]]
37
+ path = ".github/copilot-instructions.md"
38
+ tool = "GitHub Copilot"
39
+
40
+ [[config_file]]
41
+ path = ".windsurfrules"
42
+ tool = "Windsurf"
43
+
44
+ [[config_file]]
45
+ path = ".clinerules"
46
+ tool = "Cline"
47
+
48
+ [[config_file]]
49
+ path = ".aider.conf.yml"
50
+ tool = "Aider"
51
+
52
+ # Co-author trailers: matched (case-insensitively) against each "Co-authored-by:" line.
53
+ [[trailer]]
54
+ pattern = '<noreply@anthropic\.com>'
55
+ tool = "Claude"
56
+ example = "adanalife/infra@3d78c8a36c"
57
+
58
+ [[trailer]]
59
+ pattern = '^co-authored-by:\s*gemini\b.*<noreply@google\.com>'
60
+ tool = "Gemini"
61
+ example = "seanpor/JA4proxy@b7150f7451"
62
+
63
+ [[trailer]]
64
+ pattern = '<noreply@openai\.com>'
65
+ tool = "OpenAI Codex"
66
+ example = "openflowfm/visuals@f8b135806e"
67
+
68
+ [[trailer]]
69
+ pattern = '<cursoragent@cursor\.com>'
70
+ tool = "Cursor"
71
+ example = "juliano-pezzini/mytruetrack@4a62fff1c0"
72
+
73
+ # Lines anywhere in a commit message.
74
+ [[message_line]]
75
+ pattern = 'generated with \[?claude code'
76
+ tool = "Claude Code"
77
+ example = "briandconnelly/skills@51be76c730"
78
+
79
+ # Author or committer identities ("name <email>"), matched case-insensitively.
80
+ [[identity]]
81
+ pattern = '\(aider\)\s*<'
82
+ tool = "Aider"
83
+ example = "uwislab/urobot-mcp@478a4e9c25"
84
+
85
+ [[identity]]
86
+ pattern = '<198982749\+copilot@users\.noreply\.github\.com>'
87
+ tool = "GitHub Copilot coding agent"
88
+ example = "Mryan2005/novel-manager@a6fc1dfdf3"
89
+
90
+ [[identity]]
91
+ pattern = 'devin-ai-integration\[bot\]'
92
+ tool = "Devin"
93
+ example = "Huvinesh-Rajendran-12/culture-engine@8793214468"
94
+
95
+ [[identity]]
96
+ pattern = 'google-labs-jules\[bot\]'
97
+ tool = "Jules"
98
+ example = "rvoidex7/entropy-forge@4efef3bc21"
@@ -0,0 +1,71 @@
1
+ """Versioned weights and thresholds. Code reads numbers from here, never hard-codes them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass
7
+ from importlib import resources
8
+ from typing import Any
9
+
10
+ DEFAULT_METHODOLOGY = "v1"
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Methodology:
15
+ version: str
16
+ data: dict[str, Any]
17
+
18
+ @property
19
+ def secondary_factor(self) -> float:
20
+ return float(self.data["secondary_factor"])
21
+
22
+ @property
23
+ def min_code_lines(self) -> int:
24
+ return int(self.data["min_code_lines"])
25
+
26
+ @property
27
+ def calibrated(self) -> bool:
28
+ return bool(self.data.get("calibrated", False))
29
+
30
+ @property
31
+ def bias(self) -> float:
32
+ return float(self.data["bias"])
33
+
34
+ @property
35
+ def repo_intercept(self) -> float:
36
+ """Repository model: log-odds intercept (v0: 0)."""
37
+ return float(self.data.get("repo_model", {}).get("intercept", 0.0))
38
+
39
+ @property
40
+ def repo_file_coefficient(self) -> float:
41
+ """Repository model: weight on the files' mean log-odds (v0: 1)."""
42
+ return float(self.data.get("repo_model", {}).get("file_coefficient", 1.0))
43
+
44
+ @property
45
+ def repo_judge_coefficient(self) -> float:
46
+ """Repository model: weight on the judge's mean log-odds (v0: 0, judge is per file)."""
47
+ return float(self.data.get("repo_model", {}).get("judge_coefficient", 0.0))
48
+
49
+ @property
50
+ def file_weights(self) -> dict[str, float]:
51
+ return {k: float(v) for k, v in self.data["file_weights"].items()}
52
+
53
+ @property
54
+ def repo_weights(self) -> dict[str, float]:
55
+ return {k: float(v) for k, v in self.data["repo_weights"].items()}
56
+
57
+ def section(self, name: str) -> dict[str, Any]:
58
+ return dict(self.data[name])
59
+
60
+ def thresholds_for(self, signal_id: str) -> dict[str, float]:
61
+ return {k: float(v) for k, v in self.data["thresholds"][signal_id].items()}
62
+
63
+
64
+ def load_methodology(version: str = DEFAULT_METHODOLOGY) -> Methodology:
65
+ text = (
66
+ resources.files("ai_code_detector.methodology")
67
+ .joinpath(f"{version}.toml")
68
+ .read_text(encoding="utf-8")
69
+ )
70
+ data = tomllib.loads(text)
71
+ return Methodology(version=str(data["version"]), data=data)
@@ -0,0 +1,119 @@
1
+ # Methodology v0: hand-set weights and thresholds (phase 3, before any data).
2
+ #
3
+ # These numbers are starting guesses, not calibrated values. Phase 4 replaces them with
4
+ # weights fitted on the evaluation dataset (methodology v1). Change nothing here without
5
+ # re-running the evaluation and recording the results.
6
+
7
+ version = "v0"
8
+
9
+ # Uncalibrated methodologies never report "high" confidence: a narrow range only shows the
10
+ # files agree with each other under these weights, not that the weights are right.
11
+ calibrated = false
12
+
13
+ # Inside a signal family, the strongest hit counts fully and the others by this factor.
14
+ secondary_factor = 0.25
15
+
16
+ # Python files with fewer code lines than this are too small to judge and are skipped.
17
+ min_code_lines = 15
18
+
19
+ # Prior log-odds of AI assistance when there is no evidence (0.0 means 0.5).
20
+ bias = 0.0
21
+
22
+ # Log-odds weight per file-level family.
23
+ [file_weights]
24
+ comments = 1.0
25
+ naming = 0.4
26
+ human_traces = 1.0
27
+
28
+ # Log-odds shift per repository-level family, applied to the repository estimate.
29
+ [repo_weights]
30
+ history = 0.8
31
+ docs = 0.3
32
+
33
+ # LLM judge (phase 4). weight: log-odds added per unit of logit(judge likelihood),
34
+ # scaled by the judge's own confidence. Until calibration (v1) this is a guess.
35
+ [judge]
36
+ weight = 0.5
37
+ min_lines = 30
38
+ # Sized for a local 7B model on an 8 GB GPU: a ~7.5K-token prompt took ~30 s per call
39
+ # (2026-10-18), so prompts stay near 3.5K tokens.
40
+ window_lines = 150
41
+ token_budget = 3500
42
+ # Typical answers are ~300-450 tokens at ~20 tokens/s; 800 is a cap for rare long ones.
43
+ max_output_tokens = 800
44
+ agreement_share = 0.2
45
+ agreement_min_files = 2
46
+ disagreement_threshold = 0.3
47
+
48
+ [bootstrap]
49
+ resamples = 1000
50
+ seed = 1234
51
+ low_quantile = 0.10
52
+ high_quantile = 0.90
53
+ min_files = 5
54
+
55
+ [confidence]
56
+ high_families = 3
57
+ high_files = 20
58
+ high_max_width = 0.25
59
+ high_supported_share = 0.8
60
+ medium_families = 2
61
+ medium_files = 5
62
+ medium_max_width = 0.45
63
+
64
+ [thresholds.comment_density]
65
+ density_low = 0.20 # (comment + docstring lines) / code lines where AI evidence starts
66
+ density_high = 0.60 # ... and where it is at full strength
67
+ trivial_max_statements = 2 # a function with at most this many statements is "trivial"
68
+ trivial_min_count = 3
69
+ trivial_ratio_low = 0.5 # share of trivial functions with docstrings where evidence starts
70
+ sparse_density = 0.02 # below this, with enough code, comments are evidence of a human
71
+ sparse_min_code_lines = 60
72
+ sparse_strength = -0.3
73
+
74
+ [thresholds.restating_comments]
75
+ min_words = 2
76
+ max_words = 10
77
+ min_overlap = 0.6
78
+ min_count = 2
79
+ min_ratio = 0.25
80
+
81
+ [thresholds.naming_patterns]
82
+ min_identifiers = 10
83
+ generic_ratio = 0.15
84
+ min_avg_length = 8.0
85
+ short_ratio = 0.25
86
+
87
+ [thresholds.idiosyncrasy]
88
+ per_marker = 0.25
89
+ quote_min_strings = 10
90
+ quote_min_minority = 0.25
91
+ quote_strength = 0.2
92
+ max_strength = 0.8
93
+
94
+ [thresholds.dead_or_debug_code]
95
+ per_block = 0.2
96
+ per_debug = 0.3
97
+ max_strength = 0.8
98
+
99
+ [thresholds.commit_shape]
100
+ min_files = 10
101
+ first_share = 0.6
102
+ large_commit_files = 15
103
+ large_commit_share = 0.3
104
+ min_commits_for_large = 5
105
+ single_commit_strength = 0.25
106
+
107
+ [thresholds.history_depth]
108
+ min_commits = 30
109
+ min_span_days = 90
110
+ messy_share = 0.15
111
+ small_min_commits = 10
112
+ small_min_span_days = 30
113
+ small_messy_share = 0.2
114
+
115
+ [thresholds.readme_patterns]
116
+ emoji_headings = 3
117
+ template_sections = 5
118
+ marketing_words = 3
119
+ max_strength = 0.6
@@ -0,0 +1,141 @@
1
+ # Methodology v1: weights fitted on dataset v1's TRAIN split (eval/fit.py), checked on
2
+ # VALIDATION, reported once on TEST (eval/results/v1_test_*.json). Thresholds are unchanged
3
+ # from v0. See docs/methodology.md for what the numbers mean and their limits.
4
+
5
+ version = "v1"
6
+
7
+ # Still not calibrated: validation expected calibration error was 0.27 (target 0.08), so
8
+ # confidence stays capped at medium. Ranking is usable (train AUC 0.86 with the judge);
9
+ # probabilities are not.
10
+ calibrated = false
11
+
12
+ # Estimates at or above this kept false positives on human repositories at or below 5% on the
13
+ # train split, but caught only 1 of 21 AI repositories. Documented, not used for any label.
14
+ operating_threshold = 0.915
15
+
16
+ # Inside a signal family, the strongest hit counts fully and the others by this factor.
17
+ secondary_factor = 0.25
18
+
19
+ # Python files with fewer code lines than this are too small to judge and are skipped.
20
+ min_code_lines = 15
21
+
22
+ # File model (fitted): intercept and log-odds weight per file-level family. Note the signs:
23
+ # on 2025-26 agent-built code, MORE comments and more generic names lean HUMAN.
24
+ bias = 0.2174
25
+
26
+ [file_weights]
27
+ comments = -0.9996
28
+ naming = -0.2314
29
+ human_traces = 0.9677
30
+
31
+ # Repository-level families are shown as context but not scored: `history` separated messy
32
+ # pre-2021 histories from tidy modern ones (era, not authorship) and, when weighted, turned
33
+ # every recent human repository in the dataset into a near or actual false positive.
34
+ [repo_weights]
35
+ history = 0.0
36
+ docs = 0.0
37
+
38
+ # Repository model when the LLM judge ran (B3, fitted on train, L2 0.3):
39
+ # logit = intercept + file_coefficient x logit(mean file probability)
40
+ # + judge_coefficient x mean(judge confidence x logit(judge likelihood)).
41
+ [repo_model]
42
+ intercept = 1.3764
43
+ file_coefficient = 0.2678
44
+ judge_coefficient = 1.5425
45
+
46
+ # Repository model when the judge did not run (B2, signals only). Weak: train AUC 0.73 and
47
+ # 39% false positives at 0.5, so confidence is capped at low (see [confidence]).
48
+ [repo_model_signals_only]
49
+ intercept = -0.0051
50
+ file_coefficient = 2.1731
51
+ judge_coefficient = 0.0
52
+
53
+ # LLM judge. Its verdicts enter at repository level ([repo_model].judge_coefficient), not per
54
+ # file, so the per-file weight is 0. Model: qwen3.5:9b (chosen by eval/tools/compare_judges.py).
55
+ [judge]
56
+ weight = 0.0
57
+ min_lines = 30
58
+ # Sized for a local 7B model on an 8 GB GPU: a ~7.5K-token prompt took ~30 s per call
59
+ # (2026-10-18), so prompts stay near 3.5K tokens.
60
+ window_lines = 150
61
+ token_budget = 3500
62
+ # Typical answers are ~300-450 tokens at ~20 tokens/s; 800 is a cap for rare long ones.
63
+ max_output_tokens = 800
64
+ agreement_share = 0.2
65
+ agreement_min_files = 2
66
+ disagreement_threshold = 0.3
67
+
68
+ [bootstrap]
69
+ resamples = 1000
70
+ seed = 1234
71
+ low_quantile = 0.10
72
+ high_quantile = 0.90
73
+ min_files = 5
74
+
75
+ [confidence]
76
+ # Without the judge, signals alone separate human from AI code poorly; never claim more.
77
+ signals_only_max = "low"
78
+ high_families = 3
79
+ high_files = 20
80
+ high_max_width = 0.25
81
+ high_supported_share = 0.8
82
+ medium_families = 2
83
+ medium_files = 5
84
+ medium_max_width = 0.45
85
+
86
+ [thresholds.comment_density]
87
+ density_low = 0.20 # (comment + docstring lines) / code lines where AI evidence starts
88
+ density_high = 0.60 # ... and where it is at full strength
89
+ trivial_max_statements = 2 # a function with at most this many statements is "trivial"
90
+ trivial_min_count = 3
91
+ trivial_ratio_low = 0.5 # share of trivial functions with docstrings where evidence starts
92
+ sparse_density = 0.02 # below this, with enough code, comments are evidence of a human
93
+ sparse_min_code_lines = 60
94
+ sparse_strength = -0.3
95
+
96
+ [thresholds.restating_comments]
97
+ min_words = 2
98
+ max_words = 10
99
+ min_overlap = 0.6
100
+ min_count = 2
101
+ min_ratio = 0.25
102
+
103
+ [thresholds.naming_patterns]
104
+ min_identifiers = 10
105
+ generic_ratio = 0.15
106
+ min_avg_length = 8.0
107
+ short_ratio = 0.25
108
+
109
+ [thresholds.idiosyncrasy]
110
+ per_marker = 0.25
111
+ quote_min_strings = 10
112
+ quote_min_minority = 0.25
113
+ quote_strength = 0.2
114
+ max_strength = 0.8
115
+
116
+ [thresholds.dead_or_debug_code]
117
+ per_block = 0.2
118
+ per_debug = 0.3
119
+ max_strength = 0.8
120
+
121
+ [thresholds.commit_shape]
122
+ min_files = 10
123
+ first_share = 0.6
124
+ large_commit_files = 15
125
+ large_commit_share = 0.3
126
+ min_commits_for_large = 5
127
+ single_commit_strength = 0.25
128
+
129
+ [thresholds.history_depth]
130
+ min_commits = 30
131
+ min_span_days = 90
132
+ messy_share = 0.15
133
+ small_min_commits = 10
134
+ small_min_span_days = 30
135
+ small_messy_share = 0.2
136
+
137
+ [thresholds.readme_patterns]
138
+ emoji_headings = 3
139
+ template_sections = 5
140
+ marketing_words = 3
141
+ max_strength = 0.6