xithead 1.2.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (659) hide show
  1. package/.actrc +14 -0
  2. package/.actrc.local.example +15 -0
  3. package/.changelog.md +2 -0
  4. package/.claude/agents/academic-anthropologist.md +125 -0
  5. package/.claude/agents/academic-geographer.md +127 -0
  6. package/.claude/agents/academic-historian.md +123 -0
  7. package/.claude/agents/academic-narratologist.md +118 -0
  8. package/.claude/agents/academic-psychologist.md +118 -0
  9. package/.claude/agents/academic-statistician.md +144 -0
  10. package/.claude/agents/accounts-payable-agent.md +205 -0
  11. package/.claude/agents/agentic-identity-trust.md +394 -0
  12. package/.claude/agents/agents-orchestrator.md +367 -0
  13. package/.claude/agents/automation-governance-architect.md +216 -0
  14. package/.claude/agents/blender-addon-engineer.md +243 -0
  15. package/.claude/agents/business-strategist.md +488 -0
  16. package/.claude/agents/change-management-consultant.md +497 -0
  17. package/.claude/agents/chief-financial-officer.md +388 -0
  18. package/.claude/agents/corporate-training-designer.md +192 -0
  19. package/.claude/agents/customer-service.md +398 -0
  20. package/.claude/agents/customer-success-manager.md +460 -0
  21. package/.claude/agents/data-consolidation-agent.md +60 -0
  22. package/.claude/agents/data-privacy-officer.md +412 -0
  23. package/.claude/agents/design-brand-guardian.md +322 -0
  24. package/.claude/agents/design-image-prompt-engineer.md +236 -0
  25. package/.claude/agents/design-inclusive-visuals-specialist.md +73 -0
  26. package/.claude/agents/design-persona-walkthrough.md +272 -0
  27. package/.claude/agents/design-ui-designer.md +386 -0
  28. package/.claude/agents/design-ui-finish-gate-reviewer.md +217 -0
  29. package/.claude/agents/design-ux-architect.md +482 -0
  30. package/.claude/agents/design-ux-researcher.md +329 -0
  31. package/.claude/agents/design-visual-storyteller.md +149 -0
  32. package/.claude/agents/design-whimsy-injector.md +460 -0
  33. package/.claude/agents/economy-designer.md +156 -0
  34. package/.claude/agents/engineering-ai-data-remediation-engineer.md +211 -0
  35. package/.claude/agents/engineering-ai-engineer.md +146 -0
  36. package/.claude/agents/engineering-api-platform-engineer.md +181 -0
  37. package/.claude/agents/engineering-ats-validator-architect.md +383 -0
  38. package/.claude/agents/engineering-autonomous-optimization-architect.md +121 -0
  39. package/.claude/agents/engineering-backend-architect.md +255 -0
  40. package/.claude/agents/engineering-china-network-engineer.md +252 -0
  41. package/.claude/agents/engineering-cms-developer.md +536 -0
  42. package/.claude/agents/engineering-code-reviewer.md +76 -0
  43. package/.claude/agents/engineering-codebase-onboarding-engineer.md +173 -0
  44. package/.claude/agents/engineering-data-engineer.md +349 -0
  45. package/.claude/agents/engineering-data-visualization-engineer.md +151 -0
  46. package/.claude/agents/engineering-database-optimizer.md +188 -0
  47. package/.claude/agents/engineering-database-reliability-engineer.md +201 -0
  48. package/.claude/agents/engineering-desktop-app-engineer.md +209 -0
  49. package/.claude/agents/engineering-developer-tooling-engineer.md +153 -0
  50. package/.claude/agents/engineering-devops-automator.md +385 -0
  51. package/.claude/agents/engineering-drupal-performance.md +347 -0
  52. package/.claude/agents/engineering-drupal-shopping-cart.md +360 -0
  53. package/.claude/agents/engineering-electrical-engineer.md +575 -0
  54. package/.claude/agents/engineering-email-intelligence-engineer.md +390 -0
  55. package/.claude/agents/engineering-embedded-firmware-engineer.md +196 -0
  56. package/.claude/agents/engineering-feishu-integration-developer.md +606 -0
  57. package/.claude/agents/engineering-filament-optimization-specialist.md +283 -0
  58. package/.claude/agents/engineering-finops-engineer.md +164 -0
  59. package/.claude/agents/engineering-frontend-developer.md +257 -0
  60. package/.claude/agents/engineering-gaussdb-expert.md +334 -0
  61. package/.claude/agents/engineering-git-workflow-master.md +98 -0
  62. package/.claude/agents/engineering-i18n-engineer.md +214 -0
  63. package/.claude/agents/engineering-identity-access-engineer.md +217 -0
  64. package/.claude/agents/engineering-incident-response-commander.md +444 -0
  65. package/.claude/agents/engineering-iot-fleet-engineer.md +148 -0
  66. package/.claude/agents/engineering-it-service-manager.md +561 -0
  67. package/.claude/agents/engineering-knowledge-graph-engineer.md +372 -0
  68. package/.claude/agents/engineering-llm-post-training-engineer.md +166 -0
  69. package/.claude/agents/engineering-minimal-change-engineer.md +207 -0
  70. package/.claude/agents/engineering-mobile-app-builder.md +493 -0
  71. package/.claude/agents/engineering-mobile-release-engineer.md +164 -0
  72. package/.claude/agents/engineering-multi-agent-systems-architect.md +600 -0
  73. package/.claude/agents/engineering-network-engineer.md +245 -0
  74. package/.claude/agents/engineering-orgscript-engineer.md +113 -0
  75. package/.claude/agents/engineering-payments-billing-engineer.md +228 -0
  76. package/.claude/agents/engineering-pdf-engine-architect.md +696 -0
  77. package/.claude/agents/engineering-platform-engineer.md +270 -0
  78. package/.claude/agents/engineering-privacy-engineer.md +152 -0
  79. package/.claude/agents/engineering-prompt-engineer.md +209 -0
  80. package/.claude/agents/engineering-rag-pipeline-engineer.md +450 -0
  81. package/.claude/agents/engineering-rapid-prototyper.md +466 -0
  82. package/.claude/agents/engineering-realtime-collaboration-engineer.md +200 -0
  83. package/.claude/agents/engineering-rust-refactoring-specialist.md +313 -0
  84. package/.claude/agents/engineering-search-relevance-engineer.md +237 -0
  85. package/.claude/agents/engineering-section-508-specialist.md +339 -0
  86. package/.claude/agents/engineering-senior-developer.md +176 -0
  87. package/.claude/agents/engineering-servicenow-developer-mentor.md +180 -0
  88. package/.claude/agents/engineering-software-architect.md +112 -0
  89. package/.claude/agents/engineering-solidity-smart-contract-engineer.md +522 -0
  90. package/.claude/agents/engineering-sre.md +90 -0
  91. package/.claude/agents/engineering-technical-writer.md +393 -0
  92. package/.claude/agents/engineering-universal-document-compiler.md +370 -0
  93. package/.claude/agents/engineering-uswds-developer.md +340 -0
  94. package/.claude/agents/engineering-video-streaming-engineer.md +151 -0
  95. package/.claude/agents/engineering-voice-ai-integration-engineer.md +584 -0
  96. package/.claude/agents/engineering-webassembly-engineer.md +153 -0
  97. package/.claude/agents/engineering-wechat-mini-program-developer.md +356 -0
  98. package/.claude/agents/engineering-wordpress-performance.md +346 -0
  99. package/.claude/agents/engineering-wordpress-shopping-cart.md +346 -0
  100. package/.claude/agents/esg-sustainability-officer.md +396 -0
  101. package/.claude/agents/finance-bookkeeper-controller.md +260 -0
  102. package/.claude/agents/finance-financial-analyst.md +234 -0
  103. package/.claude/agents/finance-fpa-analyst.md +263 -0
  104. package/.claude/agents/finance-investment-researcher.md +272 -0
  105. package/.claude/agents/finance-tax-strategist.md +239 -0
  106. package/.claude/agents/game-audio-engineer.md +264 -0
  107. package/.claude/agents/game-designer.md +167 -0
  108. package/.claude/agents/gis-3d-scene-developer.md +111 -0
  109. package/.claude/agents/gis-analyst.md +91 -0
  110. package/.claude/agents/gis-bim-specialist.md +108 -0
  111. package/.claude/agents/gis-cartography-designer.md +150 -0
  112. package/.claude/agents/gis-drone-reality-mapping.md +120 -0
  113. package/.claude/agents/gis-geoai-ml-engineer.md +105 -0
  114. package/.claude/agents/gis-geoprocessing-specialist.md +97 -0
  115. package/.claude/agents/gis-qa-engineer.md +133 -0
  116. package/.claude/agents/gis-solution-engineer.md +101 -0
  117. package/.claude/agents/gis-spatial-data-engineer.md +97 -0
  118. package/.claude/agents/gis-spatial-data-scientist.md +111 -0
  119. package/.claude/agents/gis-technical-consultant.md +86 -0
  120. package/.claude/agents/gis-web-gis-developer.md +108 -0
  121. package/.claude/agents/godot-gameplay-scripter.md +338 -0
  122. package/.claude/agents/godot-multiplayer-engineer.md +301 -0
  123. package/.claude/agents/godot-shader-developer.md +267 -0
  124. package/.claude/agents/government-digital-presales-consultant.md +363 -0
  125. package/.claude/agents/grant-writer.md +511 -0
  126. package/.claude/agents/healthcare-aging-parent-care-companion.md +414 -0
  127. package/.claude/agents/healthcare-clinical-evidence-agent.md +231 -0
  128. package/.claude/agents/healthcare-customer-service.md +389 -0
  129. package/.claude/agents/healthcare-innovation-strategist.md +433 -0
  130. package/.claude/agents/healthcare-marketing-compliance.md +395 -0
  131. package/.claude/agents/healthcare-sovereign-health-systems-agent.md +312 -0
  132. package/.claude/agents/hospitality-guest-services.md +603 -0
  133. package/.claude/agents/hr-onboarding.md +451 -0
  134. package/.claude/agents/identity-graph-operator.md +303 -0
  135. package/.claude/agents/language-translator.md +264 -0
  136. package/.claude/agents/legal-billing-time-tracking.md +569 -0
  137. package/.claude/agents/legal-client-intake.md +492 -0
  138. package/.claude/agents/legal-document-review.md +454 -0
  139. package/.claude/agents/level-designer.md +208 -0
  140. package/.claude/agents/loan-officer-assistant.md +555 -0
  141. package/.claude/agents/lsp-index-engineer.md +320 -0
  142. package/.claude/agents/ma-integration-manager.md +427 -0
  143. package/.claude/agents/macos-spatial-metal-engineer.md +337 -0
  144. package/.claude/agents/marketing-aeo-foundations.md +264 -0
  145. package/.claude/agents/marketing-agentic-search-optimizer.md +279 -0
  146. package/.claude/agents/marketing-ai-citation-strategist.md +172 -0
  147. package/.claude/agents/marketing-app-store-optimizer.md +321 -0
  148. package/.claude/agents/marketing-baidu-seo-specialist.md +226 -0
  149. package/.claude/agents/marketing-bilibili-content-strategist.md +199 -0
  150. package/.claude/agents/marketing-book-co-author.md +110 -0
  151. package/.claude/agents/marketing-carousel-growth-engine.md +204 -0
  152. package/.claude/agents/marketing-china-ecommerce-operator.md +283 -0
  153. package/.claude/agents/marketing-china-market-localization-strategist.md +283 -0
  154. package/.claude/agents/marketing-content-creator.md +54 -0
  155. package/.claude/agents/marketing-cross-border-ecommerce.md +259 -0
  156. package/.claude/agents/marketing-developer-community-builder.md +285 -0
  157. package/.claude/agents/marketing-douyin-strategist.md +149 -0
  158. package/.claude/agents/marketing-email-strategist.md +249 -0
  159. package/.claude/agents/marketing-global-podcast-strategist.md +206 -0
  160. package/.claude/agents/marketing-growth-hacker.md +54 -0
  161. package/.claude/agents/marketing-instagram-curator.md +113 -0
  162. package/.claude/agents/marketing-kuaishou-strategist.md +223 -0
  163. package/.claude/agents/marketing-linkedin-content-creator.md +214 -0
  164. package/.claude/agents/marketing-livestream-commerce-coach.md +305 -0
  165. package/.claude/agents/marketing-multi-platform-publisher.md +217 -0
  166. package/.claude/agents/marketing-podcast-strategist.md +277 -0
  167. package/.claude/agents/marketing-pr-communications-manager.md +473 -0
  168. package/.claude/agents/marketing-private-domain-operator.md +308 -0
  169. package/.claude/agents/marketing-reddit-community-builder.md +123 -0
  170. package/.claude/agents/marketing-seo-specialist.md +370 -0
  171. package/.claude/agents/marketing-short-video-editing-coach.md +412 -0
  172. package/.claude/agents/marketing-social-media-strategist.md +125 -0
  173. package/.claude/agents/marketing-tiktok-strategist.md +125 -0
  174. package/.claude/agents/marketing-twitter-engager.md +126 -0
  175. package/.claude/agents/marketing-video-optimization-specialist.md +119 -0
  176. package/.claude/agents/marketing-wechat-official-account.md +145 -0
  177. package/.claude/agents/marketing-weibo-strategist.md +240 -0
  178. package/.claude/agents/marketing-x-twitter-intelligence-analyst.md +161 -0
  179. package/.claude/agents/marketing-xiaohongshu-specialist.md +138 -0
  180. package/.claude/agents/marketing-zhihu-strategist.md +162 -0
  181. package/.claude/agents/medical-billing-coding-specialist.md +491 -0
  182. package/.claude/agents/narrative-designer.md +243 -0
  183. package/.claude/agents/operations-manager.md +399 -0
  184. package/.claude/agents/organizational-psychologist.md +391 -0
  185. package/.claude/agents/paid-media-auditor.md +71 -0
  186. package/.claude/agents/paid-media-creative-strategist.md +71 -0
  187. package/.claude/agents/paid-media-paid-social-strategist.md +71 -0
  188. package/.claude/agents/paid-media-ppc-strategist.md +71 -0
  189. package/.claude/agents/paid-media-programmatic-buyer.md +71 -0
  190. package/.claude/agents/paid-media-search-query-analyst.md +71 -0
  191. package/.claude/agents/paid-media-tracking-specialist.md +71 -0
  192. package/.claude/agents/personal-growth-mentor.md +159 -0
  193. package/.claude/agents/product-behavioral-nudge-engine.md +83 -0
  194. package/.claude/agents/product-dx-engineer.md +332 -0
  195. package/.claude/agents/product-feedback-synthesizer.md +119 -0
  196. package/.claude/agents/product-manager.md +469 -0
  197. package/.claude/agents/product-sprint-prioritizer.md +154 -0
  198. package/.claude/agents/product-trend-researcher.md +159 -0
  199. package/.claude/agents/project-management-experiment-tracker.md +198 -0
  200. package/.claude/agents/project-management-jira-workflow-steward.md +233 -0
  201. package/.claude/agents/project-management-meeting-notes-specialist.md +95 -0
  202. package/.claude/agents/project-management-project-shepherd.md +194 -0
  203. package/.claude/agents/project-management-studio-operations.md +200 -0
  204. package/.claude/agents/project-management-studio-producer.md +203 -0
  205. package/.claude/agents/project-manager-senior.md +135 -0
  206. package/.claude/agents/real-estate-buyer-seller.md +596 -0
  207. package/.claude/agents/recruitment-specialist.md +515 -0
  208. package/.claude/agents/report-distribution-agent.md +65 -0
  209. package/.claude/agents/research-synthesist.md +136 -0
  210. package/.claude/agents/resume-tailor.md +230 -0
  211. package/.claude/agents/retail-customer-returns.md +566 -0
  212. package/.claude/agents/roblox-avatar-creator.md +297 -0
  213. package/.claude/agents/roblox-experience-designer.md +306 -0
  214. package/.claude/agents/roblox-systems-scripter.md +332 -0
  215. package/.claude/agents/sales-account-strategist.md +227 -0
  216. package/.claude/agents/sales-coach.md +271 -0
  217. package/.claude/agents/sales-data-extraction-agent.md +67 -0
  218. package/.claude/agents/sales-deal-strategist.md +180 -0
  219. package/.claude/agents/sales-discovery-coach.md +225 -0
  220. package/.claude/agents/sales-engineer.md +182 -0
  221. package/.claude/agents/sales-offer-lead-gen-strategist.md +257 -0
  222. package/.claude/agents/sales-outbound-strategist.md +201 -0
  223. package/.claude/agents/sales-outreach.md +425 -0
  224. package/.claude/agents/sales-pipeline-analyst.md +267 -0
  225. package/.claude/agents/sales-proposal-strategist.md +217 -0
  226. package/.claude/agents/security-ai-generated-code-auditor.md +207 -0
  227. package/.claude/agents/security-appsec-engineer.md +536 -0
  228. package/.claude/agents/security-architect.md +307 -0
  229. package/.claude/agents/security-blockchain-security-auditor.md +482 -0
  230. package/.claude/agents/security-cloud-security-architect.md +576 -0
  231. package/.claude/agents/security-compliance-auditor.md +158 -0
  232. package/.claude/agents/security-incident-responder.md +450 -0
  233. package/.claude/agents/security-penetration-tester.md +399 -0
  234. package/.claude/agents/security-secrets-credential-engineer.md +189 -0
  235. package/.claude/agents/security-senior-secops.md +760 -0
  236. package/.claude/agents/security-threat-detection-engineer.md +553 -0
  237. package/.claude/agents/security-threat-intelligence-analyst.md +661 -0
  238. package/.claude/agents/specialized-chief-of-staff.md +279 -0
  239. package/.claude/agents/specialized-civil-engineer.md +356 -0
  240. package/.claude/agents/specialized-codebase-archaeologist.md +341 -0
  241. package/.claude/agents/specialized-cultural-intelligence-strategist.md +88 -0
  242. package/.claude/agents/specialized-developer-advocate.md +317 -0
  243. package/.claude/agents/specialized-document-generator.md +55 -0
  244. package/.claude/agents/specialized-fedramp-rmf-compliance.md +378 -0
  245. package/.claude/agents/specialized-focus-music-architect.md +175 -0
  246. package/.claude/agents/specialized-french-consulting-market.md +194 -0
  247. package/.claude/agents/specialized-korean-business-navigator.md +216 -0
  248. package/.claude/agents/specialized-master-plan-architect.md +157 -0
  249. package/.claude/agents/specialized-mcp-builder.md +260 -0
  250. package/.claude/agents/specialized-model-qa.md +528 -0
  251. package/.claude/agents/specialized-pricing-analyst.md +243 -0
  252. package/.claude/agents/specialized-salesforce-architect.md +182 -0
  253. package/.claude/agents/specialized-strategy-duel-agent.md +130 -0
  254. package/.claude/agents/specialized-workflow-architect.md +597 -0
  255. package/.claude/agents/study-abroad-advisor.md +282 -0
  256. package/.claude/agents/supply-chain-strategist.md +591 -0
  257. package/.claude/agents/support-analytics-reporter.md +387 -0
  258. package/.claude/agents/support-executive-summary-generator.md +212 -0
  259. package/.claude/agents/support-finance-tracker.md +480 -0
  260. package/.claude/agents/support-infrastructure-maintainer.md +628 -0
  261. package/.claude/agents/support-legal-compliance-checker.md +591 -0
  262. package/.claude/agents/support-support-responder.md +607 -0
  263. package/.claude/agents/technical-artist.md +233 -0
  264. package/.claude/agents/terminal-integration-specialist.md +70 -0
  265. package/.claude/agents/testing-accessibility-auditor.md +327 -0
  266. package/.claude/agents/testing-api-tester.md +334 -0
  267. package/.claude/agents/testing-evidence-collector.md +210 -0
  268. package/.claude/agents/testing-performance-benchmarker.md +283 -0
  269. package/.claude/agents/testing-reality-checker.md +249 -0
  270. package/.claude/agents/testing-test-automation-engineer.md +196 -0
  271. package/.claude/agents/testing-test-results-analyzer.md +330 -0
  272. package/.claude/agents/testing-tool-evaluator.md +416 -0
  273. package/.claude/agents/testing-workflow-optimizer.md +463 -0
  274. package/.claude/agents/unity-architect.md +271 -0
  275. package/.claude/agents/unity-editor-tool-developer.md +310 -0
  276. package/.claude/agents/unity-multiplayer-engineer.md +323 -0
  277. package/.claude/agents/unity-shader-graph-artist.md +269 -0
  278. package/.claude/agents/unreal-multiplayer-architect.md +364 -0
  279. package/.claude/agents/unreal-systems-engineer.md +322 -0
  280. package/.claude/agents/unreal-technical-artist.md +256 -0
  281. package/.claude/agents/unreal-world-builder.md +273 -0
  282. package/.claude/agents/visionos-spatial-engineer.md +54 -0
  283. package/.claude/agents/xr-cockpit-interaction-specialist.md +32 -0
  284. package/.claude/agents/xr-immersive-developer.md +32 -0
  285. package/.claude/agents/xr-interface-architect.md +32 -0
  286. package/.claude/agents/zk-steward.md +211 -0
  287. package/.claude-plugin/marketplace.json +30 -0
  288. package/.commitlintrc.json +26 -0
  289. package/.devcontainer/Dockerfile +24 -0
  290. package/.devcontainer/devcontainer.json +70 -0
  291. package/.devcontainer/docker-compose.memory.yml +42 -0
  292. package/.devcontainer/memory-stack/devcontainer.json +84 -0
  293. package/.devcontainer/post-create.sh +83 -0
  294. package/.dockerignore +23 -0
  295. package/.env.act.example +15 -0
  296. package/.env.example +171 -0
  297. package/.eslintrc.json +16 -0
  298. package/.git-blame-ignore-revs +10 -0
  299. package/.gitattributes +2 -0
  300. package/.gitguardian.yaml +50 -0
  301. package/.githooks/pre-commit +6 -0
  302. package/.pre-commit-config.yaml +30 -0
  303. package/.release-please-config-xithead.json +22 -0
  304. package/.release-please-config.json +44 -0
  305. package/.release-please-manifest-xithead.json +3 -0
  306. package/.release-please-manifest.json +3 -0
  307. package/CODE_OF_CONDUCT.md +133 -0
  308. package/CONTRIBUTING.md +133 -0
  309. package/Cargo.lock +5557 -0
  310. package/Cargo.toml +121 -0
  311. package/Dockerfile +38 -0
  312. package/Dockerfile.proxy +48 -0
  313. package/ENTERPRISE.md +5 -0
  314. package/FEATURES_ADVANCED.md +311 -0
  315. package/Headroom-2.gif +0 -0
  316. package/HeadroomDemo-Fast.gif +0 -0
  317. package/MANIFEST.in +4 -0
  318. package/MODERNIZATION_GUIDE.md +358 -0
  319. package/Makefile +140 -0
  320. package/NOTICE +43 -0
  321. package/NPM_TOKEN_SETUP.md +81 -0
  322. package/PR.md +170 -0
  323. package/PUBLISH.md +77 -0
  324. package/README.md +58 -137
  325. package/README_FRONTEND.md +196 -0
  326. package/REALIGNMENT/00-overview.md +53 -0
  327. package/REALIGNMENT/01-bug-list.md +421 -0
  328. package/REALIGNMENT/02-architecture.md +322 -0
  329. package/REALIGNMENT/03-phase-A-lockdown.md +420 -0
  330. package/REALIGNMENT/04-phase-B-live-zone.md +470 -0
  331. package/REALIGNMENT/05-phase-C-rust-proxy.md +329 -0
  332. package/REALIGNMENT/06-phase-D-bedrock-vertex.md +222 -0
  333. package/REALIGNMENT/07-phase-E-cache-stabilization.md +338 -0
  334. package/REALIGNMENT/08-phase-F-auth-mode.md +254 -0
  335. package/REALIGNMENT/09-phase-G-rtk-observability.md +194 -0
  336. package/REALIGNMENT/10-phase-H-python-retirement.md +214 -0
  337. package/REALIGNMENT/11-phase-I-test-infra.md +385 -0
  338. package/REALIGNMENT/12-decisions-needed.md +196 -0
  339. package/REALIGNMENT/INDEX.md +82 -0
  340. package/REFACTORING_CAMPAIGN.md +277 -0
  341. package/RESTRUCTURE_PLAN.md +100 -0
  342. package/RUST_DEV.md +361 -0
  343. package/SECURITY.md +65 -0
  344. package/SETUP_AUTO_PUBLISH.md +164 -0
  345. package/TESTING-copilot-subscription.md +153 -0
  346. package/app/api/config/route.ts +22 -0
  347. package/app/api/export/route.ts +83 -0
  348. package/app/api/models/route.ts +12 -0
  349. package/app/api/stats/route.ts +46 -0
  350. package/app/dashboard/page.tsx +445 -0
  351. package/app/globals.css +35 -0
  352. package/app/installation/page.tsx +293 -0
  353. package/app/layout.tsx +35 -0
  354. package/app/master-design-system.css +2076 -0
  355. package/app/master-design-system.source.css +8 -0
  356. package/app/page.tsx +187 -0
  357. package/app/rechtliches/agb/page.tsx +165 -0
  358. package/app/rechtliches/datenschutz/page.tsx +128 -0
  359. package/app/rechtliches/impressum/page.tsx +122 -0
  360. package/app/rechtliches/widerruf/page.tsx +185 -0
  361. package/bin/xithead.js +264 -0
  362. package/codecov.yml +34 -0
  363. package/components/layout/AppShell.tsx +25 -0
  364. package/components/layout/Footer.tsx +120 -0
  365. package/components/layout/Header.tsx +145 -0
  366. package/components/marketing/LegalHighlights.tsx +45 -0
  367. package/components/marketing/LegalPageShell.tsx +49 -0
  368. package/components/marketing/LegalPanel.tsx +41 -0
  369. package/components/marketing/index.ts +3 -0
  370. package/crates/headroom-core/Cargo.toml +165 -0
  371. package/crates/headroom-core/benches/auth_mode.rs +74 -0
  372. package/crates/headroom-core/benches/ccr_store.rs +224 -0
  373. package/crates/headroom-core/benches/tokenizer.rs +52 -0
  374. package/crates/headroom-core/config/pipeline.toml +151 -0
  375. package/crates/headroom-core/proptest-regressions/transforms/tag_protector.txt +9 -0
  376. package/crates/headroom-core/src/auth_mode.rs +250 -0
  377. package/crates/headroom-core/src/cache_control.rs +414 -0
  378. package/crates/headroom-core/src/ccr/backends/in_memory.rs +317 -0
  379. package/crates/headroom-core/src/ccr/backends/mod.rs +152 -0
  380. package/crates/headroom-core/src/ccr/backends/redis.rs +146 -0
  381. package/crates/headroom-core/src/ccr/backends/sqlite.rs +205 -0
  382. package/crates/headroom-core/src/ccr/mod.rs +119 -0
  383. package/crates/headroom-core/src/compression_policy.rs +505 -0
  384. package/crates/headroom-core/src/lib.rs +33 -0
  385. package/crates/headroom-core/src/relevance/base.rs +139 -0
  386. package/crates/headroom-core/src/relevance/bm25.rs +385 -0
  387. package/crates/headroom-core/src/relevance/embedding.rs +354 -0
  388. package/crates/headroom-core/src/relevance/hybrid.rs +364 -0
  389. package/crates/headroom-core/src/relevance/mod.rs +64 -0
  390. package/crates/headroom-core/src/signals/keyword_detector.rs +433 -0
  391. package/crates/headroom-core/src/signals/line_importance.rs +84 -0
  392. package/crates/headroom-core/src/signals/mod.rs +61 -0
  393. package/crates/headroom-core/src/signals/tiered.rs +141 -0
  394. package/crates/headroom-core/src/tokenizer/estimator.rs +152 -0
  395. package/crates/headroom-core/src/tokenizer/hf_impl.rs +314 -0
  396. package/crates/headroom-core/src/tokenizer/mod.rs +56 -0
  397. package/crates/headroom-core/src/tokenizer/registry.rs +342 -0
  398. package/crates/headroom-core/src/tokenizer/tiktoken_impl.rs +265 -0
  399. package/crates/headroom-core/src/transforms/adaptive_sizer.rs +610 -0
  400. package/crates/headroom-core/src/transforms/anchor_selector.rs +1189 -0
  401. package/crates/headroom-core/src/transforms/content_detector.rs +769 -0
  402. package/crates/headroom-core/src/transforms/detection.rs +222 -0
  403. package/crates/headroom-core/src/transforms/diff_compressor.rs +1685 -0
  404. package/crates/headroom-core/src/transforms/live_zone.rs +2967 -0
  405. package/crates/headroom-core/src/transforms/log_compressor.rs +1295 -0
  406. package/crates/headroom-core/src/transforms/magika_detector.rs +395 -0
  407. package/crates/headroom-core/src/transforms/mod.rs +64 -0
  408. package/crates/headroom-core/src/transforms/pipeline/config.rs +331 -0
  409. package/crates/headroom-core/src/transforms/pipeline/mod.rs +103 -0
  410. package/crates/headroom-core/src/transforms/pipeline/offloads/diff_noise.rs +524 -0
  411. package/crates/headroom-core/src/transforms/pipeline/offloads/diff_offload.rs +279 -0
  412. package/crates/headroom-core/src/transforms/pipeline/offloads/json_offload.rs +400 -0
  413. package/crates/headroom-core/src/transforms/pipeline/offloads/log_offload.rs +284 -0
  414. package/crates/headroom-core/src/transforms/pipeline/offloads/mod.rs +34 -0
  415. package/crates/headroom-core/src/transforms/pipeline/offloads/search_offload.rs +331 -0
  416. package/crates/headroom-core/src/transforms/pipeline/orchestrator.rs +848 -0
  417. package/crates/headroom-core/src/transforms/pipeline/reformats/json_minifier.rs +175 -0
  418. package/crates/headroom-core/src/transforms/pipeline/reformats/log_template.rs +545 -0
  419. package/crates/headroom-core/src/transforms/pipeline/reformats/mod.rs +12 -0
  420. package/crates/headroom-core/src/transforms/pipeline/traits.rs +338 -0
  421. package/crates/headroom-core/src/transforms/recommendations.rs +329 -0
  422. package/crates/headroom-core/src/transforms/safety.rs +215 -0
  423. package/crates/headroom-core/src/transforms/search_compressor.rs +902 -0
  424. package/crates/headroom-core/src/transforms/smart_crusher/analyzer.rs +1262 -0
  425. package/crates/headroom-core/src/transforms/smart_crusher/anchors.rs +407 -0
  426. package/crates/headroom-core/src/transforms/smart_crusher/builder.rs +263 -0
  427. package/crates/headroom-core/src/transforms/smart_crusher/classifier.rs +214 -0
  428. package/crates/headroom-core/src/transforms/smart_crusher/compaction/classifier.rs +283 -0
  429. package/crates/headroom-core/src/transforms/smart_crusher/compaction/compactor.rs +733 -0
  430. package/crates/headroom-core/src/transforms/smart_crusher/compaction/formatter.rs +961 -0
  431. package/crates/headroom-core/src/transforms/smart_crusher/compaction/ir.rs +252 -0
  432. package/crates/headroom-core/src/transforms/smart_crusher/compaction/mod.rs +127 -0
  433. package/crates/headroom-core/src/transforms/smart_crusher/compaction/walker.rs +397 -0
  434. package/crates/headroom-core/src/transforms/smart_crusher/config.rs +173 -0
  435. package/crates/headroom-core/src/transforms/smart_crusher/constraints.rs +159 -0
  436. package/crates/headroom-core/src/transforms/smart_crusher/crusher.rs +1665 -0
  437. package/crates/headroom-core/src/transforms/smart_crusher/crushers.rs +865 -0
  438. package/crates/headroom-core/src/transforms/smart_crusher/error_keywords.rs +77 -0
  439. package/crates/headroom-core/src/transforms/smart_crusher/field_detect.rs +393 -0
  440. package/crates/headroom-core/src/transforms/smart_crusher/hashing.rs +72 -0
  441. package/crates/headroom-core/src/transforms/smart_crusher/mod.rs +81 -0
  442. package/crates/headroom-core/src/transforms/smart_crusher/observer.rs +66 -0
  443. package/crates/headroom-core/src/transforms/smart_crusher/orchestration.rs +459 -0
  444. package/crates/headroom-core/src/transforms/smart_crusher/outliers.rs +507 -0
  445. package/crates/headroom-core/src/transforms/smart_crusher/planning.rs +904 -0
  446. package/crates/headroom-core/src/transforms/smart_crusher/statistics.rs +510 -0
  447. package/crates/headroom-core/src/transforms/smart_crusher/stats_math.rs +287 -0
  448. package/crates/headroom-core/src/transforms/smart_crusher/traits.rs +203 -0
  449. package/crates/headroom-core/src/transforms/smart_crusher/types.rs +263 -0
  450. package/crates/headroom-core/src/transforms/tag_protector.rs +1272 -0
  451. package/crates/headroom-core/src/transforms/unidiff_detector.rs +232 -0
  452. package/crates/headroom-parity/Cargo.toml +26 -0
  453. package/crates/headroom-parity/examples/diff_fixture.rs +66 -0
  454. package/crates/headroom-parity/src/bin/parity_run.rs +78 -0
  455. package/crates/headroom-parity/src/lib.rs +613 -0
  456. package/crates/headroom-proxy/Cargo.toml +119 -0
  457. package/crates/headroom-proxy/data/model_prices_and_context_window.json +39767 -0
  458. package/crates/headroom-proxy/src/bedrock/auth_mode_layer.rs +192 -0
  459. package/crates/headroom-proxy/src/bedrock/envelope.rs +239 -0
  460. package/crates/headroom-proxy/src/bedrock/eventstream.rs +769 -0
  461. package/crates/headroom-proxy/src/bedrock/eventstream_to_sse.rs +459 -0
  462. package/crates/headroom-proxy/src/bedrock/invoke.rs +735 -0
  463. package/crates/headroom-proxy/src/bedrock/invoke_streaming.rs +1098 -0
  464. package/crates/headroom-proxy/src/bedrock/mod.rs +66 -0
  465. package/crates/headroom-proxy/src/bedrock/sigv4.rs +324 -0
  466. package/crates/headroom-proxy/src/bedrock/vendor.rs +82 -0
  467. package/crates/headroom-proxy/src/cache_stabilization/anthropic_cache_control.rs +698 -0
  468. package/crates/headroom-proxy/src/cache_stabilization/drift_detector.rs +683 -0
  469. package/crates/headroom-proxy/src/cache_stabilization/mod.rs +61 -0
  470. package/crates/headroom-proxy/src/cache_stabilization/openai_cache_key.rs +600 -0
  471. package/crates/headroom-proxy/src/cache_stabilization/tool_def_normalize.rs +514 -0
  472. package/crates/headroom-proxy/src/cache_stabilization/volatile_detector.rs +720 -0
  473. package/crates/headroom-proxy/src/compression/anthropic.rs +92 -0
  474. package/crates/headroom-proxy/src/compression/live_zone_anthropic.rs +1311 -0
  475. package/crates/headroom-proxy/src/compression/live_zone_openai.rs +660 -0
  476. package/crates/headroom-proxy/src/compression/live_zone_responses.rs +678 -0
  477. package/crates/headroom-proxy/src/compression/mod.rs +127 -0
  478. package/crates/headroom-proxy/src/compression/model_limits.rs +211 -0
  479. package/crates/headroom-proxy/src/config.rs +646 -0
  480. package/crates/headroom-proxy/src/error.rs +69 -0
  481. package/crates/headroom-proxy/src/handlers/chat_completions.rs +100 -0
  482. package/crates/headroom-proxy/src/handlers/conversations.rs +241 -0
  483. package/crates/headroom-proxy/src/handlers/mod.rs +13 -0
  484. package/crates/headroom-proxy/src/handlers/responses.rs +256 -0
  485. package/crates/headroom-proxy/src/headers.rs +288 -0
  486. package/crates/headroom-proxy/src/health.rs +41 -0
  487. package/crates/headroom-proxy/src/lib.rs +21 -0
  488. package/crates/headroom-proxy/src/main.rs +141 -0
  489. package/crates/headroom-proxy/src/observability/cache_hit_rate.rs +340 -0
  490. package/crates/headroom-proxy/src/observability/compression_ratio.rs +158 -0
  491. package/crates/headroom-proxy/src/observability/metric_names.rs +174 -0
  492. package/crates/headroom-proxy/src/observability/mod.rs +68 -0
  493. package/crates/headroom-proxy/src/observability/prometheus.rs +394 -0
  494. package/crates/headroom-proxy/src/observability/proxy_metrics.rs +368 -0
  495. package/crates/headroom-proxy/src/proxy.rs +1619 -0
  496. package/crates/headroom-proxy/src/responses_items.rs +565 -0
  497. package/crates/headroom-proxy/src/sse/anthropic.rs +415 -0
  498. package/crates/headroom-proxy/src/sse/framing.rs +366 -0
  499. package/crates/headroom-proxy/src/sse/mod.rs +40 -0
  500. package/crates/headroom-proxy/src/sse/openai_chat.rs +231 -0
  501. package/crates/headroom-proxy/src/sse/openai_responses.rs +458 -0
  502. package/crates/headroom-proxy/src/vertex/adc.rs +315 -0
  503. package/crates/headroom-proxy/src/vertex/envelope.rs +167 -0
  504. package/crates/headroom-proxy/src/vertex/mod.rs +277 -0
  505. package/crates/headroom-proxy/src/vertex/raw_predict.rs +490 -0
  506. package/crates/headroom-proxy/src/vertex/stream_raw_predict.rs +49 -0
  507. package/crates/headroom-proxy/src/websocket.rs +246 -0
  508. package/crates/headroom-py/Cargo.toml +37 -0
  509. package/crates/headroom-py/build.rs +77 -0
  510. package/crates/headroom-py/glibc_compat.c +170 -0
  511. package/crates/headroom-py/src/lib.rs +1655 -0
  512. package/deny.toml +32 -0
  513. package/design-system/base.css +127 -0
  514. package/design-system/components.css +1943 -0
  515. package/design-system/fonts.css +17 -0
  516. package/design-system/tailwind-preset.js +95 -0
  517. package/design-system/tokens.css +48 -0
  518. package/design-system/utilities.css +53 -0
  519. package/docker/differential-network-capture/Dockerfile.runner +14 -0
  520. package/docker/differential-network-capture/docker-compose.yml +142 -0
  521. package/docker/differential-network-capture/run-claude-lane.sh +24 -0
  522. package/docker/docker-compose.native.yml +44 -0
  523. package/docker-bake.hcl +88 -0
  524. package/docker-compose.yml +80 -0
  525. package/e2e/_lib/make_shim.ps1 +24 -0
  526. package/e2e/_lib/make_shim.sh +28 -0
  527. package/e2e/docker-native-install.sh +120 -0
  528. package/e2e/init/Dockerfile +79 -0
  529. package/e2e/wrap/Dockerfile +115 -0
  530. package/examples/07-context-compression.ipynb +279 -0
  531. package/examples/deployment/macos-launchagent/com.headroom.proxy.plist.template +65 -0
  532. package/examples/deployment/macos-launchagent/install.sh +227 -0
  533. package/examples/deployment/macos-launchagent/shell-integration.sh +74 -0
  534. package/examples/deployment/macos-launchagent/uninstall.sh +145 -0
  535. package/headroom-savings.png +0 -0
  536. package/headroom_learn.gif +0 -0
  537. package/lib/config/index.ts +12 -0
  538. package/lib/hooks/index.ts +4 -0
  539. package/lib/hooks/use-mounted.ts +13 -0
  540. package/lib/hooks/use-session.ts +34 -0
  541. package/lib/hooks/use-settings.ts +49 -0
  542. package/lib/utils/index.ts +1 -0
  543. package/lib/utils/settings.ts +162 -0
  544. package/lib/utils/utils.ts +6 -0
  545. package/llms.txt +67 -0
  546. package/middleware.ts +26 -0
  547. package/mkdocs.yml +136 -0
  548. package/next-env.d.ts +7 -0
  549. package/next.config.ts +12 -0
  550. package/npm/bin/xithead.js +2 -2
  551. package/npm/bin/xtream-head.js +366 -0
  552. package/npm/index.js +18 -91
  553. package/npm/package.json +55 -0
  554. package/package.json +47 -42
  555. package/plugins/headroom-agent-hooks/.claude-plugin/plugin.json +17 -0
  556. package/plugins/headroom-agent-hooks/hooks/hooks.json +29 -0
  557. package/plugins/headroom-oauth2/LICENSE +3 -0
  558. package/plugins/headroom-oauth2/SPEC.md +115 -0
  559. package/plugins/headroom-oauth2/pyproject.toml +48 -0
  560. package/plugins/hermes/headroom_retrieve/plugin.yaml +6 -0
  561. package/plugins/openclaw/hook-shim/HOOK.md +21 -0
  562. package/plugins/openclaw/hook-shim/handler.js +3 -0
  563. package/plugins/openclaw/openclaw.plugin.json +98 -0
  564. package/plugins/openclaw/package-lock.json +2692 -0
  565. package/plugins/openclaw/package.json +54 -0
  566. package/plugins/openclaw/prepare-dist.mjs +56 -0
  567. package/plugins/openclaw/src/convert.ts +418 -0
  568. package/plugins/openclaw/src/engine.ts +284 -0
  569. package/plugins/openclaw/src/gateway-config.ts +143 -0
  570. package/plugins/openclaw/src/index.ts +11 -0
  571. package/plugins/openclaw/src/plugin/index.ts +98 -0
  572. package/plugins/openclaw/src/proxy-manager.ts +477 -0
  573. package/plugins/openclaw/src/tools/headroom-retrieve.ts +76 -0
  574. package/plugins/openclaw/test/convert.test.ts +96 -0
  575. package/plugins/openclaw/test/engine-normalization.test.ts +21 -0
  576. package/plugins/openclaw/test/engine.test.ts +101 -0
  577. package/plugins/openclaw/test/gateway-config.test.ts +278 -0
  578. package/plugins/openclaw/test/plugin-runtime-routing.test.ts +141 -0
  579. package/plugins/openclaw/test/proxy-manager.test.ts +343 -0
  580. package/plugins/openclaw/tsup.config.ts +9 -0
  581. package/postcss.config.mjs +7 -0
  582. package/pyproject.toml +438 -0
  583. package/rust-toolchain.toml +16 -0
  584. package/sdk/typescript/examples/basic-compress.ts +64 -0
  585. package/sdk/typescript/examples/ccr-retrieve.ts +80 -0
  586. package/sdk/typescript/examples/hooks-custom-compression.ts +117 -0
  587. package/sdk/typescript/examples/middleware-composition.ts +59 -0
  588. package/sdk/typescript/examples/multi-provider.ts +53 -0
  589. package/sdk/typescript/examples/openai-anthropic-adapters.ts +73 -0
  590. package/sdk/typescript/examples/shared-context-multi-agent.ts +74 -0
  591. package/sdk/typescript/examples/simulation-dry-run.ts +80 -0
  592. package/sdk/typescript/examples/streaming-chat.ts +71 -0
  593. package/sdk/typescript/examples/structured-output.ts +99 -0
  594. package/sdk/typescript/examples/tool-calling-agent.ts +86 -0
  595. package/sdk/typescript/examples/with-headroom-vercel.ts +57 -0
  596. package/sdk/typescript/package-lock.json +3437 -0
  597. package/sdk/typescript/package.json +108 -0
  598. package/sdk/typescript/src/adapters/anthropic.ts +218 -0
  599. package/sdk/typescript/src/adapters/gemini.ts +83 -0
  600. package/sdk/typescript/src/adapters/openai.ts +77 -0
  601. package/sdk/typescript/src/adapters/vercel-ai.ts +131 -0
  602. package/sdk/typescript/src/client.ts +632 -0
  603. package/sdk/typescript/src/compress.ts +87 -0
  604. package/sdk/typescript/src/errors.ts +114 -0
  605. package/sdk/typescript/src/hooks.ts +113 -0
  606. package/sdk/typescript/src/index.ts +140 -0
  607. package/sdk/typescript/src/paths.ts +272 -0
  608. package/sdk/typescript/src/shared-context.ts +188 -0
  609. package/sdk/typescript/src/simulate.ts +52 -0
  610. package/sdk/typescript/src/types/config.ts +183 -0
  611. package/sdk/typescript/src/types/models.ts +314 -0
  612. package/sdk/typescript/src/types.ts +139 -0
  613. package/sdk/typescript/src/utils/case.ts +34 -0
  614. package/sdk/typescript/src/utils/format.ts +480 -0
  615. package/sdk/typescript/src/utils/stream.ts +50 -0
  616. package/sdk/typescript/test/adapters/anthropic.test.ts +217 -0
  617. package/sdk/typescript/test/adapters/gemini.test.ts +131 -0
  618. package/sdk/typescript/test/adapters/openai.test.ts +174 -0
  619. package/sdk/typescript/test/adapters/vercel-ai.test.ts +306 -0
  620. package/sdk/typescript/test/client-expanded.test.ts +333 -0
  621. package/sdk/typescript/test/client.test.ts +266 -0
  622. package/sdk/typescript/test/compress.test.ts +118 -0
  623. package/sdk/typescript/test/config.test.ts +275 -0
  624. package/sdk/typescript/test/errors.test.ts +169 -0
  625. package/sdk/typescript/test/format-integration.test.ts +252 -0
  626. package/sdk/typescript/test/hooks.test.ts +265 -0
  627. package/sdk/typescript/test/integration.test.ts +249 -0
  628. package/sdk/typescript/test/mdx-examples.test.ts +253 -0
  629. package/sdk/typescript/test/models.test.ts +318 -0
  630. package/sdk/typescript/test/parity.test.ts +337 -0
  631. package/sdk/typescript/test/paths.test.ts +447 -0
  632. package/sdk/typescript/test/shared-context.test.ts +245 -0
  633. package/sdk/typescript/test/simulate.test.ts +84 -0
  634. package/sdk/typescript/test/types.test.ts +244 -0
  635. package/sdk/typescript/test/utils/case.test.ts +129 -0
  636. package/sdk/typescript/test/utils/detect-format.test.ts +133 -0
  637. package/sdk/typescript/test/utils/format.test.ts +434 -0
  638. package/sdk/typescript/test/vercel-ai-e2e.test.ts +179 -0
  639. package/sdk/typescript/tsup.config.ts +17 -0
  640. package/tailwind.master.config.cjs +47 -0
  641. package/types/api.ts +12 -0
  642. package/types/config.ts +9 -0
  643. package/types/index.ts +2 -0
  644. package/uv.lock +6951 -0
  645. package/xithead.egg-info/PKG-INFO +22 -0
  646. package/xithead.egg-info/SOURCES.txt +16 -0
  647. package/xithead.egg-info/dependency_links.txt +1 -0
  648. package/xithead.egg-info/entry_points.txt +2 -0
  649. package/xithead.egg-info/requires.txt +10 -0
  650. package/xithead.egg-info/top_level.txt +2 -0
  651. package/xithead.ps1 +136 -0
  652. package/xithead.sh +129 -0
  653. package/xithead_dist/pyproject.toml +39 -0
  654. package/xithead_dist/xithead.egg-info/PKG-INFO +22 -0
  655. package/xithead_dist/xithead.egg-info/SOURCES.txt +16 -0
  656. package/xithead_dist/xithead.egg-info/dependency_links.txt +1 -0
  657. package/xithead_dist/xithead.egg-info/entry_points.txt +3 -0
  658. package/xithead_dist/xithead.egg-info/requires.txt +10 -0
  659. package/xithead_dist/xithead.egg-info/top_level.txt +2 -0
