margin-ai-code-detector 0.2.0__tar.gz

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.
Files changed (67) hide show
  1. margin_ai_code_detector-0.2.0/.gitignore +80 -0
  2. margin_ai_code_detector-0.2.0/CHANGELOG.md +37 -0
  3. margin_ai_code_detector-0.2.0/LICENSE +21 -0
  4. margin_ai_code_detector-0.2.0/PKG-INFO +137 -0
  5. margin_ai_code_detector-0.2.0/README.md +110 -0
  6. margin_ai_code_detector-0.2.0/eval/dataset.py +115 -0
  7. margin_ai_code_detector-0.2.0/eval/datasets/v0/README.md +71 -0
  8. margin_ai_code_detector-0.2.0/eval/datasets/v0/manifest.jsonl +20 -0
  9. margin_ai_code_detector-0.2.0/eval/datasets/v1/README.md +81 -0
  10. margin_ai_code_detector-0.2.0/eval/datasets/v1/build.py +120 -0
  11. margin_ai_code_detector-0.2.0/eval/datasets/v1/manifest.jsonl +71 -0
  12. margin_ai_code_detector-0.2.0/eval/datasets/v1/sources/ai_javascript.json +265 -0
  13. margin_ai_code_detector-0.2.0/eval/datasets/v1/sources/ai_python.json +150 -0
  14. margin_ai_code_detector-0.2.0/eval/datasets/v1/sources/human_javascript_pre2021.jsonl +10 -0
  15. margin_ai_code_detector-0.2.0/eval/datasets/v1/sources/human_python_gentoo_post2023.jsonl +5 -0
  16. margin_ai_code_detector-0.2.0/eval/datasets/v1/sources/human_python_pre2021.jsonl +10 -0
  17. margin_ai_code_detector-0.2.0/eval/fit.py +270 -0
  18. margin_ai_code_detector-0.2.0/eval/metrics.py +64 -0
  19. margin_ai_code_detector-0.2.0/eval/results/judge_comparison_train.json +1206 -0
  20. margin_ai_code_detector-0.2.0/eval/results/judge_comparison_train_v2.json +905 -0
  21. margin_ai_code_detector-0.2.0/eval/results/v0.json +5005 -0
  22. margin_ai_code_detector-0.2.0/eval/results/v1_dev_judge_qwen3.5-9b.json +67116 -0
  23. margin_ai_code_detector-0.2.0/eval/results/v1_dev_methodology_v0.json +66993 -0
  24. margin_ai_code_detector-0.2.0/eval/results/v1_final_methodology-v1_judge-qwen3.5-9b.json +77095 -0
  25. margin_ai_code_detector-0.2.0/eval/results/v1_final_methodology-v1_signals-only.json +77087 -0
  26. margin_ai_code_detector-0.2.0/eval/run.py +249 -0
  27. margin_ai_code_detector-0.2.0/eval/tools/compare_judges.py +140 -0
  28. margin_ai_code_detector-0.2.0/eval/tools/find_ai_candidates.py +180 -0
  29. margin_ai_code_detector-0.2.0/eval/tools/pin_before.py +74 -0
  30. margin_ai_code_detector-0.2.0/pyproject.toml +50 -0
  31. margin_ai_code_detector-0.2.0/src/ai_code_detector/__init__.py +15 -0
  32. margin_ai_code_detector-0.2.0/src/ai_code_detector/agent.py +56 -0
  33. margin_ai_code_detector-0.2.0/src/ai_code_detector/aggregate.py +183 -0
  34. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/__init__.py +1 -0
  35. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/llm_judge.py +358 -0
  36. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/prompts/__init__.py +1 -0
  37. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/prompts/judge_v1.md +28 -0
  38. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/prompts/judge_v2.md +28 -0
  39. margin_ai_code_detector-0.2.0/src/ai_code_detector/judge/sampler.py +40 -0
  40. margin_ai_code_detector-0.2.0/src/ai_code_detector/markers/__init__.py +108 -0
  41. margin_ai_code_detector-0.2.0/src/ai_code_detector/markers/v1.toml +98 -0
  42. margin_ai_code_detector-0.2.0/src/ai_code_detector/methodology/__init__.py +71 -0
  43. margin_ai_code_detector-0.2.0/src/ai_code_detector/methodology/v0.toml +119 -0
  44. margin_ai_code_detector-0.2.0/src/ai_code_detector/methodology/v1.toml +141 -0
  45. margin_ai_code_detector-0.2.0/src/ai_code_detector/models.py +197 -0
  46. margin_ai_code_detector-0.2.0/src/ai_code_detector/pipeline.py +457 -0
  47. margin_ai_code_detector-0.2.0/src/ai_code_detector/py.typed +1 -0
  48. margin_ai_code_detector-0.2.0/src/ai_code_detector/report.py +179 -0
  49. margin_ai_code_detector-0.2.0/src/ai_code_detector/signals/__init__.py +7 -0
  50. margin_ai_code_detector-0.2.0/src/ai_code_detector/signals/base.py +64 -0
  51. margin_ai_code_detector-0.2.0/src/ai_code_detector/signals/file.py +277 -0
  52. margin_ai_code_detector-0.2.0/src/ai_code_detector/signals/repo.py +183 -0
  53. margin_ai_code_detector-0.2.0/src/ai_code_detector/source/__init__.py +95 -0
  54. margin_ai_code_detector-0.2.0/src/ai_code_detector/source/javascript.py +227 -0
  55. margin_ai_code_detector-0.2.0/src/ai_code_detector/source/python.py +129 -0
  56. margin_ai_code_detector-0.2.0/tests/conftest.py +111 -0
  57. margin_ai_code_detector-0.2.0/tests/fixtures/ai_style.py.txt +59 -0
  58. margin_ai_code_detector-0.2.0/tests/fixtures/ai_style.ts.txt +58 -0
  59. margin_ai_code_detector-0.2.0/tests/fixtures/human_style.js.txt +31 -0
  60. margin_ai_code_detector-0.2.0/tests/fixtures/human_style.py.txt +35 -0
  61. margin_ai_code_detector-0.2.0/tests/test_aggregate.py +119 -0
  62. margin_ai_code_detector-0.2.0/tests/test_detector.py +173 -0
  63. margin_ai_code_detector-0.2.0/tests/test_eval.py +92 -0
  64. margin_ai_code_detector-0.2.0/tests/test_judge.py +256 -0
  65. margin_ai_code_detector-0.2.0/tests/test_markers.py +109 -0
  66. margin_ai_code_detector-0.2.0/tests/test_report.py +145 -0
  67. margin_ai_code_detector-0.2.0/tests/test_signals.py +142 -0
