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,179 @@
1
+ """What a report needs besides the scores: code excerpts around the evidence, a commit list
2
+ for the timeline, and the files that have no score. Everything here is capped, so a large
3
+ repository still produces a result of a sensible size."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections.abc import Callable, Iterable
9
+
10
+ from margin_core.loaders import GitCommit
11
+
12
+ from ai_code_detector.markers import MarkerSet, commit_marker_tools
13
+ from ai_code_detector.methodology import Methodology
14
+ from ai_code_detector.models import (
15
+ CommitSummary,
16
+ Excerpt,
17
+ ExcerptHunk,
18
+ ExcerptMark,
19
+ FileScore,
20
+ QuotedEvidence,
21
+ Side,
22
+ UnscoredFile,
23
+ )
24
+
25
+ CONTEXT_LINES = 3 # lines shown around each marked span
26
+ MERGE_GAP = 2 # hunks closer than this are joined
27
+ MAX_EXCERPT_FILES = 30
28
+ MAX_LINES_PER_FILE = 80
29
+ MAX_LINES_TOTAL = 800
30
+ MAX_LINE_CHARS = 240
31
+ MAX_NOTE_CHARS = 120
32
+ MAX_COMMITS_REPORTED = 500
33
+ MAX_SUBJECT_CHARS = 120
34
+ MAX_UNSCORED = 3000
35
+
36
+ _LOCATION = re.compile(r"^(?P<path>.+):(?P<start>\d+)(?:-(?P<end>\d+))?$")
37
+
38
+
39
+ def parse_location(location: str | None, path: str) -> tuple[int, int] | None:
40
+ """``"src/a.py:10-12"`` -> ``(10, 12)`` when it points into ``path``."""
41
+ if not location:
42
+ return None
43
+ match = _LOCATION.match(location)
44
+ if match is None or match["path"] != path:
45
+ return None
46
+ start = int(match["start"])
47
+ end = int(match["end"]) if match["end"] else start
48
+ return (start, max(start, end))
49
+
50
+
51
+ def _side(weight: float, strength: float) -> Side:
52
+ if weight == 0 or strength == 0:
53
+ return "context"
54
+ return "for" if weight * strength > 0 else "against"
55
+
56
+
57
+ def marks_for(score: FileScore, methodology: Methodology) -> list[ExcerptMark]:
58
+ """Every located piece of evidence in one file: the judge's quotes and the signals'."""
59
+ marks: list[ExcerptMark] = []
60
+ if score.judge is not None:
61
+ sides: list[tuple[Side, list[QuotedEvidence]]] = [
62
+ ("for", score.judge.evidence_for), ("against", score.judge.evidence_against),
63
+ ] # fmt: skip
64
+ for side, quotes in sides:
65
+ for q in quotes:
66
+ marks.append(ExcerptMark(
67
+ line_start=q.line_start, line_end=max(q.line_start, q.line_end),
68
+ side=side, source="judge", note=q.why[:MAX_NOTE_CHARS],
69
+ )) # fmt: skip
70
+ weights = methodology.file_weights
71
+ for hit in score.signals:
72
+ side = _side(weights.get(hit.family, 0.0), hit.strength)
73
+ for ev in hit.evidence:
74
+ span = parse_location(ev.location, score.path)
75
+ if span is not None:
76
+ marks.append(ExcerptMark(
77
+ line_start=span[0], line_end=span[1], side=side,
78
+ source=hit.signal_id, note=ev.detail[:MAX_NOTE_CHARS],
79
+ )) # fmt: skip
80
+ return sorted(marks, key=lambda m: (m.line_start, m.line_end))
81
+
82
+
83
+ def _hunk_ranges(marks: list[ExcerptMark], n_lines: int) -> list[tuple[int, int]]:
84
+ ranges: list[tuple[int, int]] = []
85
+ for m in marks:
86
+ start = max(1, m.line_start - CONTEXT_LINES)
87
+ end = min(n_lines, m.line_end + CONTEXT_LINES)
88
+ if start > end:
89
+ continue
90
+ if ranges and start <= ranges[-1][1] + MERGE_GAP:
91
+ ranges[-1] = (ranges[-1][0], max(ranges[-1][1], end))
92
+ else:
93
+ ranges.append((start, end))
94
+ return ranges
95
+
96
+
97
+ def build_excerpt(path: str, text: str, marks: list[ExcerptMark], budget: int) -> Excerpt | None:
98
+ """The hunks of ``text`` around ``marks``, within ``budget`` lines (and the per-file cap)."""
99
+ lines = text.splitlines()
100
+ marks = [m for m in marks if m.line_start <= len(lines)]
101
+ if not marks:
102
+ return None
103
+ limit = min(budget, MAX_LINES_PER_FILE)
104
+ hunks: list[ExcerptHunk] = []
105
+ used = 0
106
+ truncated = False
107
+ for start, end in _hunk_ranges(marks, len(lines)):
108
+ size = end - start + 1
109
+ if used + size > limit:
110
+ truncated = True
111
+ if used == 0: # always show the start of the first hunk
112
+ end = start + limit - 1
113
+ size = limit
114
+ else:
115
+ break
116
+ hunks.append(ExcerptHunk(
117
+ start_line=start,
118
+ lines=[line[:MAX_LINE_CHARS] for line in lines[start - 1 : end]],
119
+ )) # fmt: skip
120
+ used += size
121
+ if truncated:
122
+ break
123
+ shown = [(h.start_line, h.start_line + len(h.lines) - 1) for h in hunks]
124
+ kept = [m for m in marks if any(a <= m.line_start <= b for a, b in shown)]
125
+ truncated = truncated or len(kept) < len(marks)
126
+ return Excerpt(path=path, hunks=hunks, marks=kept, truncated=truncated)
127
+
128
+
129
+ def build_excerpts(
130
+ files: list[FileScore], methodology: Methodology, read: Callable[[str], str]
131
+ ) -> list[Excerpt]:
132
+ """Excerpts for the files the judge read, then the files with the most located evidence."""
133
+ candidates = [(f, marks_for(f, methodology)) for f in files]
134
+ candidates = [(f, m) for f, m in candidates if m]
135
+ candidates.sort(key=lambda c: (c[0].judge is None, -c[0].probability))
136
+ excerpts: list[Excerpt] = []
137
+ budget = MAX_LINES_TOTAL
138
+ for score, marks in candidates[:MAX_EXCERPT_FILES]:
139
+ if budget <= 0:
140
+ break
141
+ try:
142
+ text = read(score.path)
143
+ except OSError:
144
+ continue
145
+ excerpt = build_excerpt(score.path, text, marks, budget)
146
+ if excerpt is not None:
147
+ excerpts.append(excerpt)
148
+ budget -= sum(len(h.lines) for h in excerpt.hunks)
149
+ return excerpts
150
+
151
+
152
+ def commit_summaries(
153
+ commits: list[GitCommit],
154
+ changed: dict[str, list[str]],
155
+ markers: MarkerSet,
156
+ large_commit_files: int,
157
+ ) -> list[CommitSummary]:
158
+ """The newest commits (git order), with marker tools and a large-commit flag."""
159
+ result = []
160
+ for c in commits[:MAX_COMMITS_REPORTED]:
161
+ n_files = len(changed.get(c.sha, []))
162
+ merge = len(c.parents) > 1
163
+ result.append(CommitSummary(
164
+ sha=c.sha, date=c.authored_at, subject=c.subject[:MAX_SUBJECT_CHARS],
165
+ files_changed=n_files, merge=merge,
166
+ tools=sorted({tool for _, tool in commit_marker_tools(c, markers)}),
167
+ large=not merge and n_files >= large_commit_files,
168
+ )) # fmt: skip
169
+ return result
170
+
171
+
172
+ def unscored(entries: Iterable[tuple[str, str]]) -> tuple[list[UnscoredFile], bool]:
173
+ """``(path, reason)`` pairs as models, capped; the flag says whether some were dropped."""
174
+ files: list[UnscoredFile] = []
175
+ for path, reason in entries:
176
+ if len(files) == MAX_UNSCORED:
177
+ return files, True
178
+ files.append(UnscoredFile(path=path, reason=reason))
179
+ return files, False
@@ -0,0 +1,7 @@
1
+ """Signals: small, versioned pieces of evidence for or against AI authorship."""
2
+
3
+ from ai_code_detector.signals.base import FileSignal, RepoContext, RepoSignal
4
+ from ai_code_detector.signals.file import FILE_SIGNALS
5
+ from ai_code_detector.signals.repo import REPO_SIGNALS
6
+
7
+ __all__ = ["FILE_SIGNALS", "REPO_SIGNALS", "FileSignal", "RepoContext", "RepoSignal"]
@@ -0,0 +1,64 @@
1
+ """Signal interfaces and the context they read from."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from typing import ClassVar
8
+
9
+ from margin_core import Evidence
10
+ from margin_core.loaders import GitCommit, Workspace
11
+
12
+ from ai_code_detector.methodology import Methodology
13
+ from ai_code_detector.models import SignalHit
14
+ from ai_code_detector.source import SourceFile
15
+
16
+
17
+ @dataclass
18
+ class RepoContext:
19
+ workspace: Workspace
20
+ methodology: Methodology
21
+ commits: list[GitCommit] = field(default_factory=list) # newest first, scoped to the target
22
+ changed_files: dict[str, list[str]] = field(default_factory=dict) # sha -> workspace paths
23
+ history_truncated: bool = False
24
+
25
+
26
+ class _Signal(ABC):
27
+ id: ClassVar[str]
28
+ version: ClassVar[str]
29
+ family: ClassVar[str]
30
+
31
+ def hit(self, strength: float, explanation: str, evidence: list[Evidence]) -> SignalHit:
32
+ return SignalHit(
33
+ signal_id=self.id,
34
+ signal_version=self.version,
35
+ family=self.family,
36
+ strength=max(-1.0, min(1.0, round(strength, 4))),
37
+ explanation=explanation,
38
+ evidence=evidence,
39
+ )
40
+
41
+
42
+ class RepoSignal(_Signal):
43
+ """Looks at the repository as a whole (history, README)."""
44
+
45
+ @abstractmethod
46
+ def evaluate(self, ctx: RepoContext) -> list[SignalHit]: ...
47
+
48
+
49
+ class FileSignal(_Signal):
50
+ """Looks at one parsed source file (any supported language)."""
51
+
52
+ @abstractmethod
53
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]: ...
54
+
55
+
56
+ def clamp01(value: float) -> float:
57
+ return max(0.0, min(1.0, value))
58
+
59
+
60
+ def ramp(value: float, low: float, high: float) -> float:
61
+ """0 at or below ``low``, 1 at or above ``high``, linear in between."""
62
+ if high <= low:
63
+ return 1.0 if value >= high else 0.0
64
+ return clamp01((value - low) / (high - low))
@@ -0,0 +1,277 @@
1
+ """File-level signals. They read a language-neutral :class:`SourceFile` (Python, JS, TS)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from margin_core import Evidence
8
+
9
+ from ai_code_detector.methodology import Methodology
10
+ from ai_code_detector.models import SignalHit
11
+ from ai_code_detector.signals.base import FileSignal, ramp
12
+ from ai_code_detector.source import SourceFile, split_words
13
+
14
+ _STOPWORDS = {
15
+ "the", "a", "an", "to", "of", "and", "or", "for", "in", "on", "with", "is", "are", "be",
16
+ "this", "that", "it", "its", "we", "if", "then", "else", "from", "by", "as", "at", "into",
17
+ "all", "each", "our", "now", "here", "will", "should", "can", "using", "use",
18
+ } # fmt: skip
19
+ _GENERIC_NAMES = {
20
+ "data", "result", "results", "output", "value", "values", "item", "items", "info", "response",
21
+ "temp", "obj", "element", "elements", "input_data", "output_data", "processed_data",
22
+ "result_list", "final_result", "user_input", "my_list", "my_dict", "data_list", "data_dict",
23
+ "result_dict", "output_list", "input_value", "return_value", "new_list", "filtered_data",
24
+ "result_array", "data_array", "response_data", "result_data", "item_list",
25
+ } # fmt: skip
26
+ _GENERIC_FUNCTION = re.compile(r"^(process|handle|perform|execute|manage)_")
27
+ _SHORT_OK = {"i", "j", "k", "x", "y", "z", "_", "n", "e", "f"}
28
+ _TODO = re.compile(r"\b(TODO|FIXME|XXX|HACK)\b")
29
+ _TODO_PERSONAL = re.compile(r"\b(TODO|FIXME|XXX|HACK)\s*\(\s*\w+|\b(19|20)\d\d\b|\b[A-Z]{2,3}:")
30
+ _INFORMAL = re.compile(
31
+ r"\b(hacky?|ugly|lol|wtf|dunno|kinda|gonna|idk|meh|yikes|crap|damn|oops|sorry|"
32
+ r"magic number|no idea|why does this work|don't ask)\b",
33
+ re.IGNORECASE,
34
+ )
35
+
36
+
37
+ def _location(source: SourceFile, line: int, end: int | None = None) -> str:
38
+ return f"{source.path}:{line}" + (f"-{end}" if end and end != line else "")
39
+
40
+
41
+ def _snake(name: str) -> str:
42
+ """``processData`` and ``process_data`` both become ``process_data``."""
43
+ return "_".join(split_words(name))
44
+
45
+
46
+ class CommentDensity(FileSignal):
47
+ """Many comments and docstrings, especially on trivial functions, are typical of AI code."""
48
+
49
+ id = "comment_density"
50
+ version = "2" # v2: counts comment lines (block comments span lines); JSDoc = docstring
51
+ family = "comments"
52
+
53
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]:
54
+ t = methodology.thresholds_for(self.id)
55
+ comment_lines = source.own_line_comment_lines
56
+ density = (comment_lines + source.docstring_lines) / max(source.code_lines, 1)
57
+ trivial = [f for f in source.functions if f.statements <= t["trivial_max_statements"]]
58
+ documented = [f for f in trivial if f.has_docstring]
59
+
60
+ density_part = ramp(density, t["density_low"], t["density_high"])
61
+ trivial_part = 0.0
62
+ if len(trivial) >= t["trivial_min_count"]:
63
+ trivial_part = ramp(len(documented) / len(trivial), t["trivial_ratio_low"], 1.0)
64
+
65
+ if density_part or trivial_part:
66
+ strength = min(1.0, 0.6 * density_part + 0.6 * trivial_part)
67
+ parts = []
68
+ if density_part:
69
+ parts.append(f"{density:.0%} comment and docstring lines per code line")
70
+ if trivial_part:
71
+ parts.append(
72
+ f"{len(documented)} of {len(trivial)} trivial functions have docstrings"
73
+ )
74
+ evidence = [
75
+ Evidence(kind="file", location=_location(source, f.line, f.end_line),
76
+ detail=f"docstring on trivial function '{f.name}'")
77
+ for f in documented[:3]
78
+ ] or [Evidence(kind="file", location=source.path, detail=parts[0])] # fmt: skip
79
+ return [self.hit(strength, "Heavy commenting: " + "; ".join(parts) + ".", evidence)]
80
+
81
+ if density < t["sparse_density"] and source.code_lines >= t["sparse_min_code_lines"]:
82
+ return [
83
+ self.hit(
84
+ t["sparse_strength"],
85
+ f"Almost no comments ({comment_lines} lines for {source.code_lines} code "
86
+ "lines).",
87
+ [Evidence(kind="file", location=source.path, detail="sparse comments")],
88
+ )
89
+ ]
90
+ return []
91
+
92
+
93
+ class RestatingComments(FileSignal):
94
+ """Comments that only repeat the code next to them (``# increment counter``)."""
95
+
96
+ id = "restating_comments"
97
+ version = "1"
98
+ family = "comments"
99
+
100
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]:
101
+ t = methodology.thresholds_for(self.id)
102
+ eligible = 0
103
+ restating: list[tuple[int, str]] = []
104
+ marker = "#" if source.language == "python" else "//"
105
+ for comment in source.comments:
106
+ words = [w for w in split_words(comment.text) if w not in _STOPWORDS and len(w) > 1]
107
+ if not (t["min_words"] <= len(words) <= t["max_words"]) or _TODO.search(comment.text):
108
+ continue
109
+ target = comment.line if not comment.own_line else source.next_code_line(comment.line)
110
+ if target is None or target > len(source.lines):
111
+ continue
112
+ code = source.lines[target - 1]
113
+ if not comment.own_line:
114
+ code = code.split(marker, 1)[0]
115
+ code_words = set(split_words(code))
116
+ if not code_words:
117
+ continue
118
+ eligible += 1
119
+ overlap = sum(1 for w in words if w in code_words or w.rstrip("s") in code_words)
120
+ if overlap / len(words) >= t["min_overlap"]:
121
+ restating.append((comment.line, comment.text))
122
+
123
+ if len(restating) < t["min_count"] or not eligible:
124
+ return []
125
+ ratio = len(restating) / eligible
126
+ if ratio < t["min_ratio"]:
127
+ return []
128
+ return [
129
+ self.hit(
130
+ min(1.0, 0.3 + ratio),
131
+ f"{len(restating)} of {eligible} comments only restate the code next to them.",
132
+ [
133
+ Evidence(
134
+ kind="file",
135
+ location=_location(source, line),
136
+ detail=f"{marker} {text[:80]}",
137
+ )
138
+ for line, text in restating[:3]
139
+ ],
140
+ ) # fmt: skip
141
+ ]
142
+
143
+
144
+ class NamingPatterns(FileSignal):
145
+ """Long, generic, uniformly descriptive names lean AI; terse abbreviations lean human."""
146
+
147
+ id = "naming_patterns"
148
+ version = "2" # v2: camelCase names are compared in snake_case form
149
+ family = "naming"
150
+
151
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]:
152
+ t = methodology.thresholds_for(self.id)
153
+ names = {n for n in source.identifiers if not n.startswith("__")}
154
+ if len(names) < t["min_identifiers"]:
155
+ return []
156
+ generic = sorted(
157
+ n for n in names if _snake(n) in _GENERIC_NAMES or _GENERIC_FUNCTION.match(_snake(n))
158
+ )
159
+ considered = [n for n in names if n not in _SHORT_OK]
160
+ if not considered:
161
+ return []
162
+ avg_len = sum(len(n) for n in considered) / len(considered)
163
+ short = [n for n in considered if len(n.strip("_$")) <= 2]
164
+ generic_ratio = len(generic) / len(names)
165
+ short_ratio = len(short) / len(considered)
166
+
167
+ if generic_ratio >= t["generic_ratio"] and avg_len >= t["min_avg_length"]:
168
+ return [
169
+ self.hit(
170
+ 0.3 + 0.3 * ramp(generic_ratio, t["generic_ratio"], 0.4),
171
+ f"Generic descriptive names ({', '.join(generic[:5])}) and long identifiers "
172
+ f"(average {avg_len:.1f} characters).",
173
+ [Evidence(kind="file", location=source.path, detail=", ".join(generic[:8]))],
174
+ )
175
+ ]
176
+ if short_ratio >= t["short_ratio"]:
177
+ shown = ", ".join(sorted(short)[:5])
178
+ return [
179
+ self.hit(
180
+ -0.3,
181
+ f"Terse abbreviated names ({shown}), a habit of people more than of AI tools.",
182
+ [
183
+ Evidence(
184
+ kind="file", location=source.path, detail=", ".join(sorted(short)[:8])
185
+ )
186
+ ],
187
+ )
188
+ ]
189
+ return []
190
+
191
+
192
+ class Idiosyncrasy(FileSignal):
193
+ """Personal TODOs, informal remarks and inconsistent style: human fingerprints."""
194
+
195
+ id = "idiosyncrasy"
196
+ version = "1"
197
+ family = "human_traces"
198
+
199
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]:
200
+ t = methodology.thresholds_for(self.id)
201
+ found: list[tuple[int, str]] = []
202
+ for comment in source.comments:
203
+ if _TODO.search(comment.text) and _TODO_PERSONAL.search(comment.text):
204
+ found.append((comment.line, f"personal note: {comment.text[:70]}"))
205
+ elif _INFORMAL.search(comment.text):
206
+ found.append((comment.line, f"informal remark: {comment.text[:70]}"))
207
+ strength = t["per_marker"] * len(found)
208
+ parts = [f"{len(found)} personal or informal comments"] if found else []
209
+
210
+ singles, doubles = source.quote_styles.get("'", 0), source.quote_styles.get('"', 0)
211
+ total = singles + doubles
212
+ if (
213
+ total >= t["quote_min_strings"]
214
+ and min(singles, doubles) / total >= t["quote_min_minority"]
215
+ ):
216
+ strength += t["quote_strength"]
217
+ parts.append(f"mixed quote styles ({singles} single, {doubles} double)")
218
+ if not parts:
219
+ return []
220
+ evidence = [
221
+ Evidence(kind="file", location=_location(source, line), detail=text)
222
+ for line, text in found[:3]
223
+ ] or [Evidence(kind="file", location=source.path, detail=parts[-1])]
224
+ return [
225
+ self.hit(
226
+ -min(t["max_strength"], strength),
227
+ "Human fingerprints: " + "; ".join(parts) + ".",
228
+ evidence,
229
+ )
230
+ ]
231
+
232
+
233
+ class DeadOrDebugCode(FileSignal):
234
+ """Commented-out code and leftover debugging are rare in freshly generated code."""
235
+
236
+ id = "dead_or_debug_code"
237
+ version = "1"
238
+ family = "human_traces"
239
+
240
+ def evaluate(self, source: SourceFile, methodology: Methodology) -> list[SignalHit]:
241
+ t = methodology.thresholds_for(self.id)
242
+ blocks: list[int] = []
243
+ previous = -2
244
+ for line in sorted(source.commented_code_lines):
245
+ if line != previous + 1:
246
+ blocks.append(line)
247
+ previous = line
248
+ debug = source.debug_statements
249
+ if not blocks and not debug:
250
+ return []
251
+ strength = t["per_block"] * len(blocks) + t["per_debug"] * len(debug)
252
+ parts = []
253
+ if blocks:
254
+ parts.append(f"{len(blocks)} blocks of commented-out code")
255
+ if debug:
256
+ parts.append(f"{len(debug)} leftover debugging statements")
257
+ evidence = [
258
+ Evidence(kind="file", location=_location(source, line), detail="commented-out code")
259
+ for line in blocks[:2]
260
+ ] + [Evidence(kind="file", location=_location(source, line), detail=text)
261
+ for line, text in debug[:2]] # fmt: skip
262
+ return [
263
+ self.hit(
264
+ -min(t["max_strength"], strength),
265
+ "Work-in-progress traces: " + "; ".join(parts) + ".",
266
+ evidence,
267
+ )
268
+ ]
269
+
270
+
271
+ FILE_SIGNALS: tuple[FileSignal, ...] = (
272
+ CommentDensity(),
273
+ RestatingComments(),
274
+ NamingPatterns(),
275
+ Idiosyncrasy(),
276
+ DeadOrDebugCode(),
277
+ )