ProgramGen release
Browse filesCo-authored-by: tcftrees <tcftrees@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded
- README.mdAdded+142
- assets/mark.svgAdded
- programgen_harbor/__init__.pyAdded+5
- programgen_harbor/environment.pyAdded+365
- programgen_harbor/reference_client.pyAdded+676
- tasks/data/forward/0-k__netto.1b47785/environment/DockerfileAdded+26
- tasks/data/forward/0-k__netto.1b47785/environment/Dockerfile.inferenceAdded+26
- tasks/data/forward/0-k__netto.1b47785/environment/build_env.shAdded+10
- tasks/data/forward/0-k__netto.1b47785/environment/pre_cleanup.shAdded+114
- tasks/data/forward/0-k__netto.1b47785/environment/repo/.gitignoreAdded+134
- tasks/data/forward/0-k__netto.1b47785/environment/repo/.pre-commit-config.yamlAdded+12
- tasks/data/forward/0-k__netto.1b47785/environment/repo/.readthedocs.ymlAdded+18
- tasks/data/forward/0-k__netto.1b47785/environment/repo/CHANGELOG.mdAdded+217
- tasks/data/forward/0-k__netto.1b47785/environment/repo/CLAUDE.mdAdded+509
- tasks/data/forward/0-k__netto.1b47785/environment/repo/LICENSEAdded+21
- tasks/data/forward/0-k__netto.1b47785/environment/repo/MANIFEST.inAdded+3
- tasks/data/forward/0-k__netto.1b47785/environment/repo/README.mdAdded+242
- tasks/data/forward/0-k__netto.1b47785/environment/repo/RELEASE.mdAdded+214
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/README.mdAdded+299
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2018.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2019.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2020.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2021.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2022.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2023.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2024.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2025.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2026.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2027.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2028.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2029.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2030.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2031.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2032.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2018.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2019.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2020.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2021.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2022.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2023.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2024.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2025.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2026.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2027.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2028.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2029.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2030.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2031.jsonAdded+5
- tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2032.jsonAdded+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142---pretty_name: ProgramGenlanguage: - entags: - code - agents - software-engineering - harborsize_categories: - 1K<n<10Klicense: apache-2.0---
<div align="center">
<img src="assets/mark.svg" alt="ProgramGen" width="120" height="120">
<h1>ProgramGen</h1>
<b>Scalable Environment Construction for Agents That Develop Software from Scratch</b>
<a href="https://github.com/LegoX/ProgramGen">Code</a> · <a href="https://programgen-public-docs.pages.dev/">Documentation</a> · <a href="https://huggingface.co/Lego-X/ProgramGen-27B">Model</a>
</div>
> [!Note]> **Tasks and trajectories from the paper *ProgramGen: Scalable Environment Construction for Agents That Develop Software from Scratch*.** Each task asks an agent to rebuild a real open-source project from scratch, in a container without network access, and scores the result with hidden executable tests.
> [!Tip]> Tasks are [Harbor](https://github.com/harbor-framework/harbor) task directories. The model fine-tuned on the trajectories is [`Lego-X/ProgramGen-27B`](https://huggingface.co/Lego-X/ProgramGen-27B).
- **Forward mode**: the agent gets a specification and reconstructs the Python package; the repository's own tests are the hidden verifier.- **Reverse mode**: the agent gets usage documentation and can query the original command-line program, which runs in a separate container; hidden black-box tests compare the rebuilt program with it.
<div style="max-width:860px;margin:0 auto;padding:6px 0"><table style="display:table;width:100%;table-layout:fixed;border-collapse:collapse;font-size:14px;margin:0"><thead><tr><th style="padding:9px 8px;text-align:left;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:37%;"></th><th style="padding:9px 8px;text-align:center;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:21%;">Forward</th><th style="padding:9px 8px;text-align:center;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:21%;">Reverse</th><th style="padding:9px 8px;text-align:center;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:21%;background:rgba(179,67,31,0.07);">Total</th></tr></thead><tbody><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Tasks</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">2,142</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">3,980</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);"><strong>6,122</strong></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Verified tasks</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">2,026</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">3,905</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);"><strong>5,931</strong></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Training trajectories</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">1,290</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">1,295</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);"><strong>2,585</strong></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Languages</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">Python</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">Rust, Go, C, C++</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);"></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Hidden tests per task (median)</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">48</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">291</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);"></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Assistant turns per trajectory (median)</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">74</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">207</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);">104</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;padding-left:14px;">Trajectory length in tokens (median)</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">177K</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;">260K</td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:center;background:rgba(179,67,31,0.07);">208K</td></tr></tbody></table></div>
## Results
Fine-tuning Qwen3.8-27B on 2,600 of these trajectories (2,585 are released here):
<div style="max-width:860px;margin:0 auto;padding:8px 0"><table style="display:table;width:100%;table-layout:fixed;border-collapse:collapse;font-size:13px;margin:0"><thead><tr><th style="padding:10px 7px;text-align:left;border-bottom:2px solid #B3431F;width:40%"></th><th style="padding:10px 7px;text-align:center;font-weight:600;border-bottom:2px solid #B3431F;color:#B3431F;font-size:14px;width:20%;">Qwen3.8-27B</th><th style="padding:10px 7px;text-align:center;font-weight:600;border-bottom:2px solid #B3431F;color:#B3431F;font-size:14px;width:20%;background:rgba(179,67,31,0.07);">ProgramGen-27B</th><th style="padding:10px 7px;text-align:center;font-weight:600;border-bottom:2px solid #B3431F;color:#B3431F;font-size:14px;width:20%;">Change</th></tr></thead><tbody><tr><td colspan="4" style="padding:8px 12px;font-weight:600;color:#B3431F;border-bottom:1px solid rgba(128,128,128,0.18);background:rgba(179,67,31,0.13)">Building software from scratch</td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">Repository generation</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">NL2Repo-Bench</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Pass</div><div style="margin-top:2px;font-size:15px;line-height:1.15">39.3</div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Full</div><div style="margin-top:2px;font-size:15px;line-height:1.15">4.8</div></div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Pass</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><strong>46.6</strong></div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Full</div><div style="margin-top:2px;font-size:15px;line-height:1.15">4.8</div></div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Pass</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><span style="color:#B3431F">+7.3</span></div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Full</div><div style="margin-top:2px;font-size:15px;line-height:1.15">0.0</div></div></td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">Program reconstruction</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">ProgramBench</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Avg.</div><div style="margin-top:2px;font-size:15px;line-height:1.15">48.0</div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Almost</div><div style="margin-top:2px;font-size:15px;line-height:1.15">4.0</div></div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Avg.</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><strong>61.0</strong></div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Almost</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><strong>10.0</strong></div></div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><div style=""><div style="font-size:10px;line-height:1.1;opacity:0.55">Avg.</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><span style="color:#B3431F">+13.0</span></div></div><div style="margin-top:7px"><div style="font-size:10px;line-height:1.1;opacity:0.55">Almost</div><div style="margin-top:2px;font-size:15px;line-height:1.15"><span style="color:#B3431F">+6.0</span></div></div></td></tr><tr><td colspan="4" style="padding:8px 12px;font-weight:600;color:#B3431F;border-bottom:1px solid rgba(128,128,128,0.18);background:rgba(179,67,31,0.13)">Software repair</td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">DeepSWE</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">resolved, %</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;">41.6</td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><strong>60.2</strong></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><span style="color:#B3431F">+18.6</span></td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">SWE-bench Pro HARD</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">resolved, %</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;">76.5</td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><strong>84.3</strong></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><span style="color:#B3431F">+7.8</span></td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">SWE-bench Pro V2</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">resolved, %</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;">92.5</td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><strong>94.4</strong></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><span style="color:#B3431F">+1.9</span></td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">SWE-bench Multilingual</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">resolved, %</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;">78.0</td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><strong>79.7</strong></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><span style="color:#B3431F">+1.7</span></td></tr><tr><td colspan="4" style="padding:8px 12px;font-weight:600;color:#B3431F;border-bottom:1px solid rgba(128,128,128,0.18);background:rgba(179,67,31,0.13)">Terminal tasks</td></tr><tr><td style="padding:9px 7px 9px 18px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle"><div style="font-size:15px;font-weight:600;line-height:1.22">Terminal-Bench 2.1</div><div style="margin-top:4px;font-size:11px;line-height:1.2;opacity:0.6">resolved, %</div></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;">60.7</td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;background:rgba(179,67,31,0.07);"><strong>70.8</strong></td><td style="padding:9px 7px;text-align:center;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;font-size:15px;line-height:1.2;"><span style="color:#B3431F">+10.1</span></td></tr></tbody></table><div style="margin-top:10px;font-size:11px;line-height:1.5;opacity:0.7">Scores in %. Both models run in the same adapted OpenHands SDK 1.33 scaffold. The better result in each row is shown in bold.</div></div>
## Usage
Tested with [**Harbor v0.27.0**](https://github.com/harbor-framework/harbor/releases/tag/v0.27.0) and its Docker environment. Every index row has a `path`, so one task or one trajectory can be downloaded on its own.
```bash# <mode> is forward or reverse; the environment class is shipped in programgen_harbor/PYTHONPATH=ProgramGen harbor run -p ProgramGen/tasks/data/<mode>/<task_id> \ -e programgen_harbor:ProgramGenDockerEnvironment -a <agent> -m <model>```
> [!Important]> In reverse mode the reference program stays out of the agent's container: the agent only gets an execute-only socket client at `/reference/executable`, and the class above starts the program in a second container.>> <span style="color:#D32F2F"><b>Do not copy <code>environment/oracle/</code> into the agent's container.</b></span>>> Results obtained that way are not comparable with ours. Details are in the paper.
## Structure
```tasks/ index_verified.jsonl verified tasks index_1.3k+1.3k.jsonl tasks behind the training trajectories data/{forward,reverse}/<task_id>/ one Harbor task directorytrajectories/ index_1.3k+1.3k.jsonl training trajectories data/{forward,reverse}/<trial>/ one trajectoryprogramgen_harbor/ Harbor environment class used to run the tasks```
- **Verified tasks** passed our checks and have a working reference solution: tier `A` scores 1.0, tier `B` between 0.95 and 1.0. `oracle_reward` is the highest score reachable on the task.- **Training tasks** are the tasks behind the trajectories; 2,382 of them are also verified.- **Trajectories** were produced by DeepSeek-V4.1-Flash-1017 through OpenHands SDK 1.33, and each scored above 0.9 on its task. A trajectory is the final request (system prompt, full message history, tool definitions) plus the last response, in OpenAI chat format.- The task indexes and the trajectory index are independent lists, so a few trajectories have no matching task directory.- Internal host names, paths and credentials printed by tools were replaced with placeholders such as `<INTERNAL_IP>`.
<details><summary>Index fields</summary>
<div style="max-width:860px;margin:0 auto;padding:6px 0"><table style="display:table;width:100%;table-layout:fixed;border-collapse:collapse;font-size:14px;margin:0"><thead><tr><th style="padding:9px 8px;text-align:left;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:30%;">Field</th><th style="padding:9px 8px;text-align:left;font-weight:600;color:#B3431F;border-bottom:2px solid #B3431F;font-size:14px;width:70%;">Meaning</th></tr></thead><tbody><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>task_id</code>, <code>repo</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">task identifier and source repository on GitHub</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>mode</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;"><code>forward</code> or <code>reverse</code></td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>path</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">directory in this repository</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>tier</code>, <code>oracle_reward</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">see above (verified index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>empty_reward</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">score of an empty submission (verified index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>n_tests</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">number of scored tests (verified index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>evidence_reward</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">score of an audited agent run on the task, at least 0.9 (verified index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>in_1300</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">the task is also a training task (verified index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>trial</code>, <code>reward</code>, <code>n_messages</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">trajectory identifier, its score and its number of messages (trajectory index only)</td></tr><tr><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;font-weight:600;"><code>n_files</code>, <code>bytes</code></td><td style="padding:8px 8px;border-bottom:1px solid rgba(128,128,128,0.18);vertical-align:middle;line-height:1.35;text-align:left;">size</td></tr></tbody></table></div>
</details>
## Licence
The material written for this release (instructions, generated tests, graders, indexes, trajectories and the `programgen_harbor/` code) is under **Apache-2.0**. Files that come from a task's source repository, including the reference program built from it, remain under that repository's licence (MIT, Apache-2.0, BSD, MPL-2.0 or ISC), whose file is kept in the task.
## Citation
```bibtex[TO ADD]```12345"""Harbor environment for ProgramGen reverse tasks (reference program behind a socket, in its own container)."""
from programgen_harbor.environment import ProgramGenDockerEnvironment
__all__ = ["ProgramGenDockerEnvironment"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365"""Docker environment for ProgramGen reverse tasks.
A reverse task ships the reference program in ``environment/oracle/`` together with a smalldaemon (``programgen_reference_oracle.py``). The solver must be able to *run* the referencebut never read it, so this environment
1. replaces ``/reference/executable`` in the solver container with a statically linked, execute-only (mode 111) socket client,2. starts a second container from the same image and the same mounts, copies ``environment/oracle/`` into it and runs the daemon there,3. bind-mounts one host directory into both containers for the Unix socket.
The behaviour is switched on by ``[environment.reference_oracle]`` in ``task.toml``; taskswithout that table behave exactly like the stock Docker environment.
Usage (Harbor >= 0.27)::
PYTHONPATH=/path/to/this/folder/.. harbor run -p <task dir> \ --environment-import-path programgen_harbor:ProgramGenDockerEnvironment"""
from __future__ import annotations
import asyncioimport reimport shleximport shutilimport tomllibfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
from harbor.environments.base import ExecResultfrom harbor.environments.docker.docker import ( DockerEnvironment, _sanitize_docker_compose_project_name,)
from programgen_harbor.reference_client import programgen_reference_client_c_source
@dataclass(frozen=True)class ReferenceOracleConfig: """``[environment.reference_oracle]`` of a ProgramGen reverse task."""
enabled: bool = False kind: str = "programgen" socket: str = "/run/programgen-reference-oracle/oracle.sock" executable: str = "/opt/programgen-oracle/executable" timeout_sec: float = 60.0
@classmethod def from_task_dir(cls, environment_dir: Path) -> "ReferenceOracleConfig | None": task_toml = Path(environment_dir).parent / "task.toml" if not task_toml.is_file(): return None table = ( tomllib.loads(task_toml.read_text(encoding="utf-8")) .get("environment", {}) .get("reference_oracle") ) if not isinstance(table, dict): return None known = {k: table[k] for k in cls.__dataclass_fields__ if k in table} config = cls(**known) if not config.enabled or config.kind != "programgen": return None return config
def _safe_session_id(session_id: str) -> str: return re.sub(r"[^A-Za-z0-9]+__", "__", session_id)
class ProgramGenDockerEnvironment(DockerEnvironment): _PROGRAMGEN_ORACLE_CONTAINER_SUFFIX = "programgen-reference-oracle" _PROGRAMGEN_ORACLE_DIR = "/opt/programgen-oracle" _PROGRAMGEN_ORACLE_DAEMON_NAME = "programgen_reference_oracle.py"
def __init__(self, environment_dir: Path, *args: Any, **kwargs: Any) -> None: self._programgen_oracle_config = ReferenceOracleConfig.from_task_dir( Path(environment_dir) ) self._programgen_oracle_socket_host_dir: Path | None = None self._programgen_oracle_container_name: str | None = None if self._programgen_oracle_config is not None: trial_paths = kwargs.get("trial_paths") if trial_paths is None and len(args) >= 3: trial_paths = args[2] socket_dir = Path(trial_paths.trial_dir) / "programgen-reference-oracle-run" socket_dir.mkdir(parents=True, exist_ok=True) # Keep the host directory's group on files created through this bind mount. socket_dir.chmod(0o2777) self._programgen_oracle_socket_host_dir = socket_dir mounts = list(kwargs.get("mounts") or []) mounts.append( { "type": "bind", "source": str(socket_dir.resolve()), "target": str(Path(self._programgen_oracle_config.socket).parent), } ) kwargs["mounts"] = mounts # Harbor cuts the task name at 32 characters to build the trial name. When the cut ends # on ".", the Compose project name becomes "...-__<id>__env" and Docker rejects the # image tag derived from it. Drop the separator in front of "__". if isinstance(kwargs.get("session_id"), str): kwargs["session_id"] = _safe_session_id(kwargs["session_id"]) elif len(args) >= 2 and isinstance(args[1], str): args = (args[0], _safe_session_id(args[1]), *args[2:]) super().__init__(environment_dir, *args, **kwargs)
# ------------------------------------------------------------------ helpers
async def _programgen_docker( self, args: list[str], check: bool = True ) -> tuple[int, str]: process = await asyncio.create_subprocess_exec( *type(self)._engine_cmd(*args), stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) stdout, _ = await process.communicate() output = stdout.decode("utf-8", errors="replace") if stdout else "" if check and process.returncode != 0: raise RuntimeError( f"docker {' '.join(args)} failed ({process.returncode}): {output}" ) return process.returncode or 0, output
async def _remove_programgen_reference_oracle_container(self) -> None: if self._programgen_oracle_container_name is None: return await self._programgen_docker( ["rm", "-f", self._programgen_oracle_container_name], check=False ) self._programgen_oracle_container_name = None
def _cleanup_programgen_reference_oracle_socket_dir(self) -> None: if self._programgen_oracle_socket_host_dir is None: return shutil.rmtree(self._programgen_oracle_socket_host_dir, ignore_errors=True)
# ------------------------------------------------------- solver-side client
async def _setup_programgen_reference_client(self) -> None: reference_dir = self.environment_dir / "reference" docs_dir = self.environment_dir / "docs" assets_dir = self.environment_dir / "assets" if not (reference_dir / "executable").is_file(): raise FileNotFoundError( f"ProgramGen reference client missing: {reference_dir / 'executable'}" )
reset_result = await self.exec( "rm -rf /reference && mkdir -p /reference /reference/docs /reference/assets", cwd="/", user="root", ) if reset_result.return_code != 0: raise RuntimeError( "Failed to prepare ProgramGen reference client directory: " f"stdout={reset_result.stdout}, stderr={reset_result.stderr}" )
await self.upload_dir(reference_dir, "/reference") for source_dir, target_dir in ( (docs_dir, "/reference/docs"), (assets_dir, "/reference/assets"), ): if source_dir.is_dir() and any( path.is_file() for path in source_dir.rglob("*") ): await self.upload_dir(source_dir, target_dir)
client_source = programgen_reference_client_c_source() install_result = await self.exec( f"""set -euchmod -R a+rX /reference /reference/docs /reference/assetsrm -f /reference/executablecat > /tmp/programgen_reference_client.c <<'HARBOR_PROGRAMGEN_CLIENT_C'{client_source}HARBOR_PROGRAMGEN_CLIENT_Ccc_bin="$(command -v gcc || command -v cc || true)"if [ -z "$cc_bin" ]; then echo 'gcc or cc is required to build the ProgramGen execute-only reference client' >&2 exit 127fi"$cc_bin" -O2 -static /tmp/programgen_reference_client.c -o /reference/executablechown root:root /reference/executablechmod 111 /reference/executablemkdir -p /workspace/referencerm -f /workspace/reference/executableln -s /reference/executable /workspace/reference/executablerm -f /tmp/programgen_reference_client.c""", cwd="/", user="root", ) if install_result.return_code != 0: raise RuntimeError( "Failed to install ProgramGen reference client: " f"stdout={install_result.stdout}, stderr={install_result.stderr}" )
# ---------------------------------------------------------- oracle container
async def _wait_for_programgen_reference_oracle_ready(self, socket_path: str) -> None: probe_script = r"""import jsonimport socketimport structimport sys
socket_path = sys.argv[1]request = {"argv_b64": [], "cwd": "/workspace", "env": {}, "stdin_b64": ""}payload = json.dumps(request, separators=(",", ":")).encode("utf-8")sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)try: sock.connect(socket_path) sock.sendall(struct.pack(">Q", len(payload)) + payload) header = sock.recv(8) if len(header) != 8: raise RuntimeError("short response header") size = struct.unpack(">Q", header)[0] body = bytearray() while len(body) < size: chunk = sock.recv(size - len(body)) if not chunk: raise RuntimeError("short response body") body.extend(chunk) response = json.loads(body.decode("utf-8"))finally: sock.close()
return_code = int(response.get("return_code", 1))if return_code != 127: raise RuntimeError(f"unexpected probe return code: {return_code}")""" probe_command = ( f"test -S {shlex.quote(socket_path)} && " f"python3 -c {shlex.quote(probe_script)} {shlex.quote(socket_path)}" ) last_result: ExecResult | None = None for _ in range(60): last_result = await self.exec( probe_command, cwd="/", user="root", timeout_sec=5 ) if last_result.return_code == 0: return await asyncio.sleep(0.5)
detail = "" if last_result is not None: detail = ( f" Probe stdout={last_result.stdout or ''} " f"stderr={last_result.stderr or ''}" ) raise RuntimeError( "ProgramGen reference oracle socket did not become ready." + detail )
async def _setup_programgen_reference_oracle(self) -> None: config = self._programgen_oracle_config if config is None: return
oracle_dir = self.environment_dir / "oracle" reference_executable = oracle_dir / "executable" oracle_daemon = oracle_dir / self._PROGRAMGEN_ORACLE_DAEMON_NAME if not reference_executable.is_file(): raise FileNotFoundError( f"ProgramGen reference oracle executable missing: {reference_executable}" ) if not oracle_daemon.is_file(): raise FileNotFoundError( f"ProgramGen reference oracle daemon missing: {oracle_daemon}" )
await self._setup_programgen_reference_client()
container_name = _sanitize_docker_compose_project_name( f"{self.session_id}-{self._PROGRAMGEN_ORACLE_CONTAINER_SUFFIX}" ) self._programgen_oracle_container_name = container_name await self._programgen_docker(["rm", "-f", container_name], check=False)
# Same image, same mounts and same network policy as the solver container. await self._run_docker_compose_command( [ "run", "--no-deps", "--detach", "--name", container_name, "--user", "root", "--entrypoint", "sleep", "main", "infinity", ] ) await self._programgen_docker( ["exec", container_name, "mkdir", "-p", self._PROGRAMGEN_ORACLE_DIR] ) await self._programgen_docker( ["cp", f"{oracle_dir}/.", f"{container_name}:{self._PROGRAMGEN_ORACLE_DIR}/"] )
daemon_path = f"{self._PROGRAMGEN_ORACLE_DIR}/{self._PROGRAMGEN_ORACLE_DAEMON_NAME}" # Files fetched from a dataset hub lose their mode bits; the reference and any # bundled runtime must be executable inside the (private) oracle container. await self._programgen_docker( ["exec", container_name, "chmod", "-R", "u+rwX,go-rwx", self._PROGRAMGEN_ORACLE_DIR] ) await self._programgen_docker( ["exec", container_name, "chmod", "-R", "u+x", self._PROGRAMGEN_ORACLE_DIR] ) await self._programgen_docker( ["exec", container_name, "chmod", "755", daemon_path] )
quoted_env = " ".join( [ "PROGRAMGEN_REFERENCE_ORACLE_SOCKET=" + shlex.quote(config.socket), "PROGRAMGEN_REFERENCE_EXECUTABLE=" + shlex.quote(config.executable), "PROGRAMGEN_REFERENCE_ORACLE_TIMEOUT_SEC=" + shlex.quote(str(config.timeout_sec)), ] ) start_command = ( f"{quoted_env} exec python3 {shlex.quote(daemon_path)} " "> /tmp/programgen-reference-oracle.log 2>&1" ) await self._programgen_docker( ["exec", "-d", container_name, "bash", "-lc", start_command] )
try: await self._wait_for_programgen_reference_oracle_ready(config.socket) except RuntimeError as probe_error: _, logs = await self._programgen_docker( ["exec", container_name, "cat", "/tmp/programgen-reference-oracle.log"], check=False, ) raise RuntimeError( "ProgramGen reference oracle socket did not become ready. " f"Daemon log: {logs}. Probe error: {probe_error}" ) from probe_error
# ------------------------------------------------------------------ lifecycle
async def start(self, force_build: bool): await super().start(force_build) if self._programgen_oracle_config is not None: await self._setup_programgen_reference_oracle()
async def stop(self, delete: bool): await self._remove_programgen_reference_oracle_container() try: await super().stop(delete) finally: self._cleanup_programgen_reference_oracle_socket_dir()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676"""Shared ProgramGen execute-only reference client source."""
from __future__ import annotations
def programgen_reference_client_c_source() -> str: return r"""#define _GNU_SOURCE#include <errno.h>#include <fcntl.h>#include <stdint.h>#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/prctl.h>#include <sys/select.h>#include <sys/socket.h>#include <sys/un.h>#include <unistd.h>
extern char **environ;
static const char b64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static const char refusal_message[] = "programgen policy denied: debugging or wrapping " "/reference/executable is not allowed\n";
struct buffer { unsigned char *data; size_t len; size_t cap;};
static int reserve_buffer(struct buffer *buf, size_t extra) { if (extra > SIZE_MAX - buf->len - 1) { return -1; } size_t need = buf->len + extra + 1; if (need <= buf->cap) { return 0; } size_t cap = buf->cap ? buf->cap : 256; while (cap < need) { if (cap > SIZE_MAX / 2) { cap = need; break; } cap *= 2; } unsigned char *next = realloc(buf->data, cap); if (next == NULL) { return -1; } buf->data = next; buf->cap = cap; return 0;}
static int append_bytes(struct buffer *buf, const void *data, size_t len) { if (reserve_buffer(buf, len) != 0) { return -1; } memcpy(buf->data + buf->len, data, len); buf->len += len; buf->data[buf->len] = '\0'; return 0;}
static int write_all_fd(int fd, const unsigned char *data, size_t len);
static int starts_with(const char *value, const char *prefix) { return strncmp(value, prefix, strlen(prefix)) == 0;}
static int has_blocked_loader_environment(void) { for (char **entry = environ; entry != NULL && *entry != NULL; entry++) { if (starts_with(*entry, "LD_") || starts_with(*entry, "DYLD_")) { return 1; } } return 0;}
static int tracer_pid(void) { FILE *status = fopen("/proc/self/status", "r"); if (status == NULL) { return 0; }
char line[256]; int pid = 0; while (fgets(line, sizeof(line), status) != NULL) { if (starts_with(line, "TracerPid:")) { pid = atoi(line + strlen("TracerPid:")); break; } } fclose(status); return pid;}
static int harden_process(void) { (void)prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); (void)prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); if (has_blocked_loader_environment() || tracer_pid() > 0) { (void)write_all_fd( STDERR_FILENO, (const unsigned char *)refusal_message, strlen(refusal_message) ); return -1; } return 0;}
static int append_cstr(struct buffer *buf, const char *value) { return append_bytes(buf, value, strlen(value));}
static int append_char(struct buffer *buf, char value) { return append_bytes(buf, &value, 1);}
static int append_json_string_content(struct buffer *buf, const char *value) { for (const unsigned char *p = (const unsigned char *)value; *p != '\0'; p++) { unsigned char ch = *p; switch (ch) { case '"': if (append_cstr(buf, "\\\"") != 0) { return -1; } break; case '\\': if (append_cstr(buf, "\\\\") != 0) { return -1; } break; case '\b': if (append_cstr(buf, "\\b") != 0) { return -1; } break; case '\f': if (append_cstr(buf, "\\f") != 0) { return -1; } break; case '\n': if (append_cstr(buf, "\\n") != 0) { return -1; } break; case '\r': if (append_cstr(buf, "\\r") != 0) { return -1; } break; case '\t': if (append_cstr(buf, "\\t") != 0) { return -1; } break; default: if (ch < 0x20) { char escaped[7]; snprintf(escaped, sizeof(escaped), "\\u%04x", ch); if (append_cstr(buf, escaped) != 0) { return -1; } } else if (append_char(buf, (char)ch) != 0) { return -1; } } } return 0;}
static char *base64_encode(const unsigned char *data, size_t len) { if (len > (SIZE_MAX / 4 - 1) * 3) { return NULL; } size_t out_len = 4 * ((len + 2) / 3); char *out = malloc(out_len + 1); if (out == NULL) { return NULL; }
size_t i = 0; size_t j = 0; while (i < len) { uint32_t octet_a = i < len ? data[i++] : 0; uint32_t octet_b = i < len ? data[i++] : 0; uint32_t octet_c = i < len ? data[i++] : 0; uint32_t triple = (octet_a << 16) | (octet_b << 8) | octet_c;
out[j++] = b64_table[(triple >> 18) & 0x3f]; out[j++] = b64_table[(triple >> 12) & 0x3f]; out[j++] = b64_table[(triple >> 6) & 0x3f]; out[j++] = b64_table[triple & 0x3f]; }
if (len % 3 == 1) { out[out_len - 2] = '='; out[out_len - 1] = '='; } else if (len % 3 == 2) { out[out_len - 1] = '='; } out[out_len] = '\0'; return out;}
static int b64_value(char ch) { if (ch >= 'A' && ch <= 'Z') { return ch - 'A'; } if (ch >= 'a' && ch <= 'z') { return ch - 'a' + 26; } if (ch >= '0' && ch <= '9') { return ch - '0' + 52; } if (ch == '+') { return 62; } if (ch == '/') { return 63; } return -1;}
static unsigned char *base64_decode(const char *value, size_t len, size_t *out_len) { *out_len = 0; if (len == 0) { return calloc(1, 1); } if (len % 4 != 0) { return NULL; }
size_t padding = 0; if (len >= 1 && value[len - 1] == '=') { padding++; } if (len >= 2 && value[len - 2] == '=') { padding++; }
size_t decoded_len = (len / 4) * 3 - padding; unsigned char *out = malloc(decoded_len ? decoded_len : 1); if (out == NULL) { return NULL; }
size_t i = 0; size_t j = 0; while (i < len) { int a = b64_value(value[i++]); int b = b64_value(value[i++]); int c = value[i] == '=' ? 0 : b64_value(value[i]); i++; int d = value[i] == '=' ? 0 : b64_value(value[i]); i++; if (a < 0 || b < 0 || c < 0 || d < 0) { free(out); return NULL; }
uint32_t triple = ((uint32_t)a << 18) | ((uint32_t)b << 12) | ((uint32_t)c << 6) | (uint32_t)d; if (j < decoded_len) { out[j++] = (triple >> 16) & 0xff; } if (j < decoded_len) { out[j++] = (triple >> 8) & 0xff; } if (j < decoded_len) { out[j++] = triple & 0xff; } }
*out_len = decoded_len; return out;}
static unsigned char *read_available_stdin(size_t *out_len) { *out_len = 0; fd_set readfds; FD_ZERO(&readfds); FD_SET(STDIN_FILENO, &readfds); struct timeval timeout = {0, 0}; int ready = select(STDIN_FILENO + 1, &readfds, NULL, NULL, &timeout); if (ready <= 0 || !FD_ISSET(STDIN_FILENO, &readfds)) { return calloc(1, 1); }
int flags = fcntl(STDIN_FILENO, F_GETFL); if (flags >= 0) { (void)fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); }
struct buffer buf = {0}; unsigned char chunk[65536]; for (;;) { ssize_t n = read(STDIN_FILENO, chunk, sizeof(chunk)); if (n > 0) { if (append_bytes(&buf, chunk, (size_t)n) != 0) { free(buf.data); buf.data = NULL; break; } continue; } if (n == 0) { break; } if (errno == EINTR) { continue; } if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } break; }
if (flags >= 0) { (void)fcntl(STDIN_FILENO, F_SETFL, flags); } if (buf.data == NULL) { return calloc(1, 1); } *out_len = buf.len; return buf.data;}
static char *current_working_directory(void) { size_t size = 256; for (;;) { char *buf = malloc(size); if (buf == NULL) { return NULL; } if (getcwd(buf, size) != NULL) { return buf; } free(buf); if (errno != ERANGE || size > (1 << 20)) { char *fallback = malloc(11); if (fallback != NULL) { memcpy(fallback, "/workspace", 11); } return fallback; } size *= 2; }}
static int send_all(int fd, const void *data, size_t len) { const unsigned char *p = data; while (len > 0) { ssize_t n = send(fd, p, len, 0); if (n < 0) { if (errno == EINTR) { continue; } return -1; } if (n == 0) { return -1; } p += n; len -= (size_t)n; } return 0;}
static int recv_exact(int fd, unsigned char *data, size_t len) { while (len > 0) { ssize_t n = recv(fd, data, len, 0); if (n < 0) { if (errno == EINTR) { continue; } return -1; } if (n == 0) { return -1; } data += n; len -= (size_t)n; } return 0;}
static int send_u64_be(int fd, uint64_t value) { unsigned char encoded[8]; for (int i = 7; i >= 0; i--) { encoded[i] = value & 0xff; value >>= 8; } return send_all(fd, encoded, sizeof(encoded));}
static int recv_u64_be(int fd, uint64_t *value) { unsigned char encoded[8]; if (recv_exact(fd, encoded, sizeof(encoded)) != 0) { return -1; } uint64_t out = 0; for (size_t i = 0; i < sizeof(encoded); i++) { out = (out << 8) | encoded[i]; } *value = out; return 0;}
static char *extract_json_string(const char *json, const char *key) { struct buffer pattern = {0}; if (append_char(&pattern, '"') != 0 || append_cstr(&pattern, key) != 0 || append_cstr(&pattern, "\":\"") != 0) { free(pattern.data); return NULL; }
char *start = strstr(json, (char *)pattern.data); free(pattern.data); if (start == NULL) { return NULL; } start = strchr(start, ':'); if (start == NULL || start[1] != '"') { return NULL; } start += 2;
char *end = start; while (*end != '\0') { if (*end == '"' && (end == start || end[-1] != '\\')) { break; } end++; } if (*end != '"') { return NULL; }
size_t len = (size_t)(end - start); char *out = malloc(len + 1); if (out == NULL) { return NULL; } memcpy(out, start, len); out[len] = '\0'; return out;}
static int extract_return_code(const char *json) { const char *pattern = "\"return_code\":"; char *start = strstr(json, pattern); if (start == NULL) { return 1; } start += strlen(pattern); return (int)strtol(start, NULL, 10);}
static int write_all_fd(int fd, const unsigned char *data, size_t len) { while (len > 0) { ssize_t n = write(fd, data, len); if (n < 0) { if (errno == EINTR) { continue; } return -1; } data += n; len -= (size_t)n; } return 0;}
static int env_key_equals(const char *key, size_t key_len, const char *expected) { return strlen(expected) == key_len && memcmp(key, expected, key_len) == 0;}
static int is_allowed_env_key(const char *key, size_t key_len) { if (env_key_equals(key, key_len, "LANG") || env_key_equals(key, key_len, "LC_ALL")) { return 1; } return 0;}
static int append_allowed_env(struct buffer *payload) { if (append_char(payload, '{') != 0) { return -1; } int first = 1; for (char **entry = environ; entry != NULL && *entry != NULL; entry++) { char *equals = strchr(*entry, '='); if (equals == NULL) { continue; } size_t key_len = (size_t)(equals - *entry); if (!is_allowed_env_key(*entry, key_len)) { continue; } if (!first && append_char(payload, ',') != 0) { return -1; } first = 0; if (append_char(payload, '"') != 0 || append_bytes(payload, *entry, key_len) != 0 || append_cstr(payload, "\":\"") != 0 || append_json_string_content(payload, equals + 1) != 0 || append_char(payload, '"') != 0) { return -1; } } return append_char(payload, '}');}
static int build_request(int argc, char **argv, struct buffer *payload) { if (append_cstr(payload, "{\"argv_b64\":[") != 0) { return -1; } for (int i = 0; i < argc; i++) { char *encoded = base64_encode((const unsigned char *)argv[i], strlen(argv[i])); if (encoded == NULL) { return -1; } int ok = 0; if (i > 0) { ok = append_char(payload, ','); } ok = ok || append_char(payload, '"') || append_cstr(payload, encoded) || append_char(payload, '"'); free(encoded); if (ok != 0) { return -1; } }
char *cwd = current_working_directory(); if (cwd == NULL) { return -1; } if (append_cstr(payload, "],\"cwd\":\"") != 0 || append_json_string_content(payload, cwd) != 0 || append_cstr(payload, "\",\"env\":") != 0 || append_allowed_env(payload) != 0 || append_cstr(payload, ",\"stdin_b64\":\"") != 0) { free(cwd); return -1; } free(cwd);
size_t stdin_len = 0; unsigned char *stdin_data = read_available_stdin(&stdin_len); if (stdin_data == NULL) { return -1; } char *stdin_b64 = base64_encode(stdin_data, stdin_len); free(stdin_data); if (stdin_b64 == NULL) { return -1; } int ok = append_cstr(payload, stdin_b64) || append_cstr(payload, "\"}"); free(stdin_b64); return ok == 0 ? 0 : -1;}
int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); if (harden_process() != 0) { return 126; } const char *socket_path = getenv("PROGRAMGEN_REFERENCE_ORACLE_SOCKET"); if (socket_path == NULL || socket_path[0] == '\0') { socket_path = "/run/programgen-reference-oracle/oracle.sock"; }
struct buffer payload = {0}; if (build_request(argc, argv, &payload) != 0) { fprintf(stderr, "programgen reference oracle unavailable: failed to build request\n"); free(payload.data); return 127; }
int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { fprintf(stderr, "programgen reference oracle unavailable: socket: %s\n", strerror(errno)); free(payload.data); return 127; }
struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(socket_path) >= sizeof(addr.sun_path)) { fprintf(stderr, "programgen reference oracle unavailable: socket path too long\n"); close(fd); free(payload.data); return 127; } strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { fprintf(stderr, "programgen reference oracle unavailable: connect: %s\n", strerror(errno)); close(fd); free(payload.data); return 127; }
if (send_u64_be(fd, (uint64_t)payload.len) != 0 || send_all(fd, payload.data, payload.len) != 0) { fprintf(stderr, "programgen reference oracle unavailable: send failed\n"); close(fd); free(payload.data); return 127; } free(payload.data);
uint64_t response_size = 0; if (recv_u64_be(fd, &response_size) != 0 || response_size > (256ULL << 20)) { fprintf(stderr, "programgen reference oracle unavailable: invalid response\n"); close(fd); return 127; }
char *response = malloc((size_t)response_size + 1); if (response == NULL) { close(fd); return 127; } if (recv_exact(fd, (unsigned char *)response, (size_t)response_size) != 0) { fprintf(stderr, "programgen reference oracle unavailable: receive failed\n"); free(response); close(fd); return 127; } close(fd); response[response_size] = '\0';
char *stdout_b64 = extract_json_string(response, "stdout_b64"); char *stderr_b64 = extract_json_string(response, "stderr_b64"); int return_code = extract_return_code(response); free(response);
size_t stdout_len = 0; size_t stderr_len = 0; unsigned char *stdout_data = base64_decode(stdout_b64 ? stdout_b64 : "", stdout_b64 ? strlen(stdout_b64) : 0, &stdout_len); unsigned char *stderr_data = base64_decode(stderr_b64 ? stderr_b64 : "", stderr_b64 ? strlen(stderr_b64) : 0, &stderr_len); free(stdout_b64); free(stderr_b64); if (stdout_data == NULL || stderr_data == NULL) { free(stdout_data); free(stderr_data); fprintf(stderr, "programgen reference oracle unavailable: malformed response\n"); return 127; }
(void)write_all_fd(STDOUT_FILENO, stdout_data, stdout_len); (void)write_all_fd(STDERR_FILENO, stderr_data, stderr_len); free(stdout_data); free(stderr_data);
if (return_code < 0 || return_code > 255) { return 1; } return return_code;}"""1234567891011121314151617181920212223242526FROM python:3.10-slim-bookworm AS builderENV DEBIAN_FRONTEND=noninteractiveENV PIP_NO_CACHE_DIR=1RUN apt-get update && apt-get install -y bash ca-certificates git curl iptables openssh-client procps python3 && rm -rf /var/lib/apt/lists/*RUN apt-get update && apt-get install -y build-essential pkg-config cmake ninja-build && rm -rf /var/lib/apt/lists/*WORKDIR /workspace/repo# full original repo; deps provisioned into the image; then stripped.COPY repo/ .RUN ["bash", "-lc", "set -e\npython3 -I -c 'import base64; from pathlib import Path; Path('\"'\"'/tmp/programgen-pip-compat-v1.py'\"'\"').write_bytes(base64.b64decode('\"'\"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='\"'\"'))'\nprogramgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py \"$@\"; }\nexport -f programgen_pip_install\nprogramgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel\nprogramgen_pip_install python3 -m pip install 'setuptools>=61.0'\nprogramgen_pip_install python3 -m pip install -r requirements.txt\nprogramgen_pip_install python3 -m pip install -r requirements-dev.txt || {\n echo \"[programgen] batch test requirement file install failed; installing one by one\" >&2\n for programgen_item in -r requirements-dev.txt; do\n programgen_pip_install python3 -m pip install $programgen_item || echo \"[programgen] skipped test requirement file: $programgen_item\" >&2\n done\n}\n(\nprogramgen_install_report=\"$(mktemp)\"\ntrap 'rm -f \"$programgen_install_report\"' EXIT\nSETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report \"$programgen_install_report\"\npython3 -c 'exec(\"import json,subprocess,sys\\nfrom pip._vendor.packaging.requirements import Requirement\\nfrom pip._vendor.packaging.utils import canonicalize_name\\nreport=json.load(open(sys.argv[1], encoding='\"'\"'utf-8'\"'\"'))\\n\\nrequested={canonicalize_name(name) for name in ()}\\nrequirements=[]\\nfor item in report.get('\"'\"'install'\"'\"', []):\\n metadata=item.get('\"'\"'metadata'\"'\"', {})\\n name=canonicalize_name(metadata.get('\"'\"'name'\"'\"', '\"'\"''\"'\"'))\\n provided={canonicalize_name(value) for value in metadata.get('\"'\"'provides_extra'\"'\"', [])}\\n selected={'\"'\"''\"'\"'} | (provided & requested)\\n parsed=[Requirement(value) for value in metadata.get('\"'\"'requires_dist'\"'\"', [])]\\n while True:\\n added=set()\\n for requirement in parsed:\\n if requirement.marker is not None and not any(requirement.marker.evaluate({'\"'\"'extra'\"'\"': extra}) for extra in selected):\\n continue\\n if canonicalize_name(requirement.name)==name:\\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('\"'\"'version'\"'\"', '\"'\"''\"'\"'), prereleases=True)):\\n raise ValueError('\"'\"'local extra requires a different target distribution'\"'\"')\\n extras={canonicalize_name(value) for value in requirement.extras}\\n if not extras <= provided:\\n raise ValueError('\"'\"'local extra refers to an undeclared extra'\"'\"')\\n added.update(extras - selected)\\n if not added:\\n break\\n selected.update(added)\\n for requirement in parsed:\\n if canonicalize_name(requirement.name)==name:\\n continue\\n if requirement.marker is None or any(requirement.marker.evaluate({'\"'\"'extra'\"'\"': extra}) for extra in selected):\\n requirement.marker=None\\n requirements.append(str(requirement))\\nrequirements=list(dict.fromkeys(requirements))\\nsubprocess.run([sys.executable, '\"'\"'-I'\"'\"', '\"'\"'/tmp/programgen-pip-compat-v1.py'\"'\"', sys.executable, '\"'\"'-m'\"'\"', '\"'\"'pip'\"'\"', '\"'\"'install'\"'\"', *requirements], check=True) if requirements else None\\n\")' \"$programgen_install_report\"\n)\nprogramgen_pip_install python3 -m pip install pytest coverage"]COPY pre_cleanup.sh /tmp/pre_cleanup.shRUN bash /tmp/pre_cleanup.sh /workspace/repo
FROM python:3.10-slim-bookwormENV DEBIAN_FRONTEND=noninteractiveENV PIP_NO_CACHE_DIR=1RUN apt-get update && apt-get install -y bash ca-certificates git curl iptables openssh-client procps python3 && rm -rf /var/lib/apt/lists/*RUN apt-get update && apt-get install -y build-essential pkg-config cmake ninja-build && rm -rf /var/lib/apt/lists/*WORKDIR /workspace/repo# cleaned workspace (build-config only, source already stripped in builder)COPY --from=builder --chown=0:0 /workspace/repo /workspace/repo# provisioned third-party dependencies (offline self-contained)RUN rm -rf /usr/local/lib/python*/site-packages /usr/local/lib/python*/dist-packagesCOPY --from=builder /usr/local/lib /usr/local/libCOPY --from=builder /usr/local/bin /usr/local/bin# network DISABLED at run time: docker run --network none# the agent reconstructs the repository from scratch here; test: python3 -m pytest -vv --continue-on-collection-errors -o addopts= test/test_config.py test/test_data_loader.py test/test_main.py test/test_social_security.py test/test_taxes_children.py test/test_taxes_income.py test/test_taxes_other.py1234567891011121314151617181920212223242526FROM python:3.10-slim-bookworm AS builderENV DEBIAN_FRONTEND=noninteractiveENV PIP_NO_CACHE_DIR=1RUN apt-get update && apt-get install -y bash ca-certificates git curl iptables openssh-client procps python3 && rm -rf /var/lib/apt/lists/*RUN apt-get update && apt-get install -y build-essential pkg-config cmake ninja-build && rm -rf /var/lib/apt/lists/*WORKDIR /workspace/repo# full original repo; deps provisioned into the image; then stripped.COPY repo/ .RUN ["bash", "-lc", "set -e\npython3 -I -c 'import base64; from pathlib import Path; Path('\"'\"'/tmp/programgen-pip-compat-v1.py'\"'\"').write_bytes(base64.b64decode('\"'\"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='\"'\"'))'\nprogramgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py \"$@\"; }\nexport -f programgen_pip_install\nprogramgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel\nprogramgen_pip_install python3 -m pip install 'setuptools>=61.0'\nprogramgen_pip_install python3 -m pip install -r requirements.txt\nprogramgen_pip_install python3 -m pip install -r requirements-dev.txt || {\n echo \"[programgen] batch test requirement file install failed; installing one by one\" >&2\n for programgen_item in -r requirements-dev.txt; do\n programgen_pip_install python3 -m pip install $programgen_item || echo \"[programgen] skipped test requirement file: $programgen_item\" >&2\n done\n}\n(\nprogramgen_install_report=\"$(mktemp)\"\ntrap 'rm -f \"$programgen_install_report\"' EXIT\nSETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report \"$programgen_install_report\"\npython3 -c 'exec(\"import json,subprocess,sys\\nfrom pip._vendor.packaging.requirements import Requirement\\nfrom pip._vendor.packaging.utils import canonicalize_name\\nreport=json.load(open(sys.argv[1], encoding='\"'\"'utf-8'\"'\"'))\\n\\nrequested={canonicalize_name(name) for name in ()}\\nrequirements=[]\\nfor item in report.get('\"'\"'install'\"'\"', []):\\n metadata=item.get('\"'\"'metadata'\"'\"', {})\\n name=canonicalize_name(metadata.get('\"'\"'name'\"'\"', '\"'\"''\"'\"'))\\n provided={canonicalize_name(value) for value in metadata.get('\"'\"'provides_extra'\"'\"', [])}\\n selected={'\"'\"''\"'\"'} | (provided & requested)\\n parsed=[Requirement(value) for value in metadata.get('\"'\"'requires_dist'\"'\"', [])]\\n while True:\\n added=set()\\n for requirement in parsed:\\n if requirement.marker is not None and not any(requirement.marker.evaluate({'\"'\"'extra'\"'\"': extra}) for extra in selected):\\n continue\\n if canonicalize_name(requirement.name)==name:\\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('\"'\"'version'\"'\"', '\"'\"''\"'\"'), prereleases=True)):\\n raise ValueError('\"'\"'local extra requires a different target distribution'\"'\"')\\n extras={canonicalize_name(value) for value in requirement.extras}\\n if not extras <= provided:\\n raise ValueError('\"'\"'local extra refers to an undeclared extra'\"'\"')\\n added.update(extras - selected)\\n if not added:\\n break\\n selected.update(added)\\n for requirement in parsed:\\n if canonicalize_name(requirement.name)==name:\\n continue\\n if requirement.marker is None or any(requirement.marker.evaluate({'\"'\"'extra'\"'\"': extra}) for extra in selected):\\n requirement.marker=None\\n requirements.append(str(requirement))\\nrequirements=list(dict.fromkeys(requirements))\\nsubprocess.run([sys.executable, '\"'\"'-I'\"'\"', '\"'\"'/tmp/programgen-pip-compat-v1.py'\"'\"', sys.executable, '\"'\"'-m'\"'\"', '\"'\"'pip'\"'\"', '\"'\"'install'\"'\"', *requirements], check=True) if requirements else None\\n\")' \"$programgen_install_report\"\n)\nprogramgen_pip_install python3 -m pip install pytest coverage"]COPY pre_cleanup.sh /tmp/pre_cleanup.shRUN bash /tmp/pre_cleanup.sh /workspace/repo
FROM python:3.10-slim-bookwormENV DEBIAN_FRONTEND=noninteractiveENV PIP_NO_CACHE_DIR=1RUN apt-get update && apt-get install -y bash ca-certificates git curl iptables openssh-client procps python3 && rm -rf /var/lib/apt/lists/*RUN apt-get update && apt-get install -y build-essential pkg-config cmake ninja-build && rm -rf /var/lib/apt/lists/*WORKDIR /workspace/repo# cleaned workspace (build-config only, source already stripped in builder)COPY --from=builder --chown=0:0 /workspace/repo /workspace/repo# provisioned third-party dependencies (offline self-contained)RUN rm -rf /usr/local/lib/python*/site-packages /usr/local/lib/python*/dist-packagesCOPY --from=builder /usr/local/lib /usr/local/libCOPY --from=builder /usr/local/bin /usr/local/bin# network DISABLED at run time: docker run --network none# the agent reconstructs the repository from scratch here; test: python3 -m pytest -vv --continue-on-collection-errors -o addopts= test/test_config.py test/test_data_loader.py test/test_main.py test/test_social_security.py test/test_taxes_children.py test/test_taxes_income.py test/test_taxes_other.py12345678910#!/bin/bash# Build the self-contained closed-book inference image (+ eval image) from# the committed task directory. No pre-built or pushed base image required.set -euo pipefailHERE="$(cd "$(dirname "$0")/.." && pwd)" # task rootINFERENCE_DOCKERFILE="$HERE/environment/Dockerfile.inference"if [ ! -f "$INFERENCE_DOCKERFILE" ]; then INFERENCE_DOCKERFILE="$HERE/environment/Dockerfile"; fidocker build -t programgen-forward/0-k_1776_netto.1b47785:inference -f "$INFERENCE_DOCKERFILE" "$HERE/environment"docker build -t programgen-forward/0-k_1776_netto.1b47785:eval -f "$HERE/tests/Dockerfile" "$HERE/tests"echo "built programgen-forward/0-k_1776_netto.1b47785:inference and programgen-forward/0-k_1776_netto.1b47785:eval"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114#!/bin/bash# programgen forward pre-cleanup: closed-book repo# (keep build config + provisioned deps; strip target-repo source/tests).set -euo pipefailROOT="${1:-/workspace/repo}"cd "$ROOT"# 0. Remove the target distribution installed while provisioning deps. Both# editable and wheel installs can otherwise copy the answer into site-packages.TARGET_DIST=nettofor PROGRAMGEN_UNINSTALL_ATTEMPT in 1 2 3; do python3 - "$ROOT" "$TARGET_DIST" <<'PY' > /tmp/programgen-target-dists.txtimport importlib.metadataimport jsonimport reimport sysfrom pathlib import Pathfrom urllib.parse import unquote, urlparseroot = Path(sys.argv[1]).resolve()target = re.sub(r'[-_.]+', '-', sys.argv[2]).lower()for dist in importlib.metadata.distributions(): name = str(dist.metadata.get('Name') or '').strip() try: metadata_root = Path(dist.locate_file('')).resolve() metadata_is_local = metadata_root == root or root in metadata_root.parents except Exception: metadata_is_local = False try: direct = json.loads(dist.read_text('direct_url.json') or '{}') url = str(direct.get('url') or '') source = Path(unquote(urlparse(url).path)).resolve() if url.startswith('file:') else None except Exception: source = None normalized = re.sub(r'[-_.]+', '-', name).lower() if name and not metadata_is_local and (source == root or (target and normalized == target)): print(name)PY sort -fu /tmp/programgen-target-dists.txt -o /tmp/programgen-target-dists.txt if [ ! -s /tmp/programgen-target-dists.txt ]; then break; fi xargs -r python3 -m pip uninstall -y < /tmp/programgen-target-dists.txtdone# Fail closed if a local-project distribution survived uninstall.python3 - "$ROOT" "$TARGET_DIST" <<'PY'import importlib.metadataimport jsonimport reimport sysfrom pathlib import Pathfrom urllib.parse import unquote, urlparseroot = Path(sys.argv[1]).resolve()target = re.sub(r'[-_.]+', '-', sys.argv[2]).lower()leaks = []for dist in importlib.metadata.distributions(): name = str(dist.metadata.get('Name') or '').strip() try: metadata_root = Path(dist.locate_file('')).resolve() metadata_is_local = metadata_root == root or root in metadata_root.parents except Exception: metadata_is_local = False try: direct = json.loads(dist.read_text('direct_url.json') or '{}') url = str(direct.get('url') or '') source = Path(unquote(urlparse(url).path)).resolve() if url.startswith('file:') else None except Exception: source = None normalized = re.sub(r'[-_.]+', '-', name).lower() if not metadata_is_local and (source == root or (target and normalized == target)): leaks.append(name or str(dist))if leaks: raise SystemExit('target distributions remain installed: ' + ', '.join(leaks))PY# 1. strip target-repo source + test files (build config kept)find . -type f \( -name '*.c' -o -name '*.c++' -o -name '*.cc' -o -name '*.cjs' -o -name '*.cpp' -o -name '*.cts' -o -name '*.cu' -o -name '*.cuh' -o -name '*.cxx' -o -name '*.go' -o -name '*.h' -o -name '*.h++' -o -name '*.hh' -o -name '*.hpp' -o -name '*.hxx' -o -name '*.inl' -o -name '*.ipp' -o -name '*.java' -o -name '*.js' -o -name '*.jsx' -o -name '*.kt' -o -name '*.kts' -o -name '*.mjs' -o -name '*.mts' -o -name '*.pxd' -o -name '*.pxi' -o -name '*.py' -o -name '*.pyi' -o -name '*.pyx' -o -name '*.rs' -o -name '*.tpp' -o -name '*.ts' -o -name '*.tsx' \) -not -path './setup.py' -not -path './vendor/*' -not -path './node_modules/*' -delete || truerm -rf -- test/test_config.py test/test_data_loader.py test/test_main.py test/test_social_security.py test/test_taxes_children.py test/test_taxes_income.py test/test_taxes_other.py 2>/dev/null || truerm -rf tests test spec specs __tests__ 2>/dev/null || true# 2. strip build caches + editor/CI metadata (deps in ~/.cargo etc. kept)rm -rf target build dist .programgen-build .pytest_cache __pycache__ *.egg-info .github .idea 2>/dev/null || true# 2a. programgen closed-book artifact sweep v2: provisioning leftovers reproduce the stripped# implementation (bytecode, in-place compiled extensions) or its layout# (egg-info/dist-info); remove them everywhere except vendored deps.find . \( -path './vendor' -o -path './node_modules' \) -prune -o -type d \( -name '__pycache__' -o -name '*.egg-info' -o -name '*.dist-info' -o -name '.eggs' -o -name '.pytest_cache' -o -name '.mypy_cache' -o -name '.ruff_cache' -o -name '.hypothesis' -o -name '.tox' -o -name '.nox' -o -name 'htmlcov' \) -print0 2>/dev/null | xargs -0 -r rm -rf || truefind . \( -path './vendor' -o -path './node_modules' \) -prune -o -type d \( -name .venv -o -name venv \) -exec test -f '{}/pyvenv.cfg' \; -print0 2>/dev/null | xargs -0 -r rm -rf || truefind . \( -path './vendor' -o -path './node_modules' \) -prune -o -type d \( -path '*/build/lib.*' -o -path '*/build/temp.*' -o -path '*/build/bdist.*' -o -path '*/build/lib' \) -print0 2>/dev/null | xargs -0 -r rm -rf || truefind . \( -path './vendor' -o -path './node_modules' \) -prune -o -type f \( -name '*.pyc' -o -name '*.pyo' -o -name '*.pyd' -o -name '*.cpython-*.so' -o -name '*.abi3.so' -o -name '*.cpython-*.dylib' -o -name '*.whl' -o -name '*.egg' -o -name '*.orig' -o -name '*.rej' -o -name '.coverage' -o -name '.coverage.*' \) -print0 2>/dev/null | xargs -0 -r rm -f || true# 2b. strip editable-install residue that leaks the target package name/layout# (`pip/pdm install -e .`): repo-local .pdm-build/*.egg-*, and the editable# .pth pointers in site-packages that resolve back to this repo. Third-party# dependency packages have their own dist-info and are untouched.rm -rf .pdm-build .pdm-python *.egg-link 2>/dev/null || truefor SP in $(python3 -c "import site,sys;print(\"\\n\".join(set(site.getsitepackages()+[site.getusersitepackages()])))" 2>/dev/null); do [ -d "$SP" ] || continue find "$SP" -maxdepth 1 -name "__editable__*.pth" -delete 2>/dev/null || true grep -rl "$ROOT" "$SP"/*.pth 2>/dev/null | xargs -r rm -f || truedone# 2c. strip docs/examples + leftover EMPTY dirs (align with DeNovoSWE clean.sh):# docs/*.rst can leak API usage; an empty package dir leaks the package# name+layout. Build config (setup.py / pyproject / lockfiles / LICENSE)# is kept; provisioned deps live outside $ROOT and are untouched.find . -type f \( -name '*.md' -o -name '*.rst' \) -delete 2>/dev/null || truefind . -type d \( -name docs -o -name doc -o -name examples -o -name example \) -not -path './vendor/*' -not -path './node_modules/*' -exec rm -rf {} + 2>/dev/null || truefind . -type d -empty -delete 2>/dev/null || true# 2z. programgen closed-book artifact check v2: fail closed before the baseline commitPROGRAMGEN_LEFTOVERS=$(find . \( -path './vendor' -o -path './node_modules' \) -prune -o \( -type d \( -name '__pycache__' -o -name '*.egg-info' -o -name '*.dist-info' \) -o -type f \( -name '*.pyc' -o -name '*.pyo' -o -name '*.pyd' -o -name '*.cpython-*.so' -o -name '*.abi3.so' -o -name '*.whl' -o -name '*.egg' \) \) -print 2>/dev/null | head -20 || true)if [ -n "$PROGRAMGEN_LEFTOVERS" ]; then echo "programgen closed-book leftovers remain under $ROOT:" >&2 echo "$PROGRAMGEN_LEFTOVERS" >&2 exit 1fi# 3. git history sanitization (fresh repo, no history to mine)rm -rf .gitgit init -qgit config user.email closed-book@programgen.localgit config user.name programgengit add -f -Agit commit --allow-empty -qm 'programgen forward closed-book baseline'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/pip-wheel-metadata/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuildertarget/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv.python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder netto settings.spyderproject.spyproject
# Rope netto settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
*.idea*.DS_Store# Personal scenario scripts (contain private salary data)family_scenario.py123456789101112# See https://pre-commit.com for more information# See https://pre-commit.com/hooks.html for more hooksrepos: - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. rev: v0.8.4 hooks: # Run the linter. - id: ruff args: [--fix, --unsafe-fixes] # Run the formatter. - id: ruff-format123456789101112131415161718# Read the Docs configuration file for netto# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
version: 2
build: os: ubuntu-22.04 tools: python: "3.12"
sphinx: configuration: docs/conf.py
python: install: - requirements: docs/requirements.txt - method: pip path: .123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.2.0] - 2026-07-12
### Added- **Kindergeld and Kinderfreibetrag with Günstigerprüfung**: New `num_children` field on `TaxConfig`. When set, `calc_netto` includes the yearly Kindergeld in the result and applies the per-child Günstigerprüfung (§ 31 EStG): if the Kinderfreibetrag (incl. BEA) yields more tax relief than the Kindergeld, the allowance is deducted and the Kindergeld added back to the tax. Solidarity surcharge and church tax are always computed on the fictitious income tax with all child allowances deducted (§ 3 SolzG, § 51a EStG). Official amounts 2018-2026 in `data/children/{year}.json` (2027-2032 forecast); new public helpers `calc_kindergeld`, `calc_child_allowance_per_child`, `apply_guenstigerpruefung`. Simplifications: first/second-child Kindergeld rate for all children, no Corona-Kinderboni, single parents get half the allowance without Übertragung- **Year-aware health Zusatzbeitrag**: The official average Zusatzbeitrag now lives in the social security data files (1.0% in 2018 up to 2.9% in 2026, forecast to 3.5% by 2032). `TaxConfig.extra_health_insurance` defaults to `None`, meaning "use the year's official average"; set it explicitly to match a specific Krankenkasse. Previously a flat 2.5% default was applied to every year, overstating health contributions for 2018-2024- **Forecast data for 2027-2032**: All data categories extended with estimates for planning purposes, generated by the new `scripts/generate_forecast.py` (documented assumptions: 2%/year tax bracket indexation with frozen top bracket, 3%/year contribution ceiling growth, pension/nursing rate paths from official projections; see `data/README.md`)- **Dual-income households**: New `partner_salary` parameter on `calc_netto` and `calc_inverse_netto` for jointly assessed couples where both partners work - Income tax is assessed jointly (Ehegattensplitting) on the combined income - Social security contributions are calculated per person against the individual contribution ceilings (Beitragsbemessungsgrenzen) - Each earner receives their own Werbungskosten-Pauschbetrag - `calc_inverse_netto` solves for the primary salary with the partner salary fixed- **Lump-sum deductions data**: New `data/deductions/{year}.json` files with year-specific Werbungskosten-Pauschbetrag (1,000 € until 2021, 1,200 € in 2022, 1,230 € since 2023) and Sonderausgaben-Pauschbetrag, validated via the new `Deductions` Pydantic model- **Tax year 2026 support**: Added preliminary tax data for 2026 - Income tax brackets with estimated values - Social security rates and contribution limits - Solidarity tax parameters - Pension correction factors- **Pre-commit hooks**: Added `.pre-commit-config.yaml` for automatic code quality checks - Runs ruff linting with auto-fix before each commit - Runs ruff formatting before each commit - Prevents CI failures by catching issues locally - Added `pre-commit` to development dependencies- **TaxConfig dataclass**: New `TaxConfig` dataclass for explicit, type-safe configuration - Replaces environment variable-based configuration - Provides validation in `__post_init__` - Supports year (2018-2026), has_children, is_married, extra_health_insurance, church_tax- **Data validation with Pydantic**: All tax and social security data now validated using Pydantic models- **ReadTheDocs configuration**: Added `.readthedocs.yml` for proper documentation building- **MANIFEST.in**: Ensures data files are included in package distribution- **Comprehensive project documentation**: Added `CLAUDE.md` with detailed project guide for developers- **Data directory structure**: Tax data now organized in JSON files for better maintainability: - `data/tax_curves/{year}.json` - Income tax brackets (2018-2026) - `data/social_security/{year}.json` - Social security rates (2018-2026) - `data/soli/{year}.json` - Solidarity tax parameters (2018-2026) - `data/pension_factors/{year}.json` - Pension correction factors (2018-2026) - `data/README.md` - Documentation for tax data structure and sources- **Data loader module**: New `netto.data_loader` module with: - Pydantic models: `TaxCurve`, `SocialSecurity`, `SoliCurve`, `PensionFactor` - Validation functions for all data types - Module-level variables for easy import- **Dependencies**: Added `pydantic>=2.0` for data validation- **Type hints**: Added throughout the codebase for better IDE support- **Explicit public API**: Defined `__all__` in `__init__.py`
### Changed- **Code Quality Tools**: Migrated from Black, isort, and Flake8 to Ruff - Single, faster tool for formatting and linting - Configuration in `pyproject.toml` - Line length set to 88 (Black-compatible, industry standard) - Updated CI workflow to use Ruff - Updated development dependencies in `requirements-dev.txt` - Applied ruff formatting and linting fixes across entire codebase- **README.md**: Completely redesigned for better usability - Added comprehensive feature list - Added installation instructions - Added quick start examples (basic, custom config, with deductibles) - Added configuration reference table - Added development setup instructions - Added code quality commands using Ruff - Updated badge from "Code style: black" to Ruff badge- **CLAUDE.md**: Updated project documentation - Updated project structure to reflect `data/` directory instead of `const.py` - Updated Code Style section to mention Ruff instead of Black/Flake8 - Updated Testing section to reflect pytest migration (completed) - Updated Linting and Formatting section with Ruff commands - Updated Updating Tax Data section to reflect new JSON-based workflow - Updated CI/CD section to mention Ruff - Moved completed tasks to "Completed Tasks" section - Updated Tax Year Support Matrix (2018-2026 now fully supported)- **BREAKING**: Configuration system completely refactored: - Environment variable support removed (`NETTO_YEAR`, etc. no longer work) - All functions now accept optional `config: TaxConfig` parameter - Defaults to `TaxConfig()` with sensible defaults (year=2025, single, no church tax) - No more global state or hidden configuration- **BREAKING**: Refactored data storage from hardcoded Python dictionaries to validated JSON files- **BREAKING**: Removed `netto.const` module - import from `netto.data_loader` instead- **BREAKING**: Python 3.10+ required (was 3.8+)- **Version**: Updated from 0.1.x to 0.2.0- **Copyright years**: Updated to 2025 in LICENSE, README.md, and documentation- **Documentation version**: Updated Sphinx docs to version 0.2.0- **Supported tax years**: Updated README to reflect 2018-2026 support- **Package configuration**: Added explicit package discovery in `pyproject.toml`- **Dependencies**: Now declared in `pyproject.toml` (scipy, pydantic>=2.0)- **Documentation dependencies**: Updated `docs/requirements.txt` with missing packages- **Default year**: Updated default year from 2022 to 2025- **Health insurance rate**: Updated default extra health insurance rate from 1.4% to 2.5%
### Removed- **Development Dependencies**: Removed Black, isort, and Twine from `requirements-dev.txt` - Replaced with Ruff for formatting and linting - Twine removed as it's not needed for modern PyPI publishing workflow- **BREAKING**: Environment variable configuration support (no more `NETTO_YEAR`, `NETTO_MARRIED`, etc.)- **BREAKING**: `load_config_from_env()` function removed- **BREAKING**: `get_default_config()` function removed- **BREAKING**: Global configuration state removed- **BREAKING**: `netto/const.py` module (replaced by `netto/data_loader.py`)- **TODO list**: Removed from README.md (moved to CLAUDE.md for internal tracking)
### Fixed- **Pension deduction factors 2023/2024**: Corrected from 0.92/0.96 to 1.0 — the Jahressteuergesetz 2022 made pension contributions fully deductible from 2023 (the library previously overstated taxes for 2023/2024 by roughly 100-250 €/year for typical salaries)- **2026 tax curve coefficients**: Filled in the missing polynomial `const` values from the Steuerfortentwicklungsgesetz; the exact-formula method (`calc_income_tax`) previously crashed for 2026- **Solidarity tax for married couples**: The soli exemption threshold (Freigrenze) is now doubled for jointly assessed couples. Previously, married couples were charged up to ~2,200 €/year too much soli in the mid-to-high income range- **Year-specific lump-sum deductions**: `calc_taxable_income` no longer hardcodes the 2022 Werbungskosten-Pauschbetrag (1,200 €) for all years, and the Sonderausgaben-Pauschbetrag is doubled for married couples (72 € instead of 36 €)- **Married income tax via exact formula**: `calc_income_tax` now applies the splitting tariff (2 × tax(income/2)) for married couples, consistent with `calc_income_tax_by_integration`- **Test rounding tolerance**: Adjusted test assertions to use appropriate rounding tolerance for floating-point comparisons- **Tax curve polynomial coefficients**: Added missing coefficients and corrected bracket boundaries for 2021-2025- **ReadTheDocs build**: Fixed setuptools package discovery error- **Documentation builds**: Added missing Sphinx dependencies (sphinx>=5.0, sphinx-rtd-theme)- **Variable shadowing**: Fixed `UnboundLocalError` in `taxes_income.py`- **Import paths**: Updated all modules to import from `data_loader` instead of `const`
### Technical Improvements- **Better maintainability**: Tax data in JSON files vs. hardcoded Python- **Schema validation**: Pydantic ensures data integrity- **Clearer git history**: Individual yearly files make changes easier to review- **Easier auditing**: JSON files can be compared against official sources- **Scalability**: Simple to add new tax years (just create new JSON files)- **Separation of concerns**: Data separated from code
### Migration Guide for 0.2.0
**1. Configuration Changes:**
```python# OLD (0.1.x) - Environment variablesimport osos.environ['NETTO_YEAR'] = '2024'os.environ['NETTO_MARRIED'] = '1'from netto import calc_nettocalc_netto(50000) # Used env vars
# NEW (0.2.0) - Explicit TaxConfigfrom netto import calc_netto, TaxConfig
# Use defaultscalc_netto(50000) # year=2022, single, no church tax
# Or explicit configconfig = TaxConfig(year=2024, is_married=True)calc_netto(50000, config=config)```
**2. Internal imports (if you were using them):**
```python# OLD (0.1.x) - No longer worksfrom netto.const import __tax_curve, __social_security_curve
# NEW (0.2.0) - Import from data_loaderfrom netto.data_loader import tax_curve, social_security_curve```
**3. Python version requirement:**- Minimum Python version is now 3.10 (was 3.8)
## [0.1.0] - 2023-05-19
### Added- Initial release- Calculate net income from gross salary (`calc_netto`)- Calculate required gross salary for desired net income (`calc_inverse_netto`)- Support for married couples (doubles tax brackets)- Support for children (affects nursing insurance)- Optional church tax- Public health and pension insurance- West-German pension deduction- Tax years 2018-2024 support
[Unreleased]: https://github.com/0-k/netto/compare/v0.2.0...HEAD[0.2.0]: https://github.com/0-k/netto/releases/tag/v0.2.0[0.1.0]: https://github.com/0-k/netto/releases/tag/v0.1.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509# Claude.md - Netto Project Guide
## Project Overview
**Netto** is a German income tax (Einkommensteuer) and social security (Sozialabgaben) calculator written in Python. It calculates net income from gross salary considering various tax brackets, social security contributions, solidarity tax (Solidaritätszuschlag), and optional church tax.
**Current Version**: 0.2.0
**Supported Tax Years**: 2018-2026 (enacted law; 2026 preliminary), 2027-2032 (forecast data, regenerable via `scripts/generate_forecast.py`)
**Key Features**:- Calculate net income from gross salary (`calc_netto`)- Calculate required gross salary for desired net income (`calc_inverse_netto`)- Support for married couples (Ehegattensplitting), including dual-income households via `partner_salary`- Support for children (affects nursing insurance)- Optional church tax- Public health and pension insurance- West-German pension deduction
## Architecture
### Project Structure
```netto/├── netto/ # Main library code│ ├── __init__.py # Package initialization│ ├── main.py # Main API (calc_netto, calc_inverse_netto)│ ├── config.py # TaxConfig dataclass│ ├── data_loader.py # Data loader with Pydantic validation│ ├── taxes_income.py # Income tax calculations│ ├── taxes_other.py # Solidarity and church tax│ ├── taxes_children.py # Kindergeld and Günstigerprüfung│ └── social_security.py # Social security calculations├── data/ # Tax data (JSON files with validation)│ ├── tax_curves/ # Income tax brackets by year│ ├── social_security/ # Social security rates by year│ ├── soli/ # Solidarity tax parameters│ ├── pension_factors/ # Pension correction factors│ ├── deductions/ # Lump-sum deductions (Pauschbeträge) by year│ ├── children/ # Kindergeld and Kinderfreibetrag by year│ └── README.md # Data structure documentation├── scripts/ # Maintenance scripts (forecast data generator)├── test/ # Test suite (pytest)├── docs/ # Sphinx documentation├── examples/ # Usage examples└── .github/workflows/ # CI/CD pipelines```
### Core Components
#### 1. Configuration (`config.py`)- **TaxConfig dataclass**: Central configuration for all calculations - `year`: Tax year (2018-2032; 2027+ are forecasts) - `has_children`: Affects nursing insurance extra rate - `is_married`: Joint assessment (Ehegattensplitting): splitting tariff and doubled soli exemption threshold - `extra_health_insurance`: Total health Zusatzbeitrag; `None` (default) uses the year's official average from `data/social_security/` - `church_tax`: Church tax rate (default: 0.09, set to 0.0 for none)- Includes validation in `__post_init__`
#### 2. Tax Data (`data_loader.py`)**✅ REFACTORED TO STRUCTURED DATA**
Contains data loader with Pydantic validation for:- `tax_curve`: Progressive income tax brackets by year- `social_security_curve`: Social security limits and rates- `soli_curve`: Solidarity tax parameters- `pension_factors`: Pension deduction factors- `deductions`: Lump-sum deductions (Werbungskosten- and Sonderausgaben-Pauschbetrag) by year- `child_benefits`: Kindergeld and Kinderfreibetrag by year
**Benefits of Current Structure**:- JSON files in `data/` directory for easy editing- Pydantic schema validation ensures data integrity- Easy to audit changes via git diffs- Simple to extend to new years (just add new JSON files)- Clear separation between code and data
#### 3. Main API (`main.py`)
**calc_netto(salary, deductibles=0, verbose=False, config=None, partner_salary=0)**- Calculates net income from gross salary- `partner_salary`: spouse's gross salary for dual-income couples (requires `is_married=True`); social security is calculated per person, income tax jointly; returns household net income- Returns rounded float (2 decimal places)- Workflow: 1. Calculate deductible social security (`calc_deductible_social_security`, per earner) 2. Calculate taxable income (`calc_taxable_income`) 3. Calculate income tax via integration (`calc_income_tax_by_integration`) 4. Calculate soli, church tax, social security (per earner) 5. Return: salary (+ partner_salary) - all taxes and contributions
**calc_inverse_netto(desired_netto, deductibles=0, config=None, partner_salary=0)**- Calculates required gross salary for desired net income- With `partner_salary`, solves for the primary salary while keeping the partner salary fixed- Uses Newton's method for optimization (scipy.optimize.newton)- Returns rounded integer
#### 4. Tax Calculations
**Income Tax** (`taxes_income.py`):- Progressive tax curve with 4 brackets (0-3)- German tax formula implementation- Integration-based calculation for accuracy- Married couples: splitting tariff (2 × tax(income/2)), implemented by stretching the marginal rate curve in the integration method and by halving/doubling in the exact formula- Year-aware lump-sum deductions (Werbungskosten- and Sonderausgaben-Pauschbetrag) from `data/deductions/`, applied per earner / doubled for joint assessment
**Other Taxes** (`taxes_other.py`):- **Solidarity Tax (Soli)**: Reduced significantly in 2021 - Pre-2021: 5.5% on income tax above threshold - 2021+: Phased reduction, only affects high earners - Exemption threshold (Freigrenze) doubles for jointly assessed couples- **Church Tax**: Optional, typically 8-9% of income tax
**Social Security** (`social_security.py`):- Pension insurance (Rentenversicherung)- Unemployment insurance (Arbeitslosenversicherung)- Health insurance (Krankenversicherung)- Nursing care insurance (Pflegeversicherung) - Extra rate for childless individuals (Kinderlosenzuschlag)
## Development Guidelines
### Code Style- **Formatter & Linter**: Ruff (line length: 88) - Replaces Black, isort, and Flake8 with a single fast tool - Uses Black-compatible 88 character line length (industry standard) - Configuration in `pyproject.toml`- **Type Hints**: Use type hints for all public functions- **Docstrings**: NumPy-style docstrings with Parameters, Returns, Examples
### Testing**Framework**: pytest (migrated from unittest)
**Test Coverage**:- Target: >80% code coverage- CI runs pytest with coverage reporting to Codecov- Tests should cover: - Various salary ranges - Different configurations (married, children, church tax) - Edge cases (zero income, very high income) - Inverse calculations
### Python Version Support- **Minimum**: Python 3.10- **Tested**: 3.10, 3.11, 3.12, 3.13, 3.14- Uses modern Python features (dataclasses with slots, union types with `|`)
## Release 0.2.0 - Preparation Tasks
### Remaining Tasks
#### 1. Replace Forecast Data with Enacted Law (Ongoing)**Status**: 🔮 2027-2032 use forecast data
**Current State**:- ✅ 2018-2026: Complete with all constants (2026 preliminary)- 🔮 2027-2032: Forecast data from `scripts/generate_forecast.py`
**Required Data Sources**:- [BMF Tarifhistorie](https://www.bmf-steuerrechner.de/Tarifhistorie_Steuerrechner.pdf)- [BMF Lohnsteuerrechner](https://www.bmf-steuerrechner.de/)- [Social Security Rates](https://www.lohn-info.de/sozialversicherungsbeitraege2024.html)
**Tasks**:1. Monitor official sources for newly enacted tax data (yearly)2. Overwrite the forecast JSON files in `data/` with official values as they are enacted3. Verify calculations against official BMF calculators4. Re-run `scripts/generate_forecast.py` if forecast assumptions change (it regenerates 2027-2032)
**Tax Curve Constants Explanation**:The `const` values are polynomial coefficients used in German tax calculation:- Bracket 0: No constants (below basic allowance, 0% tax)- Bracket 1: [a, b] for linear progression zone- Bracket 2: [a, b, c] for first progression zone- Bracket 3: [a, b] for top tax rate
#### 2. Improve Error Handling (Medium Priority)**Status**: 📋 Planned
**Current Issues**:- Limited input validation- Generic error messages- No custom exception types
**Recommendation**:
**A. Custom Exception Hierarchy**:```python# In netto/exceptions.pyclass NettoError(Exception): """Base exception for netto library""" pass
class UnsupportedTaxYear(NettoError): """Tax year not supported""" pass
class InvalidSalary(NettoError): """Invalid salary value""" pass
class InvalidConfiguration(NettoError): """Invalid configuration""" pass```
**B. Enhanced Validation**:```pythondef calc_netto(salary: float, ...) -> float: if salary < 0: raise InvalidSalary(f"Salary must be non-negative, got {salary}")
if config.year not in SUPPORTED_YEARS: raise UnsupportedTaxYear( f"Year {config.year} not supported. " f"Supported years: {SUPPORTED_YEARS}" )
if deductibles < 0: raise ValueError(f"Deductibles must be non-negative, got {deductibles}")```
**C. Validation in TaxConfig**:- Already has good validation in `__post_init__`- Consider more specific exception types- Add helpful error messages with valid ranges
### Completed Tasks
The following tasks have been completed in v0.2.0:
- ✅ **ReadTheDocs Configuration**: Added `.readthedocs.yml` for proper documentation building- ✅ **Refactor const.py to Structured Data**: Migrated from hardcoded Python dictionaries to validated JSON files- ✅ **Migrate to Pytest**: Converted test suite from unittest to pytest- ✅ **Switch to Ruff**: Replaced Black, isort, and Flake8 with Ruff for faster linting and formatting
### Future Enhancements (Post 0.2.0)
**v0.3.0 - API Improvements:**- [ ] **Overloaded parameters for helper functions** - Allow functions to accept either `salary` OR calculated values (e.g., `taxable_income`) - Eliminates redundant parameter passing (currently need to pass `salary` multiple times) - Example: `get_marginal_tax_rate()` could accept either `salary` or `taxable_income` - Implementation approach: ```python def get_marginal_tax_rate( salary: float | None = None, taxable_income: float | None = None, config: TaxConfig | None = None ) -> float: if salary is not None: # Auto-calculate taxable_income from salary deductible_ss = calc_deductible_social_security(salary, config) taxable_income = calc_taxable_income(salary, deductible_ss) return _calculate_rate(taxable_income, config) ``` - Benefits: Cleaner API, less verbose for common use cases, still allows granular control - Apply to: `get_marginal_tax_rate()`, `calc_taxable_income()`, and similar functions
**Other enhancements:**- [x] Calculate support for children (Kindergeld/Kinderfreibetrag with Günstigerprüfung) — done in 0.2.0- [ ] Kinderfreibetrag-Übertragung for single parents; higher pre-2023 Kindergeld for 3rd+ children- [ ] Implement correct pension deductible for East Germany- [ ] Add support for self-employed individuals- [ ] Add support for capital gains tax (Kapitalertragsteuer)- [ ] Multi-year tax planning calculations
## Common Tasks
### Running Tests
```bash# First, install package in editable mode (required for imports to work)pip install -e .
# Run with pytest (use python -m to ensure correct environment)python -m pytest test/ -v
# Run with coveragepython -m pytest --cov=netto test/
# Run specific test filepython -m pytest test/test_main.py -v
# Alternative: Use pytest's import mode (like CI does)python -m pytest --import-mode=append test/```
**Important**: Always use `python -m pytest` (not just `pytest`) to ensure tests run in the same Python environment where you installed the package. This avoids `ModuleNotFoundError` when using UV or other tool managers.
### Building Documentation
```bashcd docs/make html# Open docs/_build/html/index.html in browser```
### Linting and Formatting
```bash# Format with ruffruff format .
# Lint with ruffruff check .
# Fix linting issues automaticallyruff check --fix .```
### Local Development
```bash# Install in development modepip install -e .
# Install with dev dependenciespip install -r requirements-dev.txt
# Set up pre-commit hooks (recommended)pre-commit install
# Run pre-commit on all files (optional, to test)pre-commit run --all-files
# Run examplespython examples/examples.py```
**Pre-commit hooks** automatically run ruff linting and formatting before each commit, preventing CI failures. This is highly recommended for all contributors.
### Updating Tax Data
**Current Process**:1. Create new JSON file in `data/tax_curves/YEAR.json` (copy and modify from previous year)2. Create new JSON file in `data/social_security/YEAR.json`3. Create new JSON file in `data/soli/YEAR.json`4. Create new JSON file in `data/pension_factors/YEAR.json`5. Create new JSON file in `data/deductions/YEAR.json`6. Find relevant data from official sources (BMF, lohn-info.de)7. Update JSON files with new year data8. Update validation in `config.py` to support the new year9. Add tests for new year10. Verify calculations against official BMF calculators
**Data Validation**:- All data is validated using Pydantic models in `data_loader.py`- Invalid data will raise validation errors on import- See `data/README.md` for detailed data structure documentation
### Release Process
See `RELEASE.md` for detailed instructions.
**Quick Checklist**:1. Update version in `pyproject.toml`2. Update `CHANGELOG.md`3. Run tests locally4. Build and verify: `python -m build && twine check dist/*`5. Commit and push6. Test on TestPyPI (via GitHub Actions)7. Create GitHub release with tag `vX.Y.Z`8. Automatic PyPI publish via trusted publishing
## Data Sources & References
### Official Sources- **Tax Calculation Formulas**: [BMF Tarifhistorie](https://www.bmf-steuerrechner.de/Tarifhistorie_Steuerrechner.pdf)- **Wage Tax Calculator**: [BMF Lohnsteuerrechner](https://www.bmf-steuerrechner.de/)- **Social Security Deductible**: [Vorsorgepauschale](https://www.lohn-info.de/vorsorgepauschale.html)- **Social Security Rates**: [Sozialversicherungsbeiträge](https://www.lohn-info.de/sozialversicherungsbeitraege2024.html)- **Solidarity Tax**: [Solidaritätszuschlag](https://www.lohn-info.de/solizuschlag.html)
### Verification Tools- [Taxable Income Calculator](https://udo-brechtel.de/mathe/est_gsv/reverse_zve_brutto.htm)- BMF official calculators (various years)
### Important Tax Law Changes
**2021**: Major solidarity tax (Soli) reduction- Changed from flat 5.5% to progressive phase-out- Only affects high earners (>~60k single, >~120k married)- Parameters: `start_taxable_income: 16956`, `start_fraction: 0.119`
**2022**: Nursing insurance extra rate increase- Childless extra rate increased from 0.25% to 0.35%
**2023-2025**: Progressive basic allowance increases- 2023: 10,909€- 2024: 11,605€- 2025: 12,086€
## Code Quality Standards
### Test Requirements- All public functions must have tests- Critical calculations should have verification tests against official calculators- Edge cases must be covered (0, negative, very large values)- Configuration combinations should be tested
### Documentation Requirements- All public functions must have NumPy-style docstrings- Include Examples section in docstrings- Keep README.md up to date with supported years- Update CHANGELOG.md for all releases
### Git Workflow- **Main branch**: `master` (protected)- **Feature branches**: `claude/feature-name-SESSION_ID`- **Pre-commit hooks**: HIGHLY RECOMMENDED - install with `pre-commit install` - Automatically runs ruff linting and formatting before each commit - Prevents CI failures by catching issues locally - Ensures consistent code quality across all commits- **Commit messages**: Conventional commits format - `feat:` for new features - `fix:` for bug fixes - `docs:` for documentation - `refactor:` for refactoring - `test:` for tests - `chore:` for maintenance - `style:` for code formatting/style changes
### CI/CD- **Build Workflow** (`workflow.yml`): Runs on every push - Lint with ruff (`ruff check .`) - Format check with ruff (`ruff format --check .`) - Test on Python 3.10-3.14 with pytest - Upload coverage to Codecov- **PyPI Publishing**: - TestPyPI: Manual trigger via GitHub Actions - PyPI: Automatic on GitHub release - Uses trusted publishing (OIDC, no API tokens)
## Troubleshooting
### Common Issues
**Issue**: Tests fail with import errors**Solution**: Install package in development mode: `pip install -e .`
**Issue**: Tax calculations don't match official calculators**Solution**:1. Verify correct year is set in config2. Check that all parameters match (married, church tax, etc.)3. Verify const values for that year are complete4. Check for rounding differences (netto rounds to 2 decimals)
**Issue**: Type errors with Python 3.10**Solution**: Ensure using `from __future__ import annotations` or use `Union[X, Y]` instead of `X | Y`
**Issue**: ReadTheDocs build fails**Solution**:1. Create `.readthedocs.yml` (see above)2. Verify `docs/requirements.txt` has all Sphinx dependencies3. Test locally: `cd docs && make html`
## Contact & Credits
**Author**: Martin Klein (hi@martinklein.co)**Repository**: https://github.com/0-k/netto**Documentation**: https://netto.readthedocs.io/**License**: MIT
## Quick Reference
### Key Functions```pythonfrom netto import calc_netto, calc_inverse_nettofrom netto.config import TaxConfig
# Basic usagenet = calc_netto(50000) # Uses defaults (2025, single, with church tax)
# Custom configurationconfig = TaxConfig(year=2024, is_married=True, has_children=True, church_tax=0.0)net = calc_netto(50000, config=config)
# Dual-income married couple (household net income)net = calc_netto(80000, config=config, partner_salary=50000)
# Inverse calculationgross = calc_inverse_netto(35000, config=config)
# With deductibles and verbose outputnet = calc_netto(50000, deductibles=2000, verbose=True, config=config)```
### Tax Year Support Matrix
| Year | Tax Curve | Social Security | Soli | Status ||------|-----------|-----------------|------|--------|| 2018 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2019 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2020 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2021 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2022 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2023 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2024 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2025 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Fully supported || 2026 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Preliminary official data || 2027-2032 | 🔮 Forecast | 🔮 Forecast | 🔮 Forecast | 🔮 Estimates (`scripts/generate_forecast.py`) |
---
**Last Updated**: 2026-07-12 (for release 0.2.0)**Document Version**: 1.3123456789101112131415161718192021MIT License
Copyright (c) 2025 Martin Klein
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123include data/**/*.jsoninclude data/**/*.mdinclude data/README.md123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242# netto
[](https://netto.readthedocs.io/en/latest/?badge=latest)[](https://pypi.python.org/pypi/netto)[](https://github.com/0-k/netto/actions/workflows/workflow.yml)[](https://codecov.io/gh/0-k/netto)[](LICENSE)[](https://github.com/astral-sh/ruff)
**netto** is a German income tax (Einkommensteuer) and social security (Sozialabgaben) calculator written in Python. It calculates net income from gross salary considering various tax brackets, social security contributions, solidarity tax (Solidaritätszuschlag), and optional church tax.
## Features
- **Calculate net income** from gross salary with `calc_netto()`- **Calculate required gross salary** for desired net income with `calc_inverse_netto()`- **Support for tax years 2018-2026**- **Married couples support** (Ehegattensplitting, including dual-income households)- **Children support**: Kindergeld and Kinderfreibetrag with automatic Günstigerprüfung, plus the nursing care insurance effect- **Optional church tax** (8-9%, configurable)- **Public health and pension insurance** calculations- **West-German pension deduction** (East German support planned)- **Type-safe configuration** with Pydantic validation- **Comprehensive documentation** on [ReadTheDocs](https://netto.readthedocs.io/)
## Installation
Install from PyPI using pip:
```bashpip install netto```
Requires Python 3.10 or higher.
## Quick Start
### Basic Usage
```pythonfrom netto import calc_netto
# Calculate net income from 50,000€ gross salary (uses defaults)net_income = calc_netto(50000)print(f"Net income: {net_income}€")# Output: Net income: 31674.4€```
### Custom Configuration
```pythonfrom netto import calc_netto, calc_inverse_netto, TaxConfig
# Configure for 2026, married couple, two children, no church taxconfig = TaxConfig( year=2026, is_married=True, num_children=2, # includes Kindergeld and the Günstigerprüfung church_tax=0.0, # Set to 0.09 for 9% church tax extra_health_insurance=0.017, # Your Krankenkasse's Zusatzbeitrag # (omit to use the official year average))
# Calculate net incomenet = calc_netto(50000, config=config)print(f"Net income: {net}€")
# Calculate required gross salary for desired net incomegross = calc_inverse_netto(35000, config=config)print(f"Required gross: {gross}€")```
### Dual-Income Married Couples
For jointly assessed couples where both partners work, pass the spouse'ssalary as `partner_salary`. Income tax is assessed jointly (Ehegattensplitting)while social security contributions are calculated per person:
```pythonfrom netto import calc_netto, calc_inverse_netto, TaxConfig
config = TaxConfig(year=2025, is_married=True, church_tax=0.0)
# Combined household net income for 80,000€ + 50,000€ gross salarieshousehold_net = calc_netto(80000, config=config, partner_salary=50000)print(f"Household net income: {household_net}€")
# Required primary salary for a desired household net income,# with the partner salary fixedgross = calc_inverse_netto(90000, config=config, partner_salary=50000)print(f"Required gross: {gross}€")```
### With Deductibles and Verbose Output
```pythonfrom netto import calc_netto, TaxConfig
config = TaxConfig(year=2024)
# Calculate with 2000€ deductibles and verbose outputnet = calc_netto( salary=60000, deductibles=2000, # e.g., professional expenses verbose=True, # Print detailed breakdown config=config)```
### Advanced: Using Helper Functions
For more granular control, you can use the intermediate calculation functions:
```pythonfrom netto import calc_taxable_income, calc_deductible_social_security, get_marginal_tax_rate
salary = 50000
# Calculate deductible social security contributionsdeductible_social_security = calc_deductible_social_security(salary)
# Calculate taxable incometaxable_income = calc_taxable_income( salary=salary, deductible_social_security=deductible_social_security)
# Get marginal tax rate for this income levelmarginal_rate = get_marginal_tax_rate(taxable_income)print(f"Marginal tax rate: {marginal_rate:.1%}")```
## Configuration
The `TaxConfig` dataclass provides type-safe configuration:
| Parameter | Type | Default | Description ||-----------|------|---------|-------------|| `year` | int | 2025 | Tax year (2018-2026 supported) || `is_married` | bool | False | Married status (Ehegattensplitting) || `has_children` | bool | False | Has (or ever had) children — removes the nursing insurance childless surcharge. Implied by `num_children > 0` || `num_children` | int | 0 | Children entitled to Kindergeld. When set, `calc_netto` includes Kindergeld and applies the Günstigerprüfung (Kindergeld vs. Kinderfreibetrag) || `church_tax` | float | 0.09 | Church tax rate (0.0-0.09, set to 0.0 for none) || `extra_health_insurance` | float \| None | None | Total health insurance Zusatzbeitrag. `None` uses the official year-specific average (e.g. 2.9% in 2026); set explicitly to match your Krankenkasse |
## Supported Tax Years
| Year | Status | Notes ||-----------|--------|-------|| 2018-2025 | Fully supported | Enacted tax law || 2026 | Fully supported | Preliminary official data || 2027-2032 | Forecast | Estimates for planning; see `data/README.md` for assumptions |
## Documentation
Full documentation is available at [netto.readthedocs.io](https://netto.readthedocs.io/).
## Data Sources
All tax calculations are based on official German government sources:
- **Tax Calculation Formulas**: [BMF Tarifhistorie](https://www.bmf-steuerrechner.de/javax.faces.resource/2025_1_14_Tarifhistorie_Steuerrechner.pdf.xhtml)- **Wage Tax Calculator**: [BMF Lohnsteuerrechner](https://www.bmf-steuerrechner.de/)- **Social Security Deductible**: [Vorsorgepauschale](https://www.lohn-info.de/vorsorgepauschale.html)- **Social Security Rates**: [Sozialversicherungsbeiträge](https://www.lohn-info.de/sozialversicherungsbeitraege2024.html)- **Solidarity Tax**: [Solidaritätszuschlag](https://www.lohn-info.de/solizuschlag.html)- **Taxable Income Calculator**: [Reverse Calculator](https://udo-brechtel.de/mathe/est_gsv/reverse_zve_brutto.htm)
## Development
### Setup
```bash# Clone the repositorygit clone https://github.com/0-k/netto.gitcd netto
# Install in development mode with dev dependenciespip install -e .pip install -r requirements-dev.txt
# Set up pre-commit hooks (recommended)pre-commit install```
Pre-commit hooks automatically run ruff linting and formatting before each commit, preventing CI failures.
### Running Tests
```bash# First-time setup: install package in editable modepip install -e .
# Run all tests with coveragepython -m pytest --cov=netto test/
# Run specific test filepython -m pytest test/test_main.py -v```
**Note**: Use `python -m pytest` (not just `pytest`) to ensure tests run in the correct Python environment where netto is installed.
### Code Quality
```bash# Format coderuff format .
# Lint coderuff check .
# Fix linting issues automaticallyruff check --fix .```
### Building Documentation
```bashcd docs/make html# Open docs/_build/html/index.html in your browser```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Credits
Created and maintained by Martin Klein (hi@martinklein.co).
**Repository**: https://github.com/0-k/netto**Documentation**: https://netto.readthedocs.io/**PyPI**: https://pypi.org/project/netto/
---
© 2025 Martin Klein123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214# Release Process for Netto
This document describes how to release a new version of Netto to PyPI.
## Prerequisites
### 1. Set up PyPI Trusted Publishing
The project uses PyPI's trusted publishing (OpenID Connect) which is more secure than API tokens. You need to configure this once:
#### For TestPyPI (recommended to test first):
1. Go to https://test.pypi.org and log in (create account if needed)2. Go to Account Settings → Publishing → Add a new pending publisher3. Fill in the form: - **PyPI Project Name**: `netto` - **Owner**: `0-k` (your GitHub username/org) - **Repository name**: `netto` - **Workflow name**: `publish_test.yml` - **Environment name**: `testpypi`4. Click "Add"
#### For PyPI (production):
1. Go to https://pypi.org and log in2. Go to Account Settings → Publishing → Add a new pending publisher3. Fill in the form: - **PyPI Project Name**: `netto` - **Owner**: `0-k` - **Repository name**: `netto` - **Workflow name**: `publish.yml` - **Environment name**: `pypi`4. Click "Add"
### 2. Create GitHub Environments
Create the required environments in your GitHub repository:
1. Go to your repository on GitHub2. Navigate to Settings → Environments3. Create two environments: - **testpypi** (for test releases) - **pypi** (for production releases)4. (Optional) Add protection rules to require approval before publishing
## Release Process
### Step 1: Update Version
Update the version number in `pyproject.toml`:
```bash# In pyproject.tomlversion = "X.Y.Z"```
### Step 2: Update CHANGELOG
Add release notes to `CHANGELOG.md` following the existing format (create if it doesn't exist):
```markdown## [X.Y.Z] - YYYY-MM-DD
### Added- New features
### Changed- Changes to existing functionality
### Fixed- Bug fixes
### Deprecated- Soon-to-be removed features
### Removed- Removed features
### Security- Security fixes```
### Step 3: Test the Build Locally
```bash# Install build toolspip install build twine
# Build the packagepython -m build
# Check the built packagetwine check dist/*
# Optionally, test install locallypip install dist/netto-X.Y.Z-py3-none-any.whl```
### Step 4: Commit and Push
```bashgit add pyproject.toml CHANGELOG.mdgit commit -m "chore: bump version to X.Y.Z"git push origin main```
### Step 5: Test on TestPyPI (Recommended)
1. Go to GitHub Actions2. Select "Publish to TestPyPI" workflow3. Click "Run workflow" → "Run workflow"4. Wait for the workflow to complete5. Test installing from TestPyPI: ```bash pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple netto ```
### Step 6: Create a GitHub Release
1. Go to your repository on GitHub2. Click "Releases" → "Create a new release"3. Click "Choose a tag" and create a new tag: `vX.Y.Z` (e.g., `v0.1.1`)4. Set the release title: `vX.Y.Z`5. Copy the relevant section from CHANGELOG.md into the release description6. Click "Publish release"
### Step 7: Automatic PyPI Publishing
Once you publish the release, the GitHub Action will automatically:1. Build the package2. Publish to PyPI
You can monitor the progress in the "Actions" tab.
### Step 8: Verify the Release
1. Check that the package appears on PyPI: https://pypi.org/project/netto/2. Test installing the package: ```bash pip install netto ```3. Verify the version: ```bash python -c "import netto; print(netto.__version__)" ```
## Troubleshooting
### Trusted Publishing Not Set Up
**Error**: `Error: Invalid or non-existent authentication information`
**Solution**: Make sure you've configured trusted publishing on PyPI/TestPyPI (see Prerequisites above).
### Environment Not Found
**Error**: `Environment not found`
**Solution**: Create the required environments in GitHub repository settings.
### Build Fails
**Error**: Build process fails during GitHub Action
**Solution**:1. Check the GitHub Actions logs2. Try building locally with `python -m build`3. Ensure all files are committed and pushed
### Package Already Exists
**Error**: `File already exists`
**Solution**: You cannot re-upload the same version. Increment the version number and try again.
## Version Numbering
Netto follows [Semantic Versioning](https://semver.org/):
- **MAJOR** version (X.0.0): Incompatible API changes- **MINOR** version (0.X.0): New functionality, backwards compatible- **PATCH** version (0.0.X): Bug fixes, backwards compatible
Examples:- `0.1.0` → `0.1.1`: Bug fix release- `0.1.0` → `0.2.0`: New features, backwards compatible- `0.9.0` → `1.0.0`: First stable release with API guarantees- `1.0.0` → `2.0.0`: Breaking changes to API
## Pre-releases
For alpha/beta releases, append to the version:
```version = "0.2.0a1" # Alpha releaseversion = "0.2.0b1" # Beta releaseversion = "0.2.0rc1" # Release candidate```
## Quick Reference
```bash# Complete release checklist1. Update version in pyproject.toml2. Update CHANGELOG.md3. python -m build4. twine check dist/*5. git commit -am "chore: bump version to X.Y.Z"6. git push7. Test on TestPyPI (via GitHub Actions)8. Create GitHub release with tag vX.Y.Z9. Automatic PyPI publish10. Verify on PyPI```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299# Tax and Social Security Data
This directory contains all tax and social security data used by the netto calculator in JSON format.
## Directory Structure
```data/├── tax_curves/ # Income tax curves by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2025.json├── social_security/ # Social security rates by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2025.json├── soli/ # Solidarity tax parameters by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2025.json├── pension_factors/ # Pension deduction factors by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2026.json├── deductions/ # Lump-sum deductions (Pauschbeträge) by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2032.json├── children/ # Kindergeld and Kinderfreibetrag by year│ ├── 2018.json│ ├── 2019.json│ ├── ...│ └── 2032.json└── README.md # This file```
## Data Format
### Tax Curves (`tax_curves/YEAR.json`)
Each file contains the progressive income tax brackets for a specific year:
```json{ "year": 2022, "brackets": { "0": { "step": 10347, "rate": 0.14, "const": null }, "1": { "step": 14926, "rate": 0.2397, "const": [1088.67, 1400] }, "2": { "step": 58596, "rate": 0.42, "const": [206.43, 2397, 869.32] }, "3": { "step": 277826, "rate": 0.45, "const": [9336.45, 17671.20] } }}```
**Fields:**- `year`: Tax year- `brackets`: Four brackets (0-3) representing German progressive tax system - `step`: Income threshold in EUR where this bracket starts - `rate`: Tax rate for this bracket (as decimal, e.g., 0.14 = 14%) - `const`: Polynomial coefficients used in German tax formula - Bracket 0: `null` (no tax below basic allowance) - Bracket 1: `[a, b]` - 2 coefficients - Bracket 2: `[a, b, c]` - 3 coefficients - Bracket 3: `[a, b]` - 2 coefficients
### Social Security (`social_security/YEAR.json`)
Each file contains social security contribution limits and rates:
```json{ "year": 2022, "pension": { "limit": 84600, "rate": 0.093 }, "unemployment": { "limit": 84600, "rate": 0.012 }, "health": { "limit": 58050, "rate": 0.073, "extra": 0.013 }, "nursing": { "limit": 58050, "rate": 0.01525, "extra": 0.0035 }}```
**Fields:**- `year`: Tax year- `pension/unemployment/health/nursing`: Contribution type - `limit`: Annual income limit in EUR (Beitragsbemessungsgrenze) - `rate`: Employee contribution rate (employer pays the same) - `extra` (health): Official average Zusatzbeitrag for the year (total; the employee pays half). Used when `TaxConfig.extra_health_insurance` is `None`; an explicit config value overrides it. - `extra` (nursing): Extra rate for childless individuals (Kinderlosenzuschlag)
### Solidarity Tax (`soli/YEAR.json`)
Each file contains solidarity tax (Solidaritätszuschlag) parameters for a specific year:
```json{ "year": 2022, "start_taxable_income": 16956, "start_fraction": 0.119, "end_rate": 0.055}```
**Fields:**- `year`: Tax year- `start_taxable_income`: Income threshold in EUR where soli starts- `start_fraction`: Fraction used for progressive phase-in- `end_rate`: Maximum soli rate (5.5%)
**Important Change in 2021:** Solidarity tax was significantly reduced. Before 2021, it applied to most taxpayers. From 2021 onward, it only affects high earners through a progressive phase-in mechanism.
### Pension Correction Factors (`pension_factors/YEAR.json`)
Each file contains pension deduction factor for West Germany for a specific year:
```json{ "year": 2022, "factor": 0.88}```
**Fields:**- `year`: Tax year- `factor`: Pension deduction factor (0.0 to 1.0)
**Note:** These factors increased by 4 percentage points per year until theJahressteuergesetz 2022 brought full deductibility (1.0) forward to 2023(originally scheduled for 2025).
### Lump-Sum Deductions (`deductions/YEAR.json`)
Each file contains the lump-sum deductions (Pauschbeträge) for a specific year:
```json{ "year": 2022, "werbungskosten_pauschbetrag": 1200, "sonderausgaben_pauschbetrag": 36}```
**Fields:**- `year`: Tax year- `werbungskosten_pauschbetrag`: Employee lump-sum deduction (Arbeitnehmer-Pauschbetrag) in EUR, granted per earner - 2018-2021: 1,000 € - 2022: 1,200 € (Steuerentlastungsgesetz 2022) - 2023 onwards: 1,230 €- `sonderausgaben_pauschbetrag`: Special expenses lump sum in EUR per person (36 €, doubled to 72 € for jointly assessed couples)
### Child Benefits (`children/YEAR.json`)
Each file contains the yearly child benefit amounts for a specific year:
```json{ "year": 2026, "kindergeld_per_child": 3108, "kinderfreibetrag_per_child": 9756}```
**Fields:**- `year`: Tax year- `kindergeld_per_child`: Yearly Kindergeld in EUR at the first/second-child rate (mid-year changes are averaged in, e.g. 2019). Simplifications: before 2023 the third and further children received slightly more; one-off Corona-Kinderboni (2020-2022) are not included.- `kinderfreibetrag_per_child`: Yearly child allowance in EUR for **both parents combined**, including the BEA allowance (Betreuungs-, Erziehungs- und Ausbildungsbedarf: 2,640 € until 2020, 2,928 € since 2021). Single parents receive half. The 2022 and 2024 values include the retroactive raises.
## Data Sources
All data should be sourced from official German government sources:
- **Tax formulas:** [BMF Tarifhistorie](https://www.bmf-steuerrechner.de/Tarifhistorie_Steuerrechner.pdf)- **Tax calculators:** [BMF Lohnsteuerrechner](https://www.bmf-steuerrechner.de/)- **Social security rates:** [Sozialversicherungsbeiträge](https://www.lohn-info.de/sozialversicherungsbeitraege2024.html)- **Soli:** [Solidaritätszuschlag](https://www.lohn-info.de/solizuschlag.html)
## Validation
All JSON data is validated using Pydantic models defined in `netto/data_loader.py`. The validation ensures:
- Correct data types (floats, integers, arrays)- Proper value ranges (e.g., rates between 0 and 1)- Required fields are present- Structural integrity (e.g., exactly 4 tax brackets)
## Adding New Years
To add tax data for a new year:
1. **Create tax curve file:** `tax_curves/YEAR.json` - Source data from BMF Tarifhistorie - Calculate `const` polynomial coefficients from official formulas
2. **Create social security file:** `social_security/YEAR.json` - Source limits (Beitragsbemessungsgrenzen) from official sources - Source rates from official announcements
3. **Create soli file:** `soli/YEAR.json` - Add year entry with updated thresholds
4. **Create pension factor file:** `pension_factors/YEAR.json` - Add year entry with factor (continues at 1.0 after 2025)
5. **Create deductions file:** `deductions/YEAR.json` - Add year entry with the current Pauschbeträge
6. **Create child benefits file:** `children/YEAR.json` - Add year entry with Kindergeld and Kinderfreibetrag (incl. BEA)
7. **Update validation in** `netto/config.py`: - Update year range validation
8. **Run tests:** - Verify calculations against official BMF calculator - Add test cases for new year
## Maintenance
- Data files are version controlled separately for easy auditing- Each change should reference the official source- Use conventional commit format: `data: update 2024 social security rates`- Verify calculations against official calculators before committing
## Forecast Years (2027-2032)
The data files for 2027-2032 are **estimates for planning purposes**, generatedby `scripts/generate_forecast.py` from the enacted 2026 values. Assumptions:
- **Tax brackets and soli threshold**: indexed by 2% per year (matching recent inflation-adjustment laws); the top bracket boundary stays frozen at 277,826 € as it has been since 2022. Polynomial coefficients are derived exactly from the bracket boundaries.- **Contribution ceilings** (Beitragsbemessungsgrenzen): +3% per year (long-run wage growth), rounded to the official grid.- **Pension rate**: follows the official Rentenversicherungsbericht projection (stable 18.6% until 2027, rising to ~20% by the early 2030s).- **Nursing rate**: moderate increases reflecting projected financing gaps (3.6% → 4.0% total by 2030).- **Average health Zusatzbeitrag**: keeps rising by 0.1 percentage points per year (2.9% in 2026 → 3.5% by 2032), continuing the recent trend.- **Health base (14.6%) and unemployment (2.6%) rates, Pauschbeträge**: flat.- **Kindergeld and Kinderfreibetrag**: indexed by 2% per year, rounded so monthly amounts stay whole euros.
To change assumptions, edit the constants at the top of`scripts/generate_forecast.py` and re-run it. Replace forecast files withofficial values as they are enacted.
## Current Status
| Year | Tax Curve | Social Security | Soli | Pension Factor | Deductions | Status ||------|-----------|-----------------|------|----------------|------------|--------|| 2018-2025 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Complete | Fully supported || 2026 | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Complete | ✅ Complete | Preliminary official data || 2027-2032 | 🔮 Forecast | 🔮 Forecast | 🔮 Forecast | 🔮 Forecast | 🔮 Forecast | Estimates (see above) |12345{ "year": 2018, "kindergeld_per_child": 2328, "kinderfreibetrag_per_child": 7428}12345{ "year": 2019, "kindergeld_per_child": 2388, "kinderfreibetrag_per_child": 7620}12345{ "year": 2020, "kindergeld_per_child": 2448, "kinderfreibetrag_per_child": 7812}12345{ "year": 2021, "kindergeld_per_child": 2628, "kinderfreibetrag_per_child": 8388}12345{ "year": 2022, "kindergeld_per_child": 2628, "kinderfreibetrag_per_child": 8548}12345{ "year": 2023, "kindergeld_per_child": 3000, "kinderfreibetrag_per_child": 8952}12345{ "year": 2024, "kindergeld_per_child": 3000, "kinderfreibetrag_per_child": 9312}12345{ "year": 2025, "kindergeld_per_child": 3060, "kinderfreibetrag_per_child": 9600}12345{ "year": 2026, "kindergeld_per_child": 3108, "kinderfreibetrag_per_child": 9756}12345{ "year": 2027, "kindergeld_per_child": 3168, "kinderfreibetrag_per_child": 9948}12345{ "year": 2028, "kindergeld_per_child": 3228, "kinderfreibetrag_per_child": 10152}12345{ "year": 2029, "kindergeld_per_child": 3288, "kinderfreibetrag_per_child": 10356}12345{ "year": 2030, "kindergeld_per_child": 3348, "kinderfreibetrag_per_child": 10560}12345{ "year": 2031, "kindergeld_per_child": 3420, "kinderfreibetrag_per_child": 10776}12345{ "year": 2032, "kindergeld_per_child": 3492, "kinderfreibetrag_per_child": 10992}12345{ "year": 2018, "werbungskosten_pauschbetrag": 1000, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2019, "werbungskosten_pauschbetrag": 1000, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2020, "werbungskosten_pauschbetrag": 1000, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2021, "werbungskosten_pauschbetrag": 1000, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2022, "werbungskosten_pauschbetrag": 1200, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2023, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2024, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2025, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2026, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2027, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2028, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2029, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2030, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2031, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}12345{ "year": 2032, "werbungskosten_pauschbetrag": 1230, "sonderausgaben_pauschbetrag": 36}.gitattributesAdded
README.mdAdded+142
assets/mark.svgAdded
programgen_harbor/__init__.pyAdded+5
programgen_harbor/environment.pyAdded+365
programgen_harbor/reference_client.pyAdded+676
tasks/data/forward/0-k__netto.1b47785/environment/DockerfileAdded+26
tasks/data/forward/0-k__netto.1b47785/environment/Dockerfile.inferenceAdded+26
tasks/data/forward/0-k__netto.1b47785/environment/build_env.shAdded+10
tasks/data/forward/0-k__netto.1b47785/environment/pre_cleanup.shAdded+114
tasks/data/forward/0-k__netto.1b47785/environment/repo/.gitignoreAdded+134
tasks/data/forward/0-k__netto.1b47785/environment/repo/.pre-commit-config.yamlAdded+12
tasks/data/forward/0-k__netto.1b47785/environment/repo/.readthedocs.ymlAdded+18
tasks/data/forward/0-k__netto.1b47785/environment/repo/CHANGELOG.mdAdded+217
tasks/data/forward/0-k__netto.1b47785/environment/repo/CLAUDE.mdAdded+509
tasks/data/forward/0-k__netto.1b47785/environment/repo/LICENSEAdded+21
tasks/data/forward/0-k__netto.1b47785/environment/repo/MANIFEST.inAdded+3
tasks/data/forward/0-k__netto.1b47785/environment/repo/README.mdAdded+242
tasks/data/forward/0-k__netto.1b47785/environment/repo/RELEASE.mdAdded+214
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/README.mdAdded+299
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2018.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2019.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2020.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2021.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2022.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2023.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2024.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2025.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2026.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2027.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2028.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2029.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2030.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2031.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/children/2032.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2018.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2019.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2020.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2021.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2022.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2023.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2024.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2025.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2026.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2027.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2028.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2029.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2030.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2031.jsonAdded+5
tasks/data/forward/0-k__netto.1b47785/environment/repo/data/deductions/2032.jsonAdded+5