@@ -0,0 +1,80 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ /lib/
14
+ /lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ share/python-wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+
24
+ # Virtual environments
25
+ .venv/
26
+ venv/
27
+ ENV/
28
+ env/
29
+
30
+ # uv
31
+ .uv/
32
+
33
+ # Environment variables & secrets
34
+ .env
35
+ .env.local
36
+ .env.*.local
37
+ *.key
38
+ *.pem
39
+
40
+ # Testing & Coverage
41
+ .pytest_cache/
42
+ .coverage
43
+ .coverage.*
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+
51
+ # Type checking & linting
52
+ .mypy_cache/
53
+ .ruff_cache/
54
+ .dmypy.json
55
+ dmypy.json
56
+
57
+ # IDEs & Editors
58
+ .vscode/
59
+ .idea/
60
+ *.swp
61
+ *.swo
62
+ *~
63
+
64
+ # Operating System
65
+ .DS_Store
66
+ Thumbs.db
67
+ ehthumbs.db
68
+ desktop.ini
69
+
70
+ # Output / Reports
71
+ report.json
72
+ report.md
73
+ temp/
74
+ tmp/
75
+
76
+ # Private planning notes (kept locally, not published)
77
+ PLAN.md
78
+
79
+ # the web UI bundled into margin-api at release time (scripts/build_release.py)
80
+ packages/api/src/margin_api/ui/
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this agent are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.2.0] - 2026-10-21
8
+
9
+ The first published version.
10
+
11
+ ### Added
12
+ - Reads Python, JavaScript and TypeScript, and the repository's git history.
13
+ - A local model judges a sample of files and points at the lines behind its view, for and
14
+ against. The quotes in the report are taken from the file, not from the model, and the code
15
+ it reads is fenced off so instructions hidden in a repository can't steer it.
16
+ - Methodology v1: the judge's verdicts and the file-level checks are combined with weights
17
+ fitted on 44 repositories. Commit history and README style are shown for context but not
18
+ scored, because in testing they separated old projects from new ones rather than people
19
+ from AI.
20
+ - Traces left by AI tools (config files such as `CLAUDE.md`, co-author trailers, bot authors)
21
+ for nine tools, each checked against a real commit. They're reported on their own and
22
+ never change the estimate.
23
+ - An estimate with a range and a confidence level, the evidence on both sides, a score per
24
+ file, code excerpts around the evidence, and a commit history without author names.
25
+ - Without a model it still runs on the file checks alone, and says the confidence is low.
26
+
27
+ ### Known limitations
28
+ - The scores aren't calibrated yet, so confidence never goes above medium.
29
+ - Tuned to avoid false accusations: at a setting that keeps false positives at 5% or less,
30
+ it misses most AI-written repositories.
31
+ - Repositories with big generated-looking data files, such as locale tables, can score high.
32
+ - Not yet tested on code written with light AI help, or on AI code that people edited.
33
+
34
+ ## [0.1.0] - not published
35
+
36
+ A development version with file checks only (methodology v0), used to build the evaluation
37
+ data. Never released.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 margin contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: margin-ai-code-detector
3
+ Version: 0.2.0
4
+ Summary: Estimates how likely a codebase was written with AI assistance, as a range with the evidence for and against.
5
+ Project-URL: Homepage, https://github.com/Waddah0-0/margin
6
+ Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/agents/ai_code_detector
7
+ Project-URL: Issues, https://github.com/Waddah0-0/margin/issues
8
+ Project-URL: Changelog, https://github.com/Waddah0-0/margin/blob/main/agents/ai_code_detector/CHANGELOG.md
9
+ Author: Waddah Ali
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,ai-detection,code-analysis,llm
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: margin-core<0.2,>=0.1.0
23
+ Requires-Dist: tree-sitter-javascript>=0.23
24
+ Requires-Dist: tree-sitter-typescript>=0.23
25
+ Requires-Dist: tree-sitter<0.26,>=0.24
26
+ Description-Content-Type: text/markdown
27
+
28
+ # AI Code Detector
29
+
30
+ Estimates how likely it is that a repository, or parts of it, was written with AI
31
+ assistance, and always shows the reasons behind the estimate.
32
+
33
+ > **Status: experimental.** Methodology v1 combines heuristic signals with a local LLM judge,
34
+ > with weights fitted on 44 repositories. On 13 held-out repositories it ranked every AI
35
+ > repository it scored above 0.5 higher than every human one (AUC 1.00, no false positives
36
+ > at 0.5), but that test set is small and the scores are not calibrated, so confidence never
37
+ > goes above medium. Without a model it falls back to much weaker signals (test AUC 0.79,
38
+ > 29% false positives). Read [how it scores](https://github.com/Waddah0-0/margin/blob/main/docs/methodology.md)
39
+ > before relying on any number.
40
+
41
+ ## What it does
42
+
43
+ Given a GitHub repository URL or a local path, the detector looks for evidence of AI
44
+ assistance in the code and its history. It returns a range with a confidence level, plus
45
+ the evidence for and against, so a person can judge the result for themselves.
46
+
47
+ ## How it works
48
+
49
+ It combines two kinds of evidence. The first is a set of quick checks on the repository
50
+ itself, such as:
51
+
52
+ - config files left behind by AI coding tools, such as `CLAUDE.md`, `.cursorrules` or
53
+ `.github/copilot-instructions.md`;
54
+ - `Co-authored-by` trailers that name an AI assistant;
55
+ - a whole project arriving in a single commit;
56
+ - comments that only restate the line below them.
57
+
58
+ Some signals point the other way: a long, messy history, personal TODOs and leftover debug
59
+ code are all evidence of human authorship, and they count too.
60
+
61
+ The second is a language model acting as a judge. A local model (`qwen3.5:9b` through Ollama
62
+ by default) reads up to 20 files, points at the lines behind its opinion, and lists what
63
+ argues against it. The quotes in the report come from the file, so evidence cannot be invented.
64
+ It never sees the signal scores. It runs automatically when a model is available, because in
65
+ evaluation it was the only evidence that worked on recent code.
66
+
67
+ The two are combined into one estimate for the repository, with weights fitted on data.
68
+ Commit history and README style are shown as context but not scored: in evaluation they
69
+ told old projects from new ones, not people from AI.
70
+
71
+ ## Input
72
+
73
+ | Field | Default | Meaning |
74
+ |---|---|---|
75
+ | `target` | required | GitHub URL (`https://github.com/<owner>/<repo>`) or local path. The primary input. |
76
+ | `paths` | all files | Restrict the analysis to these files or folders. |
77
+ | `branch` | default branch | Branch to analyse (GitHub only). |
78
+ | `use_llm_judge` | when a model is available | Ask a model to judge a sample of files. `false` skips it (weak, low confidence); `true` requires it. |
79
+ | `include_tests` | off | Score test files too (they are reported separately). |
80
+
81
+ `margin info ai-code-detector` shows the rest, including the judge's limits on files, time
82
+ and cost.
83
+
84
+ ## Output
85
+
86
+ The headline is an estimate with a range and a confidence level, for example "0.55 to 0.80,
87
+ medium confidence", never a bare percentage. When confidence is low, the report says why:
88
+ few signals fired, few files could be read, or the evidence pulled both ways.
89
+
90
+ If the repository's own metadata names an AI tool (a `Co-authored-by` trailer, say), the
91
+ report says so separately. That proves the tool was used, not how much of the code it wrote,
92
+ so it doesn't move the estimate.
93
+
94
+ Then comes the evidence: what points toward AI and what points toward a person, each item
95
+ tied to a file, a line range or a commit. Every file gets its own score with the signals that
96
+ fired and, if the judge read it, the lines it quoted. The report also includes short excerpts
97
+ of the code around each marked line (at most 80 lines per file and 800 overall), so you can
98
+ check it without opening the repository.
99
+
100
+ Finally there's the history: each commit's date, subject, the number of files it touched,
101
+ any AI tool it names, and whether it was unusually large. Author names are left out on
102
+ purpose. The report is about code, not about people. It also lists every file that wasn't
103
+ scored and why (another language, a test file, too small, a lockfile and so on).
104
+
105
+ ## Limits
106
+
107
+ No tool can prove that code was written by AI. Clean human code can look machine-made, and
108
+ edited AI code can look human. The detector is tuned to avoid false accusations, even if
109
+ that means it misses some AI-written code.
110
+
111
+ It reads Python, JavaScript and TypeScript; other languages lower the confidence. Projects
112
+ with large generated-looking data files (such as locale tables) can score high. It has not
113
+ been tested on code written with light AI help or on AI code edited by people.
114
+
115
+ Use it to inform a conversation. It must not be the sole basis for accusing a student,
116
+ a contractor or a job candidate.
117
+
118
+ ## Usage
119
+
120
+ ```bash
121
+ margin run ai-code-detector https://github.com/owner/repo --format markdown
122
+ margin run ai-code-detector ./path/to/project --format json --out report.json
123
+ ```
124
+
125
+ ## Development
126
+
127
+ This agent lives in the [margin](https://github.com/Waddah0-0/margin) monorepo, in
128
+ [`agents/ai_code_detector`](https://github.com/Waddah0-0/margin/tree/main/agents/ai_code_detector).
129
+ It is mirrored, read-only, to
130
+ [Waddah0-0/margin-ai-code-detector](https://github.com/Waddah0-0/margin-ai-code-detector);
131
+ open issues and pull requests in the main repository.
132
+
133
+ The evaluation harness lives in `eval/`: `eval/run.py` scores a dataset manifest,
134
+ `eval/fit.py` fits and compares methodologies, `eval/tools/compare_judges.py` compares judge
135
+ models, and `eval/datasets/*/README.md` describe each dataset and its biases.
136
+
137
+ Run its tests with `uv run pytest agents/ai_code_detector`.
@@ -0,0 +1,110 @@
1
+ # AI Code Detector
2
+
3
+ Estimates how likely it is that a repository, or parts of it, was written with AI
4
+ assistance, and always shows the reasons behind the estimate.
5
+
6
+ > **Status: experimental.** Methodology v1 combines heuristic signals with a local LLM judge,
7
+ > with weights fitted on 44 repositories. On 13 held-out repositories it ranked every AI
8
+ > repository it scored above 0.5 higher than every human one (AUC 1.00, no false positives
9
+ > at 0.5), but that test set is small and the scores are not calibrated, so confidence never
10
+ > goes above medium. Without a model it falls back to much weaker signals (test AUC 0.79,
11
+ > 29% false positives). Read [how it scores](https://github.com/Waddah0-0/margin/blob/main/docs/methodology.md)
12
+ > before relying on any number.
13
+
14
+ ## What it does
15
+
16
+ Given a GitHub repository URL or a local path, the detector looks for evidence of AI
17
+ assistance in the code and its history. It returns a range with a confidence level, plus
18
+ the evidence for and against, so a person can judge the result for themselves.
19
+
20
+ ## How it works
21
+
22
+ It combines two kinds of evidence. The first is a set of quick checks on the repository
23
+ itself, such as:
24
+
25
+ - config files left behind by AI coding tools, such as `CLAUDE.md`, `.cursorrules` or
26
+ `.github/copilot-instructions.md`;
27
+ - `Co-authored-by` trailers that name an AI assistant;
28
+ - a whole project arriving in a single commit;
29
+ - comments that only restate the line below them.
30
+
31
+ Some signals point the other way: a long, messy history, personal TODOs and leftover debug
32
+ code are all evidence of human authorship, and they count too.
33
+
34
+ The second is a language model acting as a judge. A local model (`qwen3.5:9b` through Ollama
35
+ by default) reads up to 20 files, points at the lines behind its opinion, and lists what
36
+ argues against it. The quotes in the report come from the file, so evidence cannot be invented.
37
+ It never sees the signal scores. It runs automatically when a model is available, because in
38
+ evaluation it was the only evidence that worked on recent code.
39
+
40
+ The two are combined into one estimate for the repository, with weights fitted on data.
41
+ Commit history and README style are shown as context but not scored: in evaluation they
42
+ told old projects from new ones, not people from AI.
43
+
44
+ ## Input
45
+
46
+ | Field | Default | Meaning |
47
+ |---|---|---|
48
+ | `target` | required | GitHub URL (`https://github.com/<owner>/<repo>`) or local path. The primary input. |
49
+ | `paths` | all files | Restrict the analysis to these files or folders. |
50
+ | `branch` | default branch | Branch to analyse (GitHub only). |
51
+ | `use_llm_judge` | when a model is available | Ask a model to judge a sample of files. `false` skips it (weak, low confidence); `true` requires it. |
52
+ | `include_tests` | off | Score test files too (they are reported separately). |
53
+
54
+ `margin info ai-code-detector` shows the rest, including the judge's limits on files, time
55
+ and cost.
56
+
57
+ ## Output
58
+
59
+ The headline is an estimate with a range and a confidence level, for example "0.55 to 0.80,
60
+ medium confidence", never a bare percentage. When confidence is low, the report says why:
61
+ few signals fired, few files could be read, or the evidence pulled both ways.
62
+
63
+ If the repository's own metadata names an AI tool (a `Co-authored-by` trailer, say), the
64
+ report says so separately. That proves the tool was used, not how much of the code it wrote,
65
+ so it doesn't move the estimate.
66
+
67
+ Then comes the evidence: what points toward AI and what points toward a person, each item
68
+ tied to a file, a line range or a commit. Every file gets its own score with the signals that
69
+ fired and, if the judge read it, the lines it quoted. The report also includes short excerpts
70
+ of the code around each marked line (at most 80 lines per file and 800 overall), so you can
71
+ check it without opening the repository.
72
+
73
+ Finally there's the history: each commit's date, subject, the number of files it touched,
74
+ any AI tool it names, and whether it was unusually large. Author names are left out on
75
+ purpose. The report is about code, not about people. It also lists every file that wasn't
76
+ scored and why (another language, a test file, too small, a lockfile and so on).
77
+
78
+ ## Limits
79
+
80
+ No tool can prove that code was written by AI. Clean human code can look machine-made, and
81
+ edited AI code can look human. The detector is tuned to avoid false accusations, even if
82
+ that means it misses some AI-written code.
83
+
84
+ It reads Python, JavaScript and TypeScript; other languages lower the confidence. Projects
85
+ with large generated-looking data files (such as locale tables) can score high. It has not
86
+ been tested on code written with light AI help or on AI code edited by people.
87
+
88
+ Use it to inform a conversation. It must not be the sole basis for accusing a student,
89
+ a contractor or a job candidate.
90
+
91
+ ## Usage
92
+
93
+ ```bash
94
+ margin run ai-code-detector https://github.com/owner/repo --format markdown
95
+ margin run ai-code-detector ./path/to/project --format json --out report.json
96
+ ```
97
+
98
+ ## Development
99
+
100
+ This agent lives in the [margin](https://github.com/Waddah0-0/margin) monorepo, in
101
+ [`agents/ai_code_detector`](https://github.com/Waddah0-0/margin/tree/main/agents/ai_code_detector).
102
+ It is mirrored, read-only, to
103
+ [Waddah0-0/margin-ai-code-detector](https://github.com/Waddah0-0/margin-ai-code-detector);
104
+ open issues and pull requests in the main repository.
105
+
106
+ The evaluation harness lives in `eval/`: `eval/run.py` scores a dataset manifest,
107
+ `eval/fit.py` fits and compares methodologies, `eval/tools/compare_judges.py` compares judge
108
+ models, and `eval/datasets/*/README.md` describe each dataset and its biases.
109
+
110
+ Run its tests with `uv run pytest agents/ai_code_detector`.
@@ -0,0 +1,115 @@
1
+ """Evaluation datasets: a JSONL manifest of labelled samples, fetched into a local cache.
2
+
3
+ Third-party code is never copied into this repository. A ``git`` sample names a public GitHub
4
+ repository and an exact commit; the fetcher clones it (blobless) into the cache and checks
5
+ that commit out, so history ends exactly there. A ``local`` sample points to a folder next to
6
+ the manifest (used for small self-generated samples and for tests).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import subprocess
14
+ from pathlib import Path
15
+ from typing import Literal
16
+
17
+ from margin_core.errors import InvalidTargetError
18
+ from margin_core.loaders import parse_github_url
19
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
20
+
21
+ Label = Literal["human", "ai", "mixed"]
22
+
23
+
24
+ class Source(BaseModel):
25
+ model_config = ConfigDict(extra="forbid")
26
+
27
+ kind: Literal["git", "local"]
28
+ url: str | None = None # git: https://github.com/<owner>/<repo>
29
+ commit: str | None = None # git: full 40-character SHA
30
+ path: str | None = None # local: folder relative to the manifest; git: sub-folder to analyse
31
+
32
+ @model_validator(mode="after")
33
+ def _check(self) -> Source:
34
+ if self.kind == "git":
35
+ if not self.url or not self.commit or len(self.commit) != 40:
36
+ raise ValueError("git sources need a GitHub url and a full 40-character commit")
37
+ try:
38
+ parse_github_url(self.url)
39
+ except InvalidTargetError as exc:
40
+ raise ValueError(str(exc)) from exc
41
+ elif not self.path:
42
+ raise ValueError("local sources need a path")
43
+ return self
44
+
45
+
46
+ class Sample(BaseModel):
47
+ model_config = ConfigDict(extra="forbid")
48
+
49
+ id: str = Field(pattern=r"^[a-z0-9][a-z0-9._-]*$")
50
+ label: Label
51
+ ai_fraction: float | None = Field(default=None, ge=0.0, le=1.0)
52
+ source: Source
53
+ language: str = "python"
54
+ era: Literal["pre2021", "2021-2022", "post2023", "unknown"]
55
+ tool: str | None = None # AI tool that produced it, when known
56
+ provenance: str # how we know the label
57
+ provenance_confidence: Literal["low", "medium", "high"]
58
+ split: Literal["train", "val", "test"]
59
+
60
+ @property
61
+ def is_ai(self) -> bool:
62
+ """Positive class: AI, or mixed with at least half AI-written code."""
63
+ return self.label == "ai" or (self.label == "mixed" and (self.ai_fraction or 0) >= 0.5)
64
+
65
+
66
+ def load_manifest(path: Path) -> list[Sample]:
67
+ samples = []
68
+ for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
69
+ if line.strip() and not line.lstrip().startswith("//"):
70
+ try:
71
+ samples.append(Sample.model_validate_json(line))
72
+ except ValueError as exc:
73
+ raise ValueError(f"{path}:{number}: {exc}") from exc
74
+ ids = [s.id for s in samples]
75
+ if len(ids) != len(set(ids)):
76
+ raise ValueError(f"{path}: duplicate sample ids")
77
+ return samples
78
+
79
+
80
+ def cache_dir() -> Path:
81
+ base = os.environ.get("MARGIN_CACHE_DIR") or str(Path.home() / ".cache" / "margin")
82
+ return Path(base) / "eval"
83
+
84
+
85
+ def _git(*args: str, cwd: Path | None = None) -> None:
86
+ subprocess.run(
87
+ ["git", "-c", "advice.detachedHead=false", *args],
88
+ cwd=cwd,
89
+ check=True,
90
+ capture_output=True,
91
+ text=True,
92
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
93
+ timeout=600,
94
+ )
95
+
96
+
97
+ def fetch(sample: Sample, manifest_dir: Path, cache: Path | None = None) -> Path:
98
+ """The folder to analyse for ``sample``, cloning it first if needed."""
99
+ source = sample.source
100
+ if source.kind == "local":
101
+ assert source.path is not None
102
+ return (manifest_dir / source.path).resolve()
103
+ assert source.url is not None and source.commit is not None
104
+ target = (cache or cache_dir()) / f"{sample.id}-{source.commit[:12]}"
105
+ marker = target / ".margin-fetched"
106
+ if not marker.exists():
107
+ if target.exists():
108
+ import shutil
109
+
110
+ shutil.rmtree(target, ignore_errors=True)
111
+ target.parent.mkdir(parents=True, exist_ok=True)
112
+ _git("clone", "-q", "--filter=blob:none", "--no-checkout", "--", source.url, str(target))
113
+ _git("checkout", "-q", "--detach", source.commit, cwd=target)
114
+ marker.write_text(json.dumps({"url": source.url, "commit": source.commit}), "utf-8")
115
+ return target / source.path if source.path else target
@@ -0,0 +1,71 @@
1
+ # Evaluation dataset v0
2
+
3
+ A small first dataset for **baseline measurements only** (PLAN §9.7). It is too small and too
4
+ biased to fit or calibrate weights; that is the job of dataset v1 in phase 4.
5
+
6
+ ## Composition
7
+
8
+ 19 repositories: **12 human** and **7 AI**. The plan asked for 10 AI samples; the search
9
+ found only 7 that passed every criterion before GitHub's unauthenticated rate limit made
10
+ further searching impractical. Five of the seven were built with Claude (one also with
11
+ Codex) and two with Devin, so the AI side leans heavily on one tool family.
12
+
13
+ - **Human:** established Python projects, each pinned to its last commit before
14
+ 2021-01-01 (before AI coding assistants were available). Label `human`, era `pre2021`.
15
+ - **AI:** public Python repositories created in 2025 or later in which at least 80% of
16
+ commits carry a verified AI-tool marker (co-author trailer, "generated with" line or bot
17
+ author; see `markers/v1.toml`). Label `ai`, era `post2023`.
18
+
19
+ Every sample is a GitHub URL plus an exact commit; no third-party code is stored here. The
20
+ fetcher clones each one (blobless) into the cache directory (`MARGIN_CACHE_DIR`,
21
+ default `~/.cache/margin/eval`).
22
+
23
+ ## How the samples were chosen
24
+
25
+ - Human: `eval/tools/pin_before.py --before 2021-01-01T00:00:00Z <repos>`, over a hand-picked
26
+ list of maintained, mostly mid-sized Python projects.
27
+ - AI: `eval/tools/find_ai_candidates.py`, which searches GitHub commits for each verified
28
+ marker and keeps repositories that pass the criteria in its docstring.
29
+
30
+ Selecting AI samples by their markers does not leak the label into the score: the
31
+ detector's estimate never uses markers. It does mean every AI sample *also* has markers,
32
+ so baseline B1 (metadata only) is perfect here by construction. B1 measures nothing on v0.
33
+
34
+ ## Known biases (read before quoting any number)
35
+
36
+ 1. **Era confound.** Every human sample is from 2020 or earlier and every AI sample is from
37
+ 2025 or later. A detector could separate them by era (newer idioms, type hints, newer
38
+ libraries) rather than by authorship. v1 adds matched pairs and post-2023 human code to
39
+ measure this.
40
+ 2. **AI samples are agent-built projects with agent-made histories.** Code that a person
41
+ wrote with light AI help, or AI code that was heavily edited, is not represented.
42
+ 3. **Popular human projects.** Well-known libraries are carefully documented, which looks
43
+ "AI-like" to comment-based signals, so v0 may overstate false positives on ordinary
44
+ human code. Their code is also likely in LLM training data, which matters for the judge
45
+ in phase 4.
46
+ 4. **Tiny and unbalanced.** 19 repositories (12 human, 7 AI); two AI repositories
47
+ contribute most of the AI files. Differences of a few points in AUC are noise.
48
+ 5. **Python only**, and labels are per repository (files inherit them).
49
+ 6. **One tool family.** Most AI samples were built with Claude.
50
+
51
+ ## Baseline results (methodology v0)
52
+
53
+ Full results: `eval/results/v0.json`.
54
+
55
+ | | Repository AUC | False positives at 0.5 | At 0.6 (FPR / TPR) | Calibration error |
56
+ |---|---|---|---|---|
57
+ | B0 constant prior | 0.50 | | | |
58
+ | B1 metadata only | 1.00 (by construction, see above) | | | |
59
+ | B2 heuristic signals | 0.86 | 4 of 12 human repos (33%) | 8% / 29% | 0.17 |
60
+
61
+ File level (B2): AUC 0.64 over 1,106 files. Pre-2021 human repositories average 0.47 and
62
+ post-2023 AI repositories 0.57, a gap that may partly reflect era rather than authorship.
63
+ The weights were not tuned on this dataset, so these numbers are honest baselines.
64
+
65
+ ## Running it
66
+
67
+ ```bash
68
+ uv run python agents/ai_code_detector/eval/run.py \
69
+ --manifest agents/ai_code_detector/eval/datasets/v0/manifest.jsonl \
70
+ --out agents/ai_code_detector/eval/results/v0.json
71
+ ```
@@ -0,0 +1,20 @@
1
+ // Dataset v0: baselines only. See README.md for how samples were chosen and their biases.
2
+ {"id": "h-itsdangerous", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/pallets/itsdangerous", "commit": "5dc90166c3df22f1ce4d5d5eba0e2e7a90204382"}, "provenance": "last commit before 2021-01-01 (2020-12-01); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
3
+ {"id": "h-records", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/kennethreitz/records", "commit": "0e2d186857f16686139c20be10a1f70a689c9ea0"}, "provenance": "last commit before 2021-01-01 (2020-12-22); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
4
+ {"id": "h-boltons", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/mahmoud/boltons", "commit": "29320d636a4a0c099f948d864bcb3418f638d0d7"}, "provenance": "last commit before 2021-01-01 (2020-08-11); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
5
+ {"id": "h-blinker", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/pallets-eco/blinker", "commit": "904d8d3803e84257c08526e9047474215aa1c976"}, "provenance": "last commit before 2021-01-01 (2020-11-07); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
6
+ {"id": "h-icecream", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/gruns/icecream", "commit": "6bc358698ff5469b784d6589d09c381810368e84"}, "provenance": "last commit before 2021-01-01 (2020-11-17); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
7
+ {"id": "h-structlog", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/hynek/structlog", "commit": "ec6077a55942f207b3eb810d1e3b852bcfc5dc59"}, "provenance": "last commit before 2021-01-01 (2020-12-31); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
8
+ {"id": "h-mycli", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/dbcli/mycli", "commit": "d928c03a7ebbcc30a4ad0cc7c19718850b60a445"}, "provenance": "last commit before 2021-01-01 (2020-12-19); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
9
+ {"id": "h-tqdm", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/tqdm/tqdm", "commit": "822ca363f0b819d571d1683747c51f099bcbf31a"}, "provenance": "last commit before 2021-01-01 (2020-12-25); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
10
+ {"id": "h-python-fire", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/google/python-fire", "commit": "629d91c3f3656049f61b44b734044e51a7895619"}, "provenance": "last commit before 2021-01-01 (2020-12-17); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
11
+ {"id": "h-arrow", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/arrow-py/arrow", "commit": "2eba8b97ea323c975fb2400b041f4c17c43c9709"}, "provenance": "last commit before 2021-01-01 (2020-12-28); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
12
+ {"id": "h-inflect", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/jaraco/inflect", "commit": "2293d411cbf1aee257d1d707aca05ef856039c90"}, "provenance": "last commit before 2021-01-01 (2020-11-15); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
13
+ {"id": "h-pluginbase", "label": "human", "era": "pre2021", "source": {"kind": "git", "url": "https://github.com/mitsuhiko/pluginbase", "commit": "af0454a6f0a7cdd118e63a116a2b60efc3827c32"}, "provenance": "last commit before 2021-01-01 (2019-02-02); predates AI coding assistants", "provenance_confidence": "high", "split": "test"}
14
+ {"id": "a-civitas", "label": "ai", "era": "post2023", "tool": "Claude, Claude Code", "source": {"kind": "git", "url": "https://github.com/kamoras/civitas", "commit": "15e6a7296e3e9a7737acfaaee6f99cf0d77de8fb"}, "provenance": "82% of 980 commits carry AI-tool markers; first commit 2026-07-12", "provenance_confidence": "medium", "split": "test"}
15
+ {"id": "a-qsent", "label": "ai", "era": "post2023", "tool": "Claude, Claude Code", "source": {"kind": "git", "url": "https://github.com/AIfromScratch/qsent", "commit": "b3c198e559689dcc9e820f475224fe12ef11a401"}, "provenance": "90% of 42 commits carry AI-tool markers; first commit 2026-01-13", "provenance_confidence": "medium", "split": "test"}
16
+ {"id": "a-frago", "label": "ai", "era": "post2023", "tool": "Claude, Claude Code", "source": {"kind": "git", "url": "https://github.com/tsaijamey/frago", "commit": "a5c6ce96356d0cd41117cc1237574f61c6eafab3"}, "provenance": "86% of 1959 commits carry AI-tool markers; first commit 2025-11-15", "provenance_confidence": "medium", "split": "test"}
17
+ {"id": "a-tilmeld", "label": "ai", "era": "post2023", "tool": "Claude", "source": {"kind": "git", "url": "https://github.com/andreasdinesen/tilmeld", "commit": "649a02b47c0328edff82c01f1ea9debd62ec0a9c"}, "provenance": "100% of 82 commits carry AI-tool markers; first commit 2026-06-21", "provenance_confidence": "medium", "split": "test"}
18
+ {"id": "a-web-port", "label": "ai", "era": "post2023", "tool": "Claude, OpenAI Codex", "source": {"kind": "git", "url": "https://github.com/SomeoneIsWorking/web-port", "commit": "8c73beefc8f268c2b52686ab13c59982987fd946"}, "provenance": "86% of 28 commits carry AI-tool markers; first commit 2026-09-08", "provenance_confidence": "medium", "split": "test"}
19
+ {"id": "a-agentic-deep-research-with-token-factory-and-tavily", "label": "ai", "era": "post2023", "tool": "Devin", "source": {"kind": "git", "url": "https://github.com/SirPhlittes/Agentic-Deep-Research-with-Token-Factory-and-Tavily", "commit": "3325ea5aedfe7f66a429f465cfa93a7b601cfc11"}, "provenance": "87% of 159 commits carry AI-tool markers; first commit 2026-10-17", "provenance_confidence": "medium", "split": "test"}
20
+ {"id": "a-ledgerpilot", "label": "ai", "era": "post2023", "tool": "Devin", "source": {"kind": "git", "url": "https://github.com/taku629/ledgerpilot", "commit": "c052cb045db241d3c6cd7507605567542a7c660c"}, "provenance": "100% of 46 commits carry AI-tool markers; first commit 2026-10-18", "provenance_confidence": "medium", "split": "test"}