@@ -0,0 +1,1685 @@
1
+ //! Unified-diff compressor — Rust port of `headroom.transforms.diff_compressor`.
2
+ //!
3
+ //! Compresses verbose `git diff` output by:
4
+ //! 1. Parsing the unified-diff format into files + hunks.
5
+ //! 2. Capping the file count (`max_files`) — when fired, sorts by total
6
+ //! changes and keeps the heaviest files.
7
+ //! 3. Capping per-file hunk count (`max_hunks_per_file`) — keeps first +
8
+ //! last + top-scored middle hunks (relevance-aware via priority patterns
9
+ //! + user query-context word overlap).
10
+ //! 4. Trimming context lines around each `+`/`-` to `max_context_lines`
11
+ //! on either side.
12
+ //! 5. Hashing the original with MD5 truncated to 24 hex chars for a CCR
13
+ //! cache_key (only emitted if compression saved >20% of lines).
14
+ //!
15
+ //! # Parity contract
16
+ //! Output bytes (`compressed` field + all numeric counts) must be
17
+ //! byte-identical to the Python implementation. The 20 fixtures in
18
+ //! `tests/parity/fixtures/diff_compressor/` are the spec.
19
+ //!
20
+ //! # Information preservation hardening (no parity impact)
21
+ //! - Below `min_lines_for_ccr`, we return the input unchanged (matches
22
+ //! Python). Important for short diffs that don't benefit from compression
23
+ //! and would lose context-trim slack.
24
+ //! - On parse failure (no `diff --git` headers found), we return the input
25
+ //! unchanged (matches Python). Malformed input is preserved verbatim.
26
+ //! - `` markers and any other non-`+`/`-`/space
27
+ //! "other" lines inside a hunk are appended to the hunk's lines. Whether
28
+ //! they survive the context trim is determined by their distance from
29
+ //! the nearest `+`/`-` line (matches Python `_reduce_context`).
30
+ //!
31
+ //! # Observability
32
+ //! [`DiffCompressorStats`] carries the granular metrics Python doesn't
33
+ //! emit (per-file hunk drop counts, dropped file names, context lines
34
+ //! trimmed, parse warnings, processing duration). The `compress_with_stats`
35
+ //! method returns it alongside the parity-equal result; `compress` is the
36
+ //! parity-only API that just emits a `tracing::info_span`.
37
+
38
+ use std::collections::BTreeMap;
39
+ use std::sync::OnceLock;
40
+ use std::time::Instant;
41
+
42
+ use md5::{Digest, Md5};
43
+ use regex::Regex;
44
+
45
+ use crate::ccr::CcrStore;
46
+
47
+ // ─── Score-weight constants ────────────────────────────────────────────────
48
+ //
49
+ // These knobs tune the relevance scorer (used only when `max_hunks_per_file`
50
+ // fires and we have to rank middle hunks). Promoted from inline magic numbers
51
+ // so a future tuning PR can move them with full visibility, and so reviewers
52
+ // can see exactly what bias the scorer encodes. Defaults match the Python
53
+ // implementation byte-for-byte.
54
+
55
+ /// Per-line-change weight in the change-density base term. The base score is
56
+ /// `min(CHANGE_DENSITY_CAP, change_count * CHANGE_DENSITY_WEIGHT)`.
57
+ pub const SCORE_CHANGE_DENSITY_WEIGHT: f64 = 0.03;
58
+ /// Cap on the change-density base term; beyond this, additional changes
59
+ /// don't keep raising the score.
60
+ pub const SCORE_CHANGE_DENSITY_CAP: f64 = 0.3;
61
+ /// Boost added per matching word from the user-query context that appears in
62
+ /// the hunk content (case-insensitive substring match).
63
+ pub const SCORE_CONTEXT_WORD_WEIGHT: f64 = 0.2;
64
+ /// Minimum word length (exclusive of) for context-word matching. Words of
65
+ /// length ≤ this are skipped (matches Python's `len(word) > 2`). Filters out
66
+ /// stop-words like "is", "to", "a".
67
+ pub const SCORE_CONTEXT_MIN_WORD_LEN: usize = 2;
68
+ /// Boost added when ANY priority pattern matches (only one boost per hunk —
69
+ /// matches Python's `break` after first match).
70
+ pub const SCORE_PRIORITY_PATTERN_BOOST: f64 = 0.3;
71
+ /// Cap on the total hunk score after all boosts.
72
+ pub const SCORE_TOTAL_CAP: f64 = 1.0;
73
+
74
+ // ─── Public API ─────────────────────────────────────────────────────────────
75
+
76
+ /// Configuration. All defaults match Python `DiffCompressorConfig`.
77
+ #[derive(Debug, Clone)]
78
+ pub struct DiffCompressorConfig {
79
+ /// How many context lines (` ` prefix) to keep on either side of each
80
+ /// `+`/`-` change line. Python default: 2.
81
+ pub max_context_lines: usize,
82
+ /// Cap on the number of hunks kept per file. When exceeded, keeps first
83
+ /// + last + top-scored middle. Python default: 10.
84
+ pub max_hunks_per_file: usize,
85
+ /// Cap on the number of files kept across the whole diff. When exceeded,
86
+ /// sorts files by total changes (desc) and keeps top N. Files beyond
87
+ /// the cap are silently dropped from the output (their names appear in
88
+ /// [`DiffCompressorStats::files_dropped`] for observability). Python
89
+ /// default: 20.
90
+ pub max_files: usize,
91
+ /// Reserved — Python config exposes this but the algorithm always keeps
92
+ /// `+` lines. Kept for fixture-config schema compatibility.
93
+ pub always_keep_additions: bool,
94
+ /// Reserved — same as `always_keep_additions` but for `-` lines.
95
+ pub always_keep_deletions: bool,
96
+ /// If true, attach an MD5-based CCR retrieval marker to the compressed
97
+ /// output when compression met the savings threshold. Python default: true.
98
+ pub enable_ccr: bool,
99
+ /// **Misnomer alert.** This actually gates the entire compression path,
100
+ /// not just the CCR marker: when `original_line_count <
101
+ /// min_lines_for_ccr`, the input is returned unchanged, no parsing, no
102
+ /// summary, no CCR. The name comes from the Python implementation; we
103
+ /// keep it to maintain fixture-config compatibility. Treat it as
104
+ /// "minimum diff size before we bother compressing." Python default: 50.
105
+ pub min_lines_for_ccr: usize,
106
+ /// CCR retrieval marker is emitted only when
107
+ /// `compressed_line_count < original_line_count *
108
+ /// min_compression_ratio_for_ccr`. Lower values demand more aggressive
109
+ /// compression before we bother emitting the marker. **Rust-only knob**
110
+ /// — Python hardcodes 0.8. Default: 0.8 (matches Python).
111
+ pub min_compression_ratio_for_ccr: f64,
112
+ }
113
+
114
+ impl Default for DiffCompressorConfig {
115
+ fn default() -> Self {
116
+ Self {
117
+ max_context_lines: 2,
118
+ max_hunks_per_file: 10,
119
+ max_files: 20,
120
+ always_keep_additions: true,
121
+ always_keep_deletions: true,
122
+ enable_ccr: true,
123
+ min_lines_for_ccr: 50,
124
+ min_compression_ratio_for_ccr: 0.8,
125
+ }
126
+ }
127
+ }
128
+
129
+ /// Parity-equal result. Field set matches Python `DiffCompressionResult`'s
130
+ /// non-`@property` fields — `compression_ratio` and `tokens_saved_estimate`
131
+ /// are computed properties on the Python side and not in fixture outputs.
132
+ #[derive(Debug, Clone)]
133
+ pub struct DiffCompressionResult {
134
+ pub compressed: String,
135
+ pub original_line_count: usize,
136
+ pub compressed_line_count: usize,
137
+ pub files_affected: usize,
138
+ pub additions: usize,
139
+ pub deletions: usize,
140
+ pub hunks_kept: usize,
141
+ pub hunks_removed: usize,
142
+ pub cache_key: Option<String>,
143
+ }
144
+
145
+ /// Sidecar stats. Not part of the parity output; surfaced to callers and
146
+ /// `tracing` spans for prod observability. None of these fields exist in
147
+ /// Python's `DiffCompressionResult`.
148
+ #[derive(Debug, Clone, Default)]
149
+ pub struct DiffCompressorStats {
150
+ pub input_lines: usize,
151
+ pub output_lines: usize,
152
+ /// `output_lines / input_lines`. 1.0 means no compression (or input was
153
+ /// returned unchanged); lower is more aggressive compression.
154
+ pub compression_ratio: f64,
155
+
156
+ pub files_total: usize,
157
+ pub files_kept: usize,
158
+ /// Names (`old_file -> new_file` from the diff header) of files dropped
159
+ /// when `max_files` fired. Empty unless that cap engaged.
160
+ pub files_dropped: Vec<String>,
161
+
162
+ pub hunks_total: usize,
163
+ pub hunks_kept: usize,
164
+ pub hunks_dropped: usize,
165
+ /// Per-file hunk drop counts. Stable iteration order via `BTreeMap`.
166
+ pub hunks_dropped_per_file: BTreeMap<String, usize>,
167
+
168
+ pub context_lines_input: usize,
169
+ pub context_lines_kept: usize,
170
+ pub context_lines_trimmed: usize,
171
+
172
+ /// Lines in the largest hunk we kept. Useful for spotting cases where
173
+ /// a single oversized hunk dominates the output.
174
+ pub largest_hunk_kept_lines: usize,
175
+ /// Lines in the largest hunk we dropped (per-file cap). 0 if none dropped.
176
+ pub largest_hunk_dropped_lines: usize,
177
+
178
+ /// Files whose original `new file mode` / `deleted file mode` line was
179
+ /// normalized to `100644` on output. Each entry is `(file_label,
180
+ /// original_mode_line)` — e.g. `("a/foo.sh -> b/foo.sh", "new file
181
+ /// mode 100755")`. Empty when no normalization occurred (mode was
182
+ /// already 100644, or no mode line was present).
183
+ ///
184
+ /// Why this matters: parity with Python forces us to hardcode `100644`
185
+ /// in the emit path regardless of what the input said. An input with
186
+ /// executable bit `100755` becomes a non-executable `100644` on output —
187
+ /// silent information loss. Surfacing this lets prod monitoring catch
188
+ /// real cases where it bites.
189
+ pub file_mode_normalizations: Vec<(String, String)>,
190
+
191
+ /// Binary file marker lines whose original detail (e.g. `Binary files
192
+ /// a/x.png and b/x.png differ`) was simplified to `Binary files differ`
193
+ /// on output. Each entry is the full original line. Empty when no
194
+ /// simplification occurred (input was already `Binary files differ`,
195
+ /// or the file wasn't binary).
196
+ ///
197
+ /// Same parity-loss pattern as `file_mode_normalizations`: Python's
198
+ /// emitter hardcodes `Binary files differ`, dropping the filename
199
+ /// detail. This stat surfaces what was lost.
200
+ pub binary_files_simplified: Vec<String>,
201
+
202
+ /// Non-fatal parser hiccups: unrecognized line patterns, malformed
203
+ /// hunk headers, etc. Surfacing them rather than dropping silently.
204
+ pub parse_warnings: Vec<String>,
205
+
206
+ pub processing_duration_us: u64,
207
+
208
+ /// True if the CCR cache_key was attached to the output (compression
209
+ /// saved >20% of lines AND `enable_ccr` was true).
210
+ pub cache_key_emitted: bool,
211
+ /// When `cache_key_emitted == false`, why. e.g. `"below threshold"`,
212
+ /// `"ccr disabled"`, `"input below min_lines_for_ccr"`.
213
+ pub ccr_skipped_reason: Option<String>,
214
+ }
215
+
216
+ /// Compressor. Cheap to clone; holds only the config.
217
+ #[derive(Debug, Clone)]
218
+ pub struct DiffCompressor {
219
+ config: DiffCompressorConfig,
220
+ }
221
+
222
+ impl Default for DiffCompressor {
223
+ fn default() -> Self {
224
+ Self::new(DiffCompressorConfig::default())
225
+ }
226
+ }
227
+
228
+ impl DiffCompressor {
229
+ pub fn new(config: DiffCompressorConfig) -> Self {
230
+ Self { config }
231
+ }
232
+
233
+ pub fn config(&self) -> &DiffCompressorConfig {
234
+ &self.config
235
+ }
236
+
237
+ /// Compress `content`. `context` is an optional user-query string used
238
+ /// for relevance scoring when `max_hunks_per_file` fires; pass `""` if
239
+ /// not applicable. Parity-only API: emits a `tracing::info_span` but
240
+ /// discards the granular sidecar stats. Use [`compress_with_stats`]
241
+ /// when you want them.
242
+ ///
243
+ /// [`compress_with_stats`]: Self::compress_with_stats
244
+ pub fn compress(&self, content: &str, context: &str) -> DiffCompressionResult {
245
+ self.compress_with_stats(content, context).0
246
+ }
247
+
248
+ /// Same as [`compress`] but also returns rich observability stats.
249
+ /// Equivalent to `compress_with_store(content, context, None).0`.
250
+ ///
251
+ /// [`compress`]: Self::compress
252
+ pub fn compress_with_stats(
253
+ &self,
254
+ content: &str,
255
+ context: &str,
256
+ ) -> (DiffCompressionResult, DiffCompressorStats) {
257
+ self.compress_with_store(content, context, None)
258
+ }
259
+
260
+ /// Compress with optional CCR persistence.
261
+ ///
262
+ /// Mirrors [`crate::transforms::log_compressor::LogCompressor::compress_with_store`]
263
+ /// and the search-compressor sibling: when `store` is `Some`, the
264
+ /// original `content` is written to it under the same `cache_key`
265
+ /// the wire-output marker carries. When `store` is `None`, the
266
+ /// `cache_key` is still emitted but the caller is responsible for
267
+ /// persisting (e.g. the Python shim's `_persist_to_python_ccr` path).
268
+ ///
269
+ /// **Why this exists:** prior to this method, `DiffCompressor` minted
270
+ /// a `cache_key` and embedded it in the output marker but never
271
+ /// stored — leaving Python ContentRouter with a dangling marker that
272
+ /// would 404 on retrieval. The `DiffOffload` orchestrator wrapper
273
+ /// papered over this for the new pipeline path; this method
274
+ /// upstreams the fix so any caller can wire in storage cleanly.
275
+ pub fn compress_with_store(
276
+ &self,
277
+ content: &str,
278
+ context: &str,
279
+ store: Option<&dyn CcrStore>,
280
+ ) -> (DiffCompressionResult, DiffCompressorStats) {
281
+ let start = Instant::now();
282
+ let mut stats = DiffCompressorStats::default();
283
+
284
+ // Python: `lines = content.split("\n")`. Rust `split` matches `str.split`
285
+ // semantics: a trailing newline produces an empty final element, exactly
286
+ // like Python. Critical for byte-equal `original_line_count`.
287
+ let lines: Vec<&str> = content.split('\n').collect();
288
+ let original_line_count = lines.len();
289
+ stats.input_lines = original_line_count;
290
+
291
+ // Short-circuit 1: input below CCR threshold → pass through unchanged.
292
+ // This is the information-preservation path: a 5-line diff isn't worth
293
+ // compressing and the original carries all the signal.
294
+ if original_line_count < self.config.min_lines_for_ccr {
295
+ stats.output_lines = original_line_count;
296
+ stats.compression_ratio = 1.0;
297
+ stats.ccr_skipped_reason = Some("input below min_lines_for_ccr".into());
298
+ stats.processing_duration_us = start.elapsed().as_micros() as u64;
299
+ return (
300
+ pass_through_result(content, original_line_count),
301
+ emit_span_and_return(stats),
302
+ );
303
+ }
304
+
305
+ // Parse the unified diff into files + hunks (and any pre-diff
306
+ // content — commit headers, email headers — which gets re-emitted
307
+ // verbatim by `format_output`).
308
+ let parsed = parse_diff(&lines);
309
+ let pre_diff_lines = parsed.pre_diff_lines;
310
+ let mut diff_files = parsed.files;
311
+ stats.parse_warnings = parsed.parse_warnings;
312
+ stats.files_total = diff_files.len();
313
+ stats.hunks_total = diff_files.iter().map(|f| f.hunks.len()).sum();
314
+ stats.context_lines_input = diff_files
315
+ .iter()
316
+ .flat_map(|f| f.hunks.iter())
317
+ .map(|h| h.context_lines)
318
+ .sum();
319
+
320
+ // Short-circuit 2: parser found no diff sections → pass through.
321
+ // Same info-preservation rationale: malformed or non-diff input is
322
+ // returned verbatim rather than emitted as an empty compressed result.
323
+ if diff_files.is_empty() {
324
+ stats.output_lines = original_line_count;
325
+ stats.compression_ratio = 1.0;
326
+ stats.ccr_skipped_reason = Some("no diff sections parsed".into());
327
+ stats.processing_duration_us = start.elapsed().as_micros() as u64;
328
+ return (
329
+ pass_through_result(content, original_line_count),
330
+ emit_span_and_return(stats),
331
+ );
332
+ }
333
+
334
+ // Score hunks by relevance to the user query (used only if
335
+ // `max_hunks_per_file` fires).
336
+ score_hunks(&mut diff_files, context);
337
+
338
+ // File cap: if too many, sort by total changes (most first) and
339
+ // keep the top `max_files`. The dropped files' names are kept in
340
+ // stats for observability — Python silently discards them.
341
+ if diff_files.len() > self.config.max_files {
342
+ diff_files.sort_by(|a, b| {
343
+ let a_changes = a.total_additions() + a.total_deletions();
344
+ let b_changes = b.total_additions() + b.total_deletions();
345
+ b_changes.cmp(&a_changes)
346
+ });
347
+ let dropped: Vec<DiffFile> = diff_files.split_off(self.config.max_files);
348
+ stats.files_dropped = dropped
349
+ .iter()
350
+ .map(|f| format!("{} -> {}", f.old_file, f.new_file))
351
+ .collect();
352
+ }
353
+ stats.files_kept = diff_files.len();
354
+
355
+ // Capture lossy-emit signals on the files that survived the file cap.
356
+ // These cases are parity-bound (Python's emit hardcodes `100644` and
357
+ // `Binary files differ` regardless of input), so the only honest move
358
+ // is to surface the loss via observability rather than fix it.
359
+ for file in diff_files.iter() {
360
+ let label = format!("{} -> {}", file.old_file, file.new_file);
361
+ // File-mode normalization: any original mode line not literally
362
+ // `new file mode 100644` / `deleted file mode 100644` is lost on
363
+ // emit. Includes `100755` (executable), `100600` (private),
364
+ // `120000` (symlink), `160000` (gitlink/submodule), etc.
365
+ if let Some(orig) = &file.original_new_file_mode_line {
366
+ if orig != "new file mode 100644" {
367
+ stats
368
+ .file_mode_normalizations
369
+ .push((label.clone(), orig.clone()));
370
+ }
371
+ }
372
+ if let Some(orig) = &file.original_deleted_file_mode_line {
373
+ if orig != "deleted file mode 100644" {
374
+ stats
375
+ .file_mode_normalizations
376
+ .push((label.clone(), orig.clone()));
377
+ }
378
+ }
379
+ // Binary detail: any line richer than the bare `Binary files
380
+ // differ` (which is virtually all of them — git emits filenames)
381
+ // gets simplified on emit.
382
+ if let Some(orig) = &file.original_binary_line {
383
+ if orig != "Binary files differ" {
384
+ stats.binary_files_simplified.push(orig.clone());
385
+ }
386
+ }
387
+ }
388
+
389
+ // Compress each file's hunks: cap count, then trim context.
390
+ let mut compressed_files: Vec<DiffFile> = Vec::with_capacity(diff_files.len());
391
+ let mut total_additions = 0usize;
392
+ let mut total_deletions = 0usize;
393
+ let mut hunks_kept_total = 0usize;
394
+ let mut hunks_removed_total = 0usize;
395
+ let mut largest_kept = 0usize;
396
+ let mut largest_dropped = 0usize;
397
+ let mut context_kept_total = 0usize;
398
+
399
+ for file in diff_files {
400
+ total_additions += file.total_additions();
401
+ total_deletions += file.total_deletions();
402
+
403
+ let original_hunk_count = file.hunks.len();
404
+ let file_label = format!("{} -> {}", file.old_file, file.new_file);
405
+
406
+ let (selected, dropped) = select_hunks(file.hunks, self.config.max_hunks_per_file);
407
+ let dropped_count = dropped.len();
408
+ if dropped_count > 0 {
409
+ stats
410
+ .hunks_dropped_per_file
411
+ .insert(file_label, dropped_count);
412
+ let max_dropped = dropped.iter().map(|h| h.lines.len()).max().unwrap_or(0);
413
+ if max_dropped > largest_dropped {
414
+ largest_dropped = max_dropped;
415
+ }
416
+ }
417
+
418
+ // Trim context inside each kept hunk.
419
+ let mut compressed_hunks: Vec<DiffHunk> = Vec::with_capacity(selected.len());
420
+ for hunk in selected {
421
+ let trimmed = reduce_context(&hunk, self.config.max_context_lines);
422
+ if trimmed.lines.len() > largest_kept {
423
+ largest_kept = trimmed.lines.len();
424
+ }
425
+ context_kept_total += trimmed.context_lines;
426
+ compressed_hunks.push(trimmed);
427
+ }
428
+
429
+ hunks_kept_total += compressed_hunks.len();
430
+ hunks_removed_total += original_hunk_count - compressed_hunks.len();
431
+
432
+ compressed_files.push(DiffFile {
433
+ hunks: compressed_hunks,
434
+ ..file
435
+ });
436
+ }
437
+
438
+ stats.hunks_kept = hunks_kept_total;
439
+ stats.hunks_dropped = hunks_removed_total;
440
+ stats.context_lines_kept = context_kept_total;
441
+ stats.context_lines_trimmed = stats.context_lines_input.saturating_sub(context_kept_total);
442
+ stats.largest_hunk_kept_lines = largest_kept;
443
+ stats.largest_hunk_dropped_lines = largest_dropped;
444
+
445
+ let files_affected = compressed_files.len();
446
+
447
+ // Format compressed output. The footer summary line goes inside
448
+ // `compressed`; the CCR retrieval marker (if present) is appended
449
+ // after — both must match Python's emitter byte-for-byte.
450
+ let mut compressed_output = format_output(
451
+ &pre_diff_lines,
452
+ &compressed_files,
453
+ files_affected,
454
+ total_additions,
455
+ total_deletions,
456
+ hunks_removed_total,
457
+ );
458
+ let compressed_line_count = count_split_lines(&compressed_output);
459
+
460
+ // CCR layer: hash original with MD5[:24], append retrieval marker
461
+ // *only* if compression met `min_compression_ratio_for_ccr`. Python
462
+ // hardcodes 0.8 (>20% savings); we expose it as a config knob with
463
+ // the same default.
464
+ //
465
+ // CRITICAL: `compressed_line_count` is captured BEFORE the CCR marker
466
+ // is appended, both for the marker's own text ("compressed to N")
467
+ // and for the result field. The output string ends up with one more
468
+ // line than `compressed_line_count` reports, by design — Python
469
+ // does the same. Mismatching this by recounting after the append
470
+ // breaks parity by 1.
471
+ let savings_threshold = self.config.min_compression_ratio_for_ccr;
472
+ let mut cache_key: Option<String> = None;
473
+ if self.config.enable_ccr
474
+ && (compressed_line_count as f64) < (original_line_count as f64) * savings_threshold
475
+ {
476
+ let key = md5_hex_24(content);
477
+ compressed_output.push('\n');
478
+ compressed_output.push_str(&format!(
479
+ "[{} lines compressed to {}. Retrieve full diff: hash={}]",
480
+ original_line_count, compressed_line_count, key
481
+ ));
482
+ // Persist the original under the same key. When `store` is
483
+ // `Some`, the marker we just emitted resolves through it on
484
+ // the LLM's retrieval tool call. When `None`, the caller
485
+ // (typically the Python shim) is responsible — see the
486
+ // method-level docs.
487
+ if let Some(s) = store {
488
+ s.put(&key, content);
489
+ }
490
+ cache_key = Some(key);
491
+ stats.cache_key_emitted = true;
492
+ } else if !self.config.enable_ccr {
493
+ stats.ccr_skipped_reason = Some("ccr disabled".into());
494
+ } else {
495
+ stats.ccr_skipped_reason = Some(format!(
496
+ "compression ratio {:.3} above threshold {:.3}",
497
+ if original_line_count == 0 {
498
+ 1.0
499
+ } else {
500
+ compressed_line_count as f64 / original_line_count as f64
501
+ },
502
+ savings_threshold
503
+ ));
504
+ }
505
+
506
+ stats.output_lines = compressed_line_count;
507
+ stats.compression_ratio = if original_line_count == 0 {
508
+ 1.0
509
+ } else {
510
+ compressed_line_count as f64 / original_line_count as f64
511
+ };
512
+ stats.processing_duration_us = start.elapsed().as_micros() as u64;
513
+
514
+ let result = DiffCompressionResult {
515
+ compressed: compressed_output,
516
+ original_line_count,
517
+ compressed_line_count,
518
+ files_affected,
519
+ additions: total_additions,
520
+ deletions: total_deletions,
521
+ hunks_kept: hunks_kept_total,
522
+ hunks_removed: hunks_removed_total,
523
+ cache_key,
524
+ };
525
+
526
+ (result, emit_span_and_return(stats))
527
+ }
528
+ }
529
+
530
+ // ─── Internal types ────────────────────────────────────────────────────────
531
+
532
+ #[derive(Debug, Clone)]
533
+ struct DiffHunk {
534
+ header: String,
535
+ lines: Vec<String>,
536
+ additions: usize,
537
+ deletions: usize,
538
+ context_lines: usize,
539
+ /// Relevance score; only meaningful when `max_hunks_per_file` fires.
540
+ score: f64,
541
+ }
542
+
543
+ #[derive(Debug, Clone)]
544
+ struct DiffFile {
545
+ header: String,
546
+ old_file: String,
547
+ new_file: String,
548
+ hunks: Vec<DiffHunk>,
549
+ is_binary: bool,
550
+ is_new_file: bool,
551
+ is_deleted_file: bool,
552
+ is_renamed: bool,
553
+ /// Bug-fix: rename / similarity / dissimilarity / copy marker lines
554
+ /// captured verbatim from the parser (e.g. `rename from old.py`,
555
+ /// `rename to new.py`, `similarity index 95%`). Re-emitted after the
556
+ /// `diff --git` header so the LLM can see that a file was renamed
557
+ /// rather than modified-in-place. Previously dropped in both Python
558
+ /// and Rust — fixed in both as part of the same change.
559
+ rename_lines: Vec<String>,
560
+ /// Full original `new file mode <NNNNNN>` line if present. Captured so
561
+ /// we can detect when emit-time normalization to `100644` lost the
562
+ /// executable bit (or any other mode signal).
563
+ original_new_file_mode_line: Option<String>,
564
+ /// Full original `deleted file mode <NNNNNN>` line if present.
565
+ original_deleted_file_mode_line: Option<String>,
566
+ /// Full original `Binary files X and Y differ` line if present.
567
+ /// Captured so we can detect when emit simplifies to `Binary files differ`.
568
+ original_binary_line: Option<String>,
569
+ }
570
+
571
+ impl DiffFile {
572
+ fn total_additions(&self) -> usize {
573
+ self.hunks.iter().map(|h| h.additions).sum()
574
+ }
575
+ fn total_deletions(&self) -> usize {
576
+ self.hunks.iter().map(|h| h.deletions).sum()
577
+ }
578
+ }
579
+
580
+ // ─── Parser ────────────────────────────────────────────────────────────────
581
+
582
+ /// Matches any hunk header — regular `@@ -A,B +C,D @@` AND combined-diff
583
+ /// `@@@ -A,B -C,D +E,F @@@` (3-way merge) and `@@@@ ... @@@@` (4-way merge,
584
+ /// extremely rare).
585
+ ///
586
+ /// Bug-fix: the previous regex only matched `@@`, so combined-diff hunks
587
+ /// from merge commits had ALL their content silently dropped — `current_hunk`
588
+ /// was never set, so subsequent +/- lines fell through to the no-op branch.
589
+ /// Fixed in tandem with the Python source.
590
+ ///
591
+ /// Implementation note: Rust's `regex` crate (RE2-based) doesn't support
592
+ /// backreferences, so the matched-pair count of `@`s on each side is
593
+ /// hand-rolled as alternation. Octopus merges with >3 parents (5+ `@`s)
594
+ /// would slip through this regex back to the content-line branch — they're
595
+ /// vanishingly rare in practice (n-parent merges with n>3 essentially
596
+ /// never appear in real repos). When they do, a `parse_warnings` entry is
597
+ /// emitted so prod monitoring can flag the case rather than silently
598
+ /// dropping it.
599
+ fn hunk_header_regex() -> &'static Regex {
600
+ static RE: OnceLock<Regex> = OnceLock::new();
601
+ RE.get_or_init(|| {
602
+ Regex::new(concat!(
603
+ r"^(?:",
604
+ // Regular @@ ... @@
605
+ r"@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@",
606
+ r"|",
607
+ // 3-way merge @@@ ... @@@
608
+ r"@@@ -\d+(?:,\d+)? -\d+(?:,\d+)? \+\d+(?:,\d+)? @@@",
609
+ r"|",
610
+ // 4-way merge @@@@ ... @@@@
611
+ r"@@@@ -\d+(?:,\d+)? -\d+(?:,\d+)? -\d+(?:,\d+)? \+\d+(?:,\d+)? @@@@",
612
+ r")(.*)$"
613
+ ))
614
+ .expect("static regex compiles")
615
+ })
616
+ }
617
+
618
+ /// Extracts the new-file starting line number (`+N`) from any hunk header,
619
+ /// regardless of whether it's regular or combined-diff. Used for in-order
620
+ /// resort after middle-hunk selection.
621
+ fn hunk_new_range_regex() -> &'static Regex {
622
+ static RE: OnceLock<Regex> = OnceLock::new();
623
+ RE.get_or_init(|| Regex::new(r"\+(\d+)").expect("static regex compiles"))
624
+ }
625
+
626
+ fn diff_git_regex() -> &'static Regex {
627
+ static RE: OnceLock<Regex> = OnceLock::new();
628
+ RE.get_or_init(|| Regex::new(r"^diff --git a/(.+) b/(.+)$").expect("static regex compiles"))
629
+ }
630
+
631
+ /// Bug-fix (2026-04-25): merge-commit headers `diff --combined <path>` and
632
+ /// `diff --cc <path>`. Single-path file diffs paired with combined-diff
633
+ /// hunk syntax (`@@@`+). Previously not recognized — merge diffs from
634
+ /// `git log -p` were treated as a single non-diff blob because the header
635
+ /// didn't match `diff --git`, so they fell into pre-diff content.
636
+ fn diff_combined_regex() -> &'static Regex {
637
+ static RE: OnceLock<Regex> = OnceLock::new();
638
+ RE.get_or_init(|| Regex::new(r"^diff --combined (.+)$").expect("static regex compiles"))
639
+ }
640
+
641
+ fn diff_cc_regex() -> &'static Regex {
642
+ static RE: OnceLock<Regex> = OnceLock::new();
643
+ RE.get_or_init(|| Regex::new(r"^diff --cc (.+)$").expect("static regex compiles"))
644
+ }
645
+
646
+ /// Returns true if `line` is any kind of `diff --…` file-section header
647
+ /// (regular `--git`, or the combined-diff `--combined` / `--cc` variants).
648
+ fn is_diff_header(line: &str) -> bool {
649
+ diff_git_regex().is_match(line)
650
+ || diff_combined_regex().is_match(line)
651
+ || diff_cc_regex().is_match(line)
652
+ }
653
+
654
+ fn old_file_regex() -> &'static Regex {
655
+ static RE: OnceLock<Regex> = OnceLock::new();
656
+ RE.get_or_init(|| Regex::new(r"^--- (a/(.+)|/dev/null)$").expect("static regex compiles"))
657
+ }
658
+
659
+ fn new_file_regex() -> &'static Regex {
660
+ static RE: OnceLock<Regex> = OnceLock::new();
661
+ RE.get_or_init(|| Regex::new(r"^\+\+\+ (b/(.+)|/dev/null)$").expect("static regex compiles"))
662
+ }
663
+
664
+ fn binary_regex() -> &'static Regex {
665
+ static RE: OnceLock<Regex> = OnceLock::new();
666
+ RE.get_or_init(|| Regex::new(r"^Binary files .+ differ$").expect("static regex compiles"))
667
+ }
668
+
669
+ /// Parser output: pre-diff content (commit headers, email headers from
670
+ /// `git format-patch`, anything before the first `diff --git`), plus the
671
+ /// parsed file structures. Bug-fix: pre-diff content used to be dropped
672
+ /// silently; now preserved verbatim and re-emitted by `format_output`.
673
+ struct ParsedDiff {
674
+ pre_diff_lines: Vec<String>,
675
+ files: Vec<DiffFile>,
676
+ parse_warnings: Vec<String>,
677
+ }
678
+
679
+ fn parse_diff(lines: &[&str]) -> ParsedDiff {
680
+ let mut files: Vec<DiffFile> = Vec::new();
681
+ let mut current_file: Option<DiffFile> = None;
682
+ let mut current_hunk: Option<DiffHunk> = None;
683
+ let mut pre_diff_lines: Vec<String> = Vec::new();
684
+ let warnings: Vec<String> = Vec::new();
685
+
686
+ for &line in lines {
687
+ // New file section. Includes regular `diff --git` AND merge-commit
688
+ // `diff --combined <path>` / `diff --cc <path>` (bug-fix
689
+ // 2026-04-25). Without these, merge diffs from `git log -p` got
690
+ // treated as one giant pre-diff blob and never reached the
691
+ // hunk-parsing path.
692
+ if is_diff_header(line) {
693
+ if let Some(h) = current_hunk.take() {
694
+ if let Some(f) = current_file.as_mut() {
695
+ f.hunks.push(h);
696
+ }
697
+ }
698
+ if let Some(f) = current_file.take() {
699
+ files.push(f);
700
+ }
701
+ current_file = Some(DiffFile {
702
+ header: line.to_string(),
703
+ old_file: String::new(),
704
+ new_file: String::new(),
705
+ hunks: Vec::new(),
706
+ is_binary: false,
707
+ is_new_file: false,
708
+ is_deleted_file: false,
709
+ is_renamed: false,
710
+ rename_lines: Vec::new(),
711
+ original_new_file_mode_line: None,
712
+ original_deleted_file_mode_line: None,
713
+ original_binary_line: None,
714
+ });
715
+ continue;
716
+ }
717
+
718
+ // Bug-fix: lines before the first `diff --git` are pre-diff content
719
+ // (commit metadata, email headers, etc.) — capture verbatim rather
720
+ // than drop silently. They get re-emitted at the head of the
721
+ // compressed output.
722
+ if current_file.is_none() {
723
+ pre_diff_lines.push(line.to_string());
724
+ continue;
725
+ }
726
+
727
+ // File-level mode/binary/rename markers. Capture the full original
728
+ // line in addition to the boolean — Python only sets the flag and
729
+ // discards the actual mode/detail, but we want the original around
730
+ // so we can surface emit-time normalizations as observability.
731
+ if let Some(f) = current_file.as_mut() {
732
+ if line.starts_with("new file mode") {
733
+ f.is_new_file = true;
734
+ f.original_new_file_mode_line = Some(line.to_string());
735
+ } else if line.starts_with("deleted file mode") {
736
+ f.is_deleted_file = true;
737
+ f.original_deleted_file_mode_line = Some(line.to_string());
738
+ } else if line.starts_with("rename ")
739
+ || line.starts_with("similarity ")
740
+ || line.starts_with("copy ")
741
+ || line.starts_with("dissimilarity ")
742
+ {
743
+ // Bug-fix: capture the rename / similarity / dissimilarity /
744
+ // copy marker lines verbatim. Previously only `is_renamed`
745
+ // was set and the lines were dropped, so emit looked like
746
+ // a plain modification.
747
+ f.is_renamed = true;
748
+ f.rename_lines.push(line.to_string());
749
+ } else if binary_regex().is_match(line) {
750
+ f.is_binary = true;
751
+ f.original_binary_line = Some(line.to_string());
752
+ }
753
+ }
754
+
755
+ // `--- a/file` or `--- /dev/null`.
756
+ if old_file_regex().is_match(line) {
757
+ if let Some(f) = current_file.as_mut() {
758
+ f.old_file = line.to_string();
759
+ }
760
+ continue;
761
+ }
762
+
763
+ // `+++ b/file` or `+++ /dev/null`.
764
+ if new_file_regex().is_match(line) {
765
+ if let Some(f) = current_file.as_mut() {
766
+ f.new_file = line.to_string();
767
+ }
768
+ continue;
769
+ }
770
+
771
+ // Hunk header.
772
+ if hunk_header_regex().is_match(line) {
773
+ if let Some(h) = current_hunk.take() {
774
+ if let Some(f) = current_file.as_mut() {
775
+ f.hunks.push(h);
776
+ }
777
+ }
778
+ current_hunk = Some(DiffHunk {
779
+ header: line.to_string(),
780
+ lines: Vec::new(),
781
+ additions: 0,
782
+ deletions: 0,
783
+ context_lines: 0,
784
+ score: 0.0,
785
+ });
786
+ continue;
787
+ }
788
+
789
+ // Hunk content.
790
+ if let Some(h) = current_hunk.as_mut() {
791
+ if line.starts_with('+') && !line.starts_with("+++") {
792
+ h.additions += 1;
793
+ h.lines.push(line.to_string());
794
+ } else if line.starts_with('-') && !line.starts_with("---") {
795
+ h.deletions += 1;
796
+ h.lines.push(line.to_string());
797
+ } else if line.starts_with(' ') || line.is_empty() {
798
+ h.context_lines += 1;
799
+ h.lines.push(line.to_string());
800
+ } else {
801
+ // "Other" line: ``, trailing
802
+ // junk like comments, etc. Append verbatim — the context
803
+ // trim later decides whether it survives based on
804
+ // proximity to a `+`/`-` line.
805
+ h.lines.push(line.to_string());
806
+ }
807
+ }
808
+ }
809
+
810
+ if let Some(h) = current_hunk.take() {
811
+ if let Some(f) = current_file.as_mut() {
812
+ f.hunks.push(h);
813
+ }
814
+ }
815
+ if let Some(f) = current_file.take() {
816
+ files.push(f);
817
+ }
818
+
819
+ ParsedDiff {
820
+ pre_diff_lines,
821
+ files,
822
+ parse_warnings: warnings,
823
+ }
824
+ }
825
+
826
+ // ─── Scoring ───────────────────────────────────────────────────────────────
827
+
828
+ /// Priority patterns matching `headroom.transforms.error_detection.PRIORITY_PATTERNS_DIFF`:
829
+ /// ERROR + IMPORTANCE + SECURITY. Used in scoring so error-relevant hunks
830
+ /// survive `max_hunks_per_file` capping.
831
+ fn priority_patterns() -> &'static [Regex] {
832
+ static RES: OnceLock<Vec<Regex>> = OnceLock::new();
833
+ RES.get_or_init(|| {
834
+ vec![
835
+ Regex::new(r"(?i)\b(error|exception|fail(?:ed|ure)?|fatal|critical|crash|panic)\b")
836
+ .unwrap(),
837
+ Regex::new(r"(?i)\b(important|note|todo|fixme|hack|xxx|bug|fix)\b").unwrap(),
838
+ Regex::new(r"(?i)\b(security|auth|password|secret|token)\b").unwrap(),
839
+ ]
840
+ })
841
+ }
842
+
843
+ fn score_hunks(files: &mut [DiffFile], context: &str) {
844
+ let context_lower = context.to_lowercase();
845
+ let context_words: Vec<&str> = context_lower.split_whitespace().collect();
846
+
847
+ for file in files.iter_mut() {
848
+ for hunk in file.hunks.iter_mut() {
849
+ let mut score: f64 = 0.0;
850
+ // Base score from change density (capped).
851
+ score += (hunk.additions as f64 + hunk.deletions as f64) * SCORE_CHANGE_DENSITY_WEIGHT;
852
+ if score > SCORE_CHANGE_DENSITY_CAP {
853
+ score = SCORE_CHANGE_DENSITY_CAP;
854
+ }
855
+
856
+ let hunk_content_lower = hunk.lines.join("\n").to_lowercase();
857
+
858
+ for word in &context_words {
859
+ if word.len() > SCORE_CONTEXT_MIN_WORD_LEN && hunk_content_lower.contains(word) {
860
+ score += SCORE_CONTEXT_WORD_WEIGHT;
861
+ }
862
+ }
863
+
864
+ for pat in priority_patterns() {
865
+ if pat.is_match(&hunk_content_lower) {
866
+ score += SCORE_PRIORITY_PATTERN_BOOST;
867
+ break;
868
+ }
869
+ }
870
+
871
+ if score > SCORE_TOTAL_CAP {
872
+ score = SCORE_TOTAL_CAP;
873
+ }
874
+ hunk.score = score;
875
+ }
876
+ }
877
+ }
878
+
879
+ // ─── Hunk selection (max_hunks_per_file cap) ───────────────────────────────
880
+
881
+ /// Mirror of Python's `_compress_hunks` (the file-internal hunk cap, not
882
+ /// the file count cap). Returns `(selected_in_original_order, dropped)`.
883
+ fn select_hunks(hunks: Vec<DiffHunk>, max_per_file: usize) -> (Vec<DiffHunk>, Vec<DiffHunk>) {
884
+ if hunks.len() <= max_per_file {
885
+ return (hunks, Vec::new());
886
+ }
887
+ if hunks.is_empty() {
888
+ return (Vec::new(), Vec::new());
889
+ }
890
+
891
+ // Python keeps first + last + top-scored middle, then resorts by hunk
892
+ // header start-line to restore appearance order.
893
+ let n = hunks.len();
894
+ let mut indexed: Vec<(usize, DiffHunk)> = hunks.into_iter().enumerate().collect();
895
+
896
+ let first = indexed.remove(0);
897
+ let last = if !indexed.is_empty() {
898
+ Some(indexed.pop().unwrap())
899
+ } else {
900
+ None
901
+ };
902
+ let middle: Vec<(usize, DiffHunk)> = indexed;
903
+
904
+ let remaining_slots = if last.is_some() {
905
+ max_per_file.saturating_sub(2)
906
+ } else {
907
+ max_per_file.saturating_sub(1)
908
+ };
909
+
910
+ // Sort middle by score desc; pick top.
911
+ let mut middle_sorted = middle;
912
+ middle_sorted.sort_by(|a, b| {
913
+ b.1.score
914
+ .partial_cmp(&a.1.score)
915
+ .unwrap_or(std::cmp::Ordering::Equal)
916
+ });
917
+ let (kept_middle, dropped_middle): (Vec<_>, Vec<_>) = middle_sorted
918
+ .into_iter()
919
+ .enumerate()
920
+ .partition(|(rank, _)| *rank < remaining_slots);
921
+ let kept_middle: Vec<(usize, DiffHunk)> = kept_middle.into_iter().map(|(_, x)| x).collect();
922
+ let dropped_middle: Vec<DiffHunk> = dropped_middle.into_iter().map(|(_, (_, h))| h).collect();
923
+
924
+ // Reassemble in original order using the captured indices.
925
+ let mut selected: Vec<(usize, DiffHunk)> = Vec::with_capacity(max_per_file);
926
+ selected.push(first);
927
+ selected.extend(kept_middle);
928
+ if let Some(l) = last {
929
+ selected.push(l);
930
+ }
931
+ // Python sorts by `_extract_line_number(header)` (the @@ start line);
932
+ // we match that exactly because two hunks could in principle share an
933
+ // index (they don't in practice but match Python's tiebreak).
934
+ selected.sort_by(|a, b| {
935
+ let la = extract_line_number(&a.1.header);
936
+ let lb = extract_line_number(&b.1.header);
937
+ la.cmp(&lb)
938
+ });
939
+
940
+ let _ = n;
941
+ (
942
+ selected.into_iter().map(|(_, h)| h).collect(),
943
+ dropped_middle,
944
+ )
945
+ }
946
+
947
+ fn extract_line_number(header: &str) -> usize {
948
+ // Use the dedicated `+N` regex — works for both `@@` and `@@@` headers.
949
+ // The previous implementation captured group(1) of the hunk-header
950
+ // regex, which was the line number for `@@` only; under the new combined
951
+ // diff regex, group(1) is the `@`-prefix.
952
+ if let Some(caps) = hunk_new_range_regex().captures(header) {
953
+ if let Some(m) = caps.get(1) {
954
+ if let Ok(n) = m.as_str().parse::<usize>() {
955
+ return n;
956
+ }
957
+ }
958
+ }
959
+ 0
960
+ }
961
+
962
+ // ─── Context trimming ──────────────────────────────────────────────────────
963
+
964
+ fn reduce_context(hunk: &DiffHunk, max_context: usize) -> DiffHunk {
965
+ // Indices of `+`/`-` lines.
966
+ let change_positions: Vec<usize> = hunk
967
+ .lines
968
+ .iter()
969
+ .enumerate()
970
+ .filter_map(|(i, l)| {
971
+ if l.starts_with('+') || l.starts_with('-') {
972
+ Some(i)
973
+ } else {
974
+ None
975
+ }
976
+ })
977
+ .collect();
978
+
979
+ if change_positions.is_empty() {
980
+ // No-changes hunk → keep up to `max_context` leading lines, like Python.
981
+ let take = max_context.min(hunk.lines.len());
982
+ let lines: Vec<String> = hunk.lines.iter().take(take).cloned().collect();
983
+ return DiffHunk {
984
+ header: hunk.header.clone(),
985
+ lines,
986
+ additions: 0,
987
+ deletions: 0,
988
+ context_lines: take,
989
+ score: hunk.score,
990
+ };
991
+ }
992
+
993
+ // Indices to keep: each change + `max_context` lines either side.
994
+ let mut keep = std::collections::BTreeSet::new();
995
+ for &pos in &change_positions {
996
+ keep.insert(pos);
997
+ let lo = pos.saturating_sub(max_context);
998
+ for i in lo..pos {
999
+ keep.insert(i);
1000
+ }
1001
+ let hi = (pos + max_context + 1).min(hunk.lines.len());
1002
+ for i in (pos + 1)..hi {
1003
+ keep.insert(i);
1004
+ }
1005
+ }
1006
+
1007
+ // Bug-fix: ALWAYS keep `` markers (and any
1008
+ // other backslash-prefixed metadata) regardless of distance from a
1009
+ // change. These are structural patch markers, not context — losing
1010
+ // them breaks round-trippable patches and changes the semantic
1011
+ // meaning of the trailing line in the file. Mirrors the same fix in
1012
+ // the Python source.
1013
+ for (i, line) in hunk.lines.iter().enumerate() {
1014
+ if line.starts_with('\\') {
1015
+ keep.insert(i);
1016
+ }
1017
+ }
1018
+
1019
+ let mut new_lines: Vec<String> = Vec::with_capacity(keep.len());
1020
+ let mut additions = 0usize;
1021
+ let mut deletions = 0usize;
1022
+ let mut context_lines = 0usize;
1023
+ for &i in &keep {
1024
+ let line = &hunk.lines[i];
1025
+ new_lines.push(line.clone());
1026
+ if line.starts_with('+') {
1027
+ additions += 1;
1028
+ } else if line.starts_with('-') {
1029
+ deletions += 1;
1030
+ } else {
1031
+ context_lines += 1;
1032
+ }
1033
+ }
1034
+
1035
+ DiffHunk {
1036
+ header: hunk.header.clone(),
1037
+ lines: new_lines,
1038
+ additions,
1039
+ deletions,
1040
+ context_lines,
1041
+ score: hunk.score,
1042
+ }
1043
+ }
1044
+
1045
+ // ─── Output formatter ──────────────────────────────────────────────────────
1046
+
1047
+ fn format_output(
1048
+ pre_diff_lines: &[String],
1049
+ files: &[DiffFile],
1050
+ files_affected: usize,
1051
+ total_additions: usize,
1052
+ total_deletions: usize,
1053
+ hunks_removed: usize,
1054
+ ) -> String {
1055
+ let mut out_lines: Vec<String> = Vec::new();
1056
+
1057
+ // Bug-fix: emit pre-diff content (commit headers, email headers)
1058
+ // verbatim before the file sections. Previously dropped silently.
1059
+ for l in pre_diff_lines {
1060
+ out_lines.push(l.clone());
1061
+ }
1062
+
1063
+ for f in files {
1064
+ out_lines.push(f.header.clone());
1065
+
1066
+ // Bug-fix: emit rename / similarity / dissimilarity / copy marker
1067
+ // lines immediately after `diff --git`, matching git's canonical
1068
+ // output ordering. Previously these were captured into
1069
+ // `is_renamed=true` and dropped — output looked like a plain
1070
+ // modification of the old path.
1071
+ for l in &f.rename_lines {
1072
+ out_lines.push(l.clone());
1073
+ }
1074
+
1075
+ if f.is_new_file {
1076
+ out_lines.push("new file mode 100644".into());
1077
+ } else if f.is_deleted_file {
1078
+ out_lines.push("deleted file mode 100644".into());
1079
+ }
1080
+
1081
+ if f.is_binary {
1082
+ out_lines.push("Binary files differ".into());
1083
+ continue;
1084
+ }
1085
+
1086
+ if !f.old_file.is_empty() {
1087
+ out_lines.push(f.old_file.clone());
1088
+ }
1089
+ if !f.new_file.is_empty() {
1090
+ out_lines.push(f.new_file.clone());
1091
+ }
1092
+
1093
+ for h in &f.hunks {
1094
+ out_lines.push(h.header.clone());
1095
+ for l in &h.lines {
1096
+ out_lines.push(l.clone());
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ // Summary footer — only when we touched at least one file.
1102
+ if hunks_removed > 0 || files_affected > 0 {
1103
+ let mut parts = Vec::with_capacity(3);
1104
+ parts.push(format!("{} files changed", files_affected));
1105
+ parts.push(format!("+{} -{} lines", total_additions, total_deletions));
1106
+ if hunks_removed > 0 {
1107
+ parts.push(format!("{} hunks omitted", hunks_removed));
1108
+ }
1109
+ out_lines.push(format!("[{}]", parts.join(", ")));
1110
+ }
1111
+
1112
+ out_lines.join("\n")
1113
+ }
1114
+
1115
+ // ─── Helpers ───────────────────────────────────────────────────────────────
1116
+
1117
+ fn pass_through_result(content: &str, line_count: usize) -> DiffCompressionResult {
1118
+ DiffCompressionResult {
1119
+ compressed: content.to_string(),
1120
+ original_line_count: line_count,
1121
+ compressed_line_count: line_count,
1122
+ files_affected: 0,
1123
+ additions: 0,
1124
+ deletions: 0,
1125
+ hunks_kept: 0,
1126
+ hunks_removed: 0,
1127
+ cache_key: None,
1128
+ }
1129
+ }
1130
+
1131
+ /// `s.split('\n').count()` — matches Python's `len(content.split("\n"))` so
1132
+ /// the line count is byte-for-byte identical regardless of trailing newlines.
1133
+ fn count_split_lines(s: &str) -> usize {
1134
+ s.split('\n').count()
1135
+ }
1136
+
1137
+ /// MD5 of `s`'s UTF-8 bytes, hex-encoded, truncated to 24 chars. Matches
1138
+ /// `hashlib.md5(s.encode()).hexdigest()[:24]` from
1139
+ /// `headroom.cache.compression_store.CompressionStore.store`.
1140
+ fn md5_hex_24(s: &str) -> String {
1141
+ let mut hasher = Md5::new();
1142
+ hasher.update(s.as_bytes());
1143
+ let digest = hasher.finalize();
1144
+ let mut hex = String::with_capacity(32);
1145
+ for b in digest {
1146
+ hex.push_str(&format!("{:02x}", b));
1147
+ }
1148
+ hex.truncate(24);
1149
+ hex
1150
+ }
1151
+
1152
+ /// Emit a `tracing::info` event for the OTel pipeline and return the stats
1153
+ /// unchanged (so callers can see them too).
1154
+ fn emit_span_and_return(stats: DiffCompressorStats) -> DiffCompressorStats {
1155
+ tracing::info!(
1156
+ target: "diff_compressor",
1157
+ input_lines = stats.input_lines,
1158
+ output_lines = stats.output_lines,
1159
+ compression_ratio = stats.compression_ratio,
1160
+ files_total = stats.files_total,
1161
+ files_kept = stats.files_kept,
1162
+ files_dropped = stats.files_dropped.len(),
1163
+ hunks_total = stats.hunks_total,
1164
+ hunks_kept = stats.hunks_kept,
1165
+ hunks_dropped = stats.hunks_dropped,
1166
+ context_lines_trimmed = stats.context_lines_trimmed,
1167
+ largest_hunk_kept_lines = stats.largest_hunk_kept_lines,
1168
+ largest_hunk_dropped_lines = stats.largest_hunk_dropped_lines,
1169
+ parse_warnings = stats.parse_warnings.len(),
1170
+ processing_duration_us = stats.processing_duration_us,
1171
+ cache_key_emitted = stats.cache_key_emitted,
1172
+ file_mode_normalizations = stats.file_mode_normalizations.len(),
1173
+ binary_files_simplified = stats.binary_files_simplified.len(),
1174
+ "diff_compressor finished"
1175
+ );
1176
+ stats
1177
+ }
1178
+
1179
+ // ─── Tests ─────────────────────────────────────────────────────────────────
1180
+
1181
+ #[cfg(test)]
1182
+ mod tests {
1183
+ use super::*;
1184
+
1185
+ #[test]
1186
+ fn short_input_passes_through() {
1187
+ let c = DiffCompressor::default();
1188
+ let input = "diff --git a/x b/x\n@@ -1 +1 @@\n-a\n+b";
1189
+ let r = c.compress(input, "");
1190
+ // 4 lines, below min_lines_for_ccr (50) → pass-through.
1191
+ assert_eq!(r.compressed, input);
1192
+ assert_eq!(r.original_line_count, 4);
1193
+ assert_eq!(r.compressed_line_count, 4);
1194
+ assert_eq!(r.files_affected, 0);
1195
+ assert!(r.cache_key.is_none());
1196
+ }
1197
+
1198
+ #[test]
1199
+ fn non_diff_input_passes_through() {
1200
+ let c = DiffCompressor::default();
1201
+ let input = "this is not a diff\n".repeat(60); // > min_lines_for_ccr
1202
+ let r = c.compress(&input, "");
1203
+ assert_eq!(r.compressed, input);
1204
+ assert_eq!(r.files_affected, 0);
1205
+ }
1206
+
1207
+ #[test]
1208
+ fn md5_24_matches_python() {
1209
+ // Verified against Python: hashlib.md5(b"hello").hexdigest()[:24]
1210
+ assert_eq!(md5_hex_24("hello"), "5d41402abc4b2a76b9719d91");
1211
+ assert_eq!(md5_hex_24(""), "d41d8cd98f00b204e9800998");
1212
+ }
1213
+
1214
+ #[test]
1215
+ fn count_split_lines_matches_python_split_n() {
1216
+ // `"".split("\n")` == [""] in Python → 1
1217
+ assert_eq!(count_split_lines(""), 1);
1218
+ assert_eq!(count_split_lines("a"), 1);
1219
+ assert_eq!(count_split_lines("a\n"), 2);
1220
+ assert_eq!(count_split_lines("a\nb"), 2);
1221
+ assert_eq!(count_split_lines("\n"), 2);
1222
+ }
1223
+
1224
+ #[test]
1225
+ fn stats_are_emitted_with_compress_with_stats() {
1226
+ let c = DiffCompressor::default();
1227
+ let input = "noise\n".repeat(60);
1228
+ let (_r, stats) = c.compress_with_stats(&input, "");
1229
+ assert_eq!(stats.input_lines, 61); // 60 newlines split into 61 elements
1230
+ assert_eq!(stats.output_lines, 61);
1231
+ assert_eq!(stats.compression_ratio, 1.0);
1232
+ assert!(stats.parse_warnings.is_empty());
1233
+ assert!(stats.ccr_skipped_reason.is_some());
1234
+ }
1235
+
1236
+ /// Build a synthetic 8-file diff matching the parity-fixture shape so we
1237
+ /// can sanity-check the algorithm before running parity.
1238
+ fn build_synthetic_diff(n_files: usize) -> String {
1239
+ let mut s = String::new();
1240
+ for i in 0..n_files {
1241
+ s.push_str(&format!(
1242
+ "diff --git a/file_{i}.py b/file_{i}.py\n--- a/file_{i}.py\n+++ b/file_{i}.py\n@@ -1,10 +1,12 @@\n",
1243
+ ));
1244
+ for k in 0..5 {
1245
+ s.push_str(&format!(" context_{k}_{i}\n"));
1246
+ }
1247
+ for k in 0..3 {
1248
+ s.push_str(&format!("-removed_{k}_{i}\n"));
1249
+ }
1250
+ for k in 0..5 {
1251
+ s.push_str(&format!("+added_{k}_{i}\n"));
1252
+ }
1253
+ for k in 0..5 {
1254
+ s.push_str(&format!(" tail_{k}_{i}\n"));
1255
+ }
1256
+ }
1257
+ s.push_str("# variant 1");
1258
+ s
1259
+ }
1260
+
1261
+ #[test]
1262
+ fn synthetic_eight_file_diff_matches_known_shape() {
1263
+ let c = DiffCompressor::default();
1264
+ let input = build_synthetic_diff(8);
1265
+ let r = c.compress(&input, "");
1266
+ assert_eq!(r.original_line_count, 177);
1267
+ assert_eq!(r.files_affected, 8);
1268
+ assert_eq!(r.additions, 40);
1269
+ assert_eq!(r.deletions, 24);
1270
+ assert_eq!(r.hunks_kept, 8);
1271
+ assert_eq!(r.hunks_removed, 0);
1272
+ // Compressed line count should be 129 (matches the parity fixture).
1273
+ assert_eq!(r.compressed_line_count, 129);
1274
+ assert!(r.cache_key.is_some());
1275
+ }
1276
+
1277
+ // ─── Lossy-path tests ───────────────────────────────────────────────────
1278
+
1279
+ /// Build a single-file diff with N hunks. Each hunk has 2 context lines,
1280
+ /// 1 deletion, 1 addition, 2 context lines. Hunk headers use distinct
1281
+ /// start lines so the in-order resort after middle-hunk selection works.
1282
+ fn build_n_hunk_diff(n: usize) -> String {
1283
+ let mut s = String::from("diff --git a/big.py b/big.py\n--- a/big.py\n+++ b/big.py\n");
1284
+ for i in 0..n {
1285
+ // 100 lines apart per hunk so they're independent.
1286
+ let start = i * 100 + 1;
1287
+ s.push_str(&format!("@@ -{0},6 +{0},6 @@\n", start));
1288
+ s.push_str(&format!(" ctx_a_{i}\n"));
1289
+ s.push_str(&format!(" ctx_b_{i}\n"));
1290
+ s.push_str(&format!("-old_{i}\n"));
1291
+ s.push_str(&format!("+new_{i}\n"));
1292
+ s.push_str(&format!(" ctx_c_{i}\n"));
1293
+ s.push_str(&format!(" ctx_d_{i}\n"));
1294
+ }
1295
+ s
1296
+ }
1297
+
1298
+ #[test]
1299
+ fn max_hunks_per_file_cap_drops_excess_and_records_stats() {
1300
+ // 15 hunks, cap = 10 → 5 dropped. First + last + 8 top-scored middle kept.
1301
+ let cfg = DiffCompressorConfig {
1302
+ max_hunks_per_file: 10,
1303
+ ..Default::default()
1304
+ };
1305
+ let input = build_n_hunk_diff(15);
1306
+ let (result, stats) = DiffCompressor::new(cfg).compress_with_stats(&input, "");
1307
+
1308
+ assert_eq!(result.hunks_kept, 10, "kept 10 hunks");
1309
+ assert_eq!(result.hunks_removed, 5, "dropped 5");
1310
+ assert_eq!(stats.hunks_total, 15);
1311
+ assert_eq!(stats.hunks_dropped, 5);
1312
+ // Per-file accounting must match overall.
1313
+ let per_file_total: usize = stats.hunks_dropped_per_file.values().sum();
1314
+ assert_eq!(per_file_total, 5);
1315
+ // The dropped hunks have 6 lines each (after parsing); largest_dropped
1316
+ // should reflect that.
1317
+ assert!(stats.largest_hunk_dropped_lines >= 6);
1318
+ }
1319
+
1320
+ #[test]
1321
+ fn max_files_cap_drops_files_and_records_names_in_stats() {
1322
+ // 25 files, cap = 20 → 5 dropped. files_dropped should carry the names.
1323
+ let cfg = DiffCompressorConfig {
1324
+ max_files: 20,
1325
+ ..Default::default()
1326
+ };
1327
+ let input = build_synthetic_diff(25);
1328
+ let (_result, stats) = DiffCompressor::new(cfg).compress_with_stats(&input, "");
1329
+
1330
+ assert_eq!(stats.files_total, 25);
1331
+ assert_eq!(stats.files_kept, 20);
1332
+ assert_eq!(
1333
+ stats.files_dropped.len(),
1334
+ 5,
1335
+ "expected 5 dropped file labels"
1336
+ );
1337
+ // Each label should be the `old_file -> new_file` form.
1338
+ for label in &stats.files_dropped {
1339
+ assert!(
1340
+ label.contains("-> "),
1341
+ "label `{label}` should contain ` -> `"
1342
+ );
1343
+ }
1344
+ }
1345
+
1346
+ #[test]
1347
+ fn file_mode_normalization_is_recorded_for_executable_bit() {
1348
+ // Construct a long-enough diff that introduces an executable file.
1349
+ // Mode 100755 != 100644, so emit will silently normalize and stats
1350
+ // must capture the original.
1351
+ let mut input = String::from(
1352
+ "diff --git a/script.sh b/script.sh\n\
1353
+ new file mode 100755\n\
1354
+ --- /dev/null\n\
1355
+ +++ b/script.sh\n\
1356
+ @@ -0,0 +1,3 @@\n\
1357
+ +#!/bin/sh\n\
1358
+ +echo hi\n\
1359
+ +exit 0\n",
1360
+ );
1361
+ // Pad to clear `min_lines_for_ccr` so compression runs.
1362
+ for _ in 0..50 {
1363
+ input.push_str("# pad\n");
1364
+ }
1365
+ let (_r, stats) = DiffCompressor::default().compress_with_stats(&input, "");
1366
+ assert_eq!(stats.file_mode_normalizations.len(), 1, "{stats:?}");
1367
+ let (label, original) = &stats.file_mode_normalizations[0];
1368
+ assert!(label.contains("script.sh"));
1369
+ assert_eq!(original, "new file mode 100755");
1370
+ }
1371
+
1372
+ #[test]
1373
+ fn binary_files_simplification_is_recorded() {
1374
+ let mut input = String::from(
1375
+ "diff --git a/img.png b/img.png\n\
1376
+ Binary files a/img.png and b/img.png differ\n",
1377
+ );
1378
+ // Pad to clear min_lines_for_ccr.
1379
+ for _ in 0..60 {
1380
+ input.push_str("# pad\n");
1381
+ }
1382
+ let (_r, stats) = DiffCompressor::default().compress_with_stats(&input, "");
1383
+ assert_eq!(stats.binary_files_simplified.len(), 1, "{stats:?}");
1384
+ assert_eq!(
1385
+ stats.binary_files_simplified[0],
1386
+ "Binary files a/img.png and b/img.png differ"
1387
+ );
1388
+ }
1389
+
1390
+ #[test]
1391
+ fn min_compression_ratio_for_ccr_is_configurable() {
1392
+ // With default 0.8, the 8-file synthetic compresses 177→129 (ratio
1393
+ // 0.729) which beats the threshold → CCR marker emitted.
1394
+ let r = DiffCompressor::default().compress(&build_synthetic_diff(8), "");
1395
+ assert!(r.cache_key.is_some(), "default 0.8 should emit CCR");
1396
+
1397
+ // With 0.5, the same compression (0.729 ratio) does NOT beat
1398
+ // 0.5 → no CCR marker, no cache_key.
1399
+ let cfg = DiffCompressorConfig {
1400
+ min_compression_ratio_for_ccr: 0.5,
1401
+ ..Default::default()
1402
+ };
1403
+ let (r2, stats) =
1404
+ DiffCompressor::new(cfg).compress_with_stats(&build_synthetic_diff(8), "");
1405
+ assert!(
1406
+ r2.cache_key.is_none(),
1407
+ "0.5 threshold should suppress CCR for 0.729-ratio compression"
1408
+ );
1409
+ assert!(!stats.cache_key_emitted);
1410
+ assert!(stats.ccr_skipped_reason.is_some());
1411
+ }
1412
+
1413
+ #[test]
1414
+ fn compress_with_store_persists_original_under_cache_key() {
1415
+ // Regression: pre-fix, `DiffCompressor` minted a `cache_key` and
1416
+ // embedded `[... hash=abc123]` in the output marker but never
1417
+ // wrote the original anywhere — leaving Python ContentRouter
1418
+ // with a dangling marker that 404'd on retrieval. Now any caller
1419
+ // can pass a store and the marker resolves.
1420
+ use crate::ccr::InMemoryCcrStore;
1421
+ let store = InMemoryCcrStore::new();
1422
+ let input = build_synthetic_diff(8);
1423
+ let (r, stats) = DiffCompressor::default().compress_with_store(&input, "", Some(&store));
1424
+ let key = r.cache_key.expect("default 0.8 should emit CCR");
1425
+ assert!(stats.cache_key_emitted);
1426
+ // Marker text must reference the same key.
1427
+ assert!(r.compressed.contains(&format!("hash={key}")));
1428
+ // Original must round-trip through the store.
1429
+ assert_eq!(store.get(&key).as_deref(), Some(input.as_str()));
1430
+ }
1431
+
1432
+ #[test]
1433
+ fn compress_with_store_none_matches_compress_with_stats_behavior() {
1434
+ // Passing `None` must be byte-identical to the legacy API:
1435
+ // emits cache_key, leaves persistence to the caller. This pins
1436
+ // the parity-preserving-default contract.
1437
+ let input = build_synthetic_diff(8);
1438
+ let (legacy_result, _) = DiffCompressor::default().compress_with_stats(&input, "");
1439
+ let (new_result, _) = DiffCompressor::default().compress_with_store(&input, "", None);
1440
+ assert_eq!(new_result.compressed, legacy_result.compressed);
1441
+ assert_eq!(new_result.cache_key, legacy_result.cache_key);
1442
+ }
1443
+
1444
+ #[test]
1445
+ fn compress_with_store_no_op_when_ccr_skipped() {
1446
+ // When compression doesn't clear the savings threshold, no
1447
+ // cache_key is minted AND no store write happens.
1448
+ use crate::ccr::InMemoryCcrStore;
1449
+ let cfg = DiffCompressorConfig {
1450
+ min_compression_ratio_for_ccr: 0.1, // very strict
1451
+ ..Default::default()
1452
+ };
1453
+ let store = InMemoryCcrStore::new();
1454
+ let (r, _) = DiffCompressor::new(cfg).compress_with_store(
1455
+ &build_synthetic_diff(8),
1456
+ "",
1457
+ Some(&store),
1458
+ );
1459
+ assert!(r.cache_key.is_none());
1460
+ assert_eq!(store.len(), 0);
1461
+ }
1462
+
1463
+ #[test]
1464
+ fn score_constants_match_inline_values() {
1465
+ // Pin the constants so a future tuning PR has to update both.
1466
+ // (If you're updating these, also update the docs in the parity
1467
+ // contract — the scorer only fires when max_hunks_per_file caps,
1468
+ // so the impact is limited but observable.)
1469
+ assert_eq!(SCORE_CHANGE_DENSITY_WEIGHT, 0.03);
1470
+ assert_eq!(SCORE_CHANGE_DENSITY_CAP, 0.3);
1471
+ assert_eq!(SCORE_CONTEXT_WORD_WEIGHT, 0.2);
1472
+ assert_eq!(SCORE_CONTEXT_MIN_WORD_LEN, 2);
1473
+ assert_eq!(SCORE_PRIORITY_PATTERN_BOOST, 0.3);
1474
+ assert_eq!(SCORE_TOTAL_CAP, 1.0);
1475
+ }
1476
+
1477
+ // ─── Bug-fix tests (rename/combined-diff/no-newline/pre-diff) ──────────
1478
+
1479
+ /// Bug-fix test: rename markers (`rename from`, `rename to`,
1480
+ /// `similarity index`) must survive into the compressed output. Before
1481
+ /// the fix the parser captured them as `is_renamed=true` and the
1482
+ /// emitter dropped them entirely — output looked like a plain
1483
+ /// modification of the old path.
1484
+ #[test]
1485
+ fn bugfix_rename_markers_are_preserved_in_output() {
1486
+ let input = "diff --git a/old.py b/new.py\n\
1487
+ similarity index 92%\n\
1488
+ rename from old.py\n\
1489
+ rename to new.py\n\
1490
+ --- a/old.py\n\
1491
+ +++ b/new.py\n\
1492
+ @@ -1,3 +1,3 @@\n\
1493
+ ctx_a\n\
1494
+ -old_line\n\
1495
+ +new_line\n\
1496
+ ctx_b\n";
1497
+ // Below default min_lines_for_ccr=50 — drop the threshold so the
1498
+ // parser+emitter actually run.
1499
+ let cfg = DiffCompressorConfig {
1500
+ min_lines_for_ccr: 5,
1501
+ ..Default::default()
1502
+ };
1503
+ let r = DiffCompressor::new(cfg).compress(input, "");
1504
+ assert!(
1505
+ r.compressed.contains("similarity index 92%"),
1506
+ "missing 'similarity index' marker:\n{}",
1507
+ r.compressed
1508
+ );
1509
+ assert!(
1510
+ r.compressed.contains("rename from old.py"),
1511
+ "missing 'rename from':\n{}",
1512
+ r.compressed
1513
+ );
1514
+ assert!(
1515
+ r.compressed.contains("rename to new.py"),
1516
+ "missing 'rename to':\n{}",
1517
+ r.compressed
1518
+ );
1519
+ }
1520
+
1521
+ /// Bug-fix test: combined-diff (`@@@`) hunk content must NOT be
1522
+ /// silently dropped. Before the fix the hunk-header regex only
1523
+ /// matched `@@`, so 3-way merge hunks had `current_hunk` never set
1524
+ /// and all their content fell through to the no-op branch.
1525
+ #[test]
1526
+ fn bugfix_combined_diff_3way_content_is_parsed_and_emitted() {
1527
+ let input = "diff --git a/merge.py b/merge.py\n\
1528
+ --- a/merge.py\n\
1529
+ +++ b/merge.py\n\
1530
+ @@@ -1,3 -1,3 +1,4 @@@\n\
1531
+ unchanged_a\n\
1532
+ -old_branch_1\n\
1533
+ - old_branch_2\n\
1534
+ ++new_in_merge\n\
1535
+ +new_added\n\
1536
+ unchanged_b\n";
1537
+ let cfg = DiffCompressorConfig {
1538
+ min_lines_for_ccr: 5,
1539
+ ..Default::default()
1540
+ };
1541
+ let (r, stats) = DiffCompressor::new(cfg).compress_with_stats(input, "");
1542
+ assert!(
1543
+ r.compressed.contains("@@@ -1,3 -1,3 +1,4 @@@"),
1544
+ "@@@ header not preserved:\n{}",
1545
+ r.compressed
1546
+ );
1547
+ assert!(
1548
+ r.compressed.contains("++new_in_merge"),
1549
+ "combined-diff +/+ content not preserved:\n{}",
1550
+ r.compressed
1551
+ );
1552
+ assert!(
1553
+ stats.files_total > 0,
1554
+ "parser found no files; combined-diff still broken"
1555
+ );
1556
+ }
1557
+
1558
+ /// Bug-fix test: `` markers must survive
1559
+ /// the context trim regardless of distance from a `+`/`-` line. Before
1560
+ /// the fix, `_reduce_context` only kept lines within max_context_lines
1561
+ /// of a change; trailing `\` markers got cut whenever they were too
1562
+ /// far away.
1563
+ #[test]
1564
+ fn bugfix_no_newline_marker_preserved_despite_distance() {
1565
+ // Place the `+/-` change far from the trailing `\` marker so the
1566
+ // context trim would, if buggy, drop the marker.
1567
+ let input = "diff --git a/last.txt b/last.txt\n\
1568
+ --- a/last.txt\n\
1569
+ +++ b/last.txt\n\
1570
+ @@ -1,8 +1,8 @@\n\
1571
+ -old_first\n\
1572
+ +new_first\n\
1573
+ ctx_a\n\
1574
+ ctx_b\n\
1575
+ ctx_c\n\
1576
+ ctx_d\n\
1577
+ ctx_e\n\
1578
+ ctx_f\n\
1579
+ \\n";
1580
+ let cfg = DiffCompressorConfig {
1581
+ min_lines_for_ccr: 5,
1582
+ ..Default::default()
1583
+ };
1584
+ let r = DiffCompressor::new(cfg).compress(input, "");
1585
+ assert!(
1586
+ r.compressed.contains("\"),
1587
+ "no-newline marker dropped by context trim:\n{}",
1588
+ r.compressed
1589
+ );
1590
+ }
1591
+
1592
+ /// Routing-gap test: `diff --combined <path>` (merge-commit header)
1593
+ /// must start a new file section. Before the fix, only `diff --git`
1594
+ /// was recognized — merge diffs from `git log -p` got treated as one
1595
+ /// big pre-diff blob and passed through unchanged.
1596
+ #[test]
1597
+ fn gap_diff_combined_header_starts_a_file() {
1598
+ let input = "diff --combined merge.py\n\
1599
+ index abc..def..ghi 100644\n\
1600
+ --- a/merge.py\n\
1601
+ +++ b/merge.py\n\
1602
+ @@@ -1,3 -1,3 +1,4 @@@\n\
1603
+ ctx_a\n\
1604
+ - removed_p1\n\
1605
+ -removed_p2\n\
1606
+ ++added_in_merge\n\
1607
+ ctx_b\n";
1608
+ let cfg = DiffCompressorConfig {
1609
+ min_lines_for_ccr: 5,
1610
+ ..Default::default()
1611
+ };
1612
+ let r = DiffCompressor::new(cfg).compress(input, "");
1613
+ assert_eq!(r.files_affected, 1);
1614
+ assert!(r.compressed.contains("diff --combined merge.py"));
1615
+ assert!(r.compressed.contains("@@@ -1,3 -1,3 +1,4 @@@"));
1616
+ assert!(r.compressed.contains("++added_in_merge"));
1617
+ }
1618
+
1619
+ /// Routing-gap test: `diff --cc <path>` (alternate merge-commit form).
1620
+ /// Same reasoning as `diff_combined`.
1621
+ #[test]
1622
+ fn gap_diff_cc_header_starts_a_file() {
1623
+ let input = "diff --cc cc_target.py\n\
1624
+ index abc..def..ghi\n\
1625
+ --- a/cc_target.py\n\
1626
+ +++ b/cc_target.py\n\
1627
+ @@@ -1,3 -1,3 +1,4 @@@\n\
1628
+ ctx\n\
1629
+ - p1_removed\n\
1630
+ -p2_removed\n\
1631
+ ++merge_added\n\
1632
+ more_ctx\n";
1633
+ let cfg = DiffCompressorConfig {
1634
+ min_lines_for_ccr: 5,
1635
+ ..Default::default()
1636
+ };
1637
+ let r = DiffCompressor::new(cfg).compress(input, "");
1638
+ assert_eq!(r.files_affected, 1);
1639
+ assert!(r.compressed.contains("diff --cc cc_target.py"));
1640
+ assert!(r.compressed.contains("++merge_added"));
1641
+ }
1642
+
1643
+ /// Bug-fix test: pre-diff content (commit headers, email-style
1644
+ /// metadata) is preserved verbatim before the diff sections. Before
1645
+ /// the fix, anything before the first `diff --git` was silently
1646
+ /// dropped — `git log -p` output lost commit messages, Author, Date,
1647
+ /// etc.
1648
+ #[test]
1649
+ fn bugfix_pre_diff_content_is_preserved() {
1650
+ let input = "commit abc1234567890\n\
1651
+ Author: Tester <t@example.com>\n\
1652
+ Date: Mon Apr 25 12:00:00 2026\n\
1653
+ \n Refactor: rename and modify\n\n\
1654
+ diff --git a/x.py b/x.py\n\
1655
+ --- a/x.py\n\
1656
+ +++ b/x.py\n\
1657
+ @@ -1 +1 @@\n\
1658
+ -a\n\
1659
+ +b\n";
1660
+ let cfg = DiffCompressorConfig {
1661
+ min_lines_for_ccr: 5,
1662
+ ..Default::default()
1663
+ };
1664
+ let r = DiffCompressor::new(cfg).compress(input, "");
1665
+ assert!(
1666
+ r.compressed.starts_with("commit abc1234567890"),
1667
+ "pre-diff commit header dropped:\n{}",
1668
+ r.compressed
1669
+ );
1670
+ assert!(
1671
+ r.compressed.contains("Author: Tester"),
1672
+ "pre-diff Author header dropped:\n{}",
1673
+ r.compressed
1674
+ );
1675
+ assert!(
1676
+ r.compressed.contains("Refactor: rename and modify"),
1677
+ "pre-diff commit message dropped:\n{}",
1678
+ r.compressed
1679
+ );
1680
+ // And the diff itself is still there.
1681
+ assert!(r.compressed.contains("diff --git a/x.py b/x.py"));
1682
+ assert!(r.compressed.contains("-a"));
1683
+ assert!(r.compressed.contains("+b"));
1684
+ }
1685
+ }