xithead 1.5.0 → 1.5.1

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 (649) hide show
  1. package/design-system/README.md +80 -0
  2. package/package.json +20 -1
  3. package/public/apple-touch-icon.png +0 -0
  4. package/public/logo-transparent.png +0 -0
  5. package/public/xithead.ps1 +937 -0
  6. package/scripts/README.md +77 -0
  7. package/scripts/audit_wheel_glibc_symbols.py +217 -0
  8. package/scripts/build-master-design-system.cjs +33 -0
  9. package/scripts/build_rust_extension.sh +58 -0
  10. package/scripts/changelog-gen.py +203 -0
  11. package/scripts/eval_output_shaper.py +235 -0
  12. package/scripts/export_kompress_v2_onnx.py +267 -0
  13. package/scripts/fixtures/anthropic_replay_body.json +133 -0
  14. package/scripts/fixtures/codex_response_create_frame.json +52 -0
  15. package/scripts/install-git-hooks.sh +104 -0
  16. package/scripts/install.ps1 +1809 -0
  17. package/scripts/install.sh +1673 -0
  18. package/scripts/pr-governance.py +297 -0
  19. package/scripts/record_fixtures.py +59 -0
  20. package/scripts/refresh_model_limits.sh +48 -0
  21. package/scripts/replay_codex_ws_load.py +445 -0
  22. package/scripts/repro_codex_replay.py +699 -0
  23. package/scripts/smoke_issue_327.py +233 -0
  24. package/scripts/sync-plugin-versions.py +116 -0
  25. package/scripts/tests/test_changelog_gen.py +302 -0
  26. package/scripts/tests/test_pr_governance.py +163 -0
  27. package/scripts/tests/test_pr_health_labels.py +94 -0
  28. package/scripts/tests/test_pr_health_workflow.py +14 -0
  29. package/scripts/tests/test_sync_plugin_versions.py +131 -0
  30. package/scripts/tests/test_version_sync.py +291 -0
  31. package/scripts/validate-workflows.sh +39 -0
  32. package/scripts/verify-versions.py +106 -0
  33. package/scripts/version-sync.py +207 -0
  34. package/tailwind.config.js +31 -0
  35. package/tsconfig.json +84 -0
  36. package/.actrc +0 -14
  37. package/.actrc.local.example +0 -15
  38. package/.changelog.md +0 -2
  39. package/.claude/agents/academic-anthropologist.md +0 -125
  40. package/.claude/agents/academic-geographer.md +0 -127
  41. package/.claude/agents/academic-historian.md +0 -123
  42. package/.claude/agents/academic-narratologist.md +0 -118
  43. package/.claude/agents/academic-psychologist.md +0 -118
  44. package/.claude/agents/academic-statistician.md +0 -144
  45. package/.claude/agents/accounts-payable-agent.md +0 -205
  46. package/.claude/agents/agentic-identity-trust.md +0 -394
  47. package/.claude/agents/agents-orchestrator.md +0 -367
  48. package/.claude/agents/automation-governance-architect.md +0 -216
  49. package/.claude/agents/blender-addon-engineer.md +0 -243
  50. package/.claude/agents/business-strategist.md +0 -488
  51. package/.claude/agents/change-management-consultant.md +0 -497
  52. package/.claude/agents/chief-financial-officer.md +0 -388
  53. package/.claude/agents/corporate-training-designer.md +0 -192
  54. package/.claude/agents/customer-service.md +0 -398
  55. package/.claude/agents/customer-success-manager.md +0 -460
  56. package/.claude/agents/data-consolidation-agent.md +0 -60
  57. package/.claude/agents/data-privacy-officer.md +0 -412
  58. package/.claude/agents/design-brand-guardian.md +0 -322
  59. package/.claude/agents/design-image-prompt-engineer.md +0 -236
  60. package/.claude/agents/design-inclusive-visuals-specialist.md +0 -73
  61. package/.claude/agents/design-persona-walkthrough.md +0 -272
  62. package/.claude/agents/design-ui-designer.md +0 -386
  63. package/.claude/agents/design-ui-finish-gate-reviewer.md +0 -217
  64. package/.claude/agents/design-ux-architect.md +0 -482
  65. package/.claude/agents/design-ux-researcher.md +0 -329
  66. package/.claude/agents/design-visual-storyteller.md +0 -149
  67. package/.claude/agents/design-whimsy-injector.md +0 -460
  68. package/.claude/agents/economy-designer.md +0 -156
  69. package/.claude/agents/engineering-ai-data-remediation-engineer.md +0 -211
  70. package/.claude/agents/engineering-ai-engineer.md +0 -146
  71. package/.claude/agents/engineering-api-platform-engineer.md +0 -181
  72. package/.claude/agents/engineering-ats-validator-architect.md +0 -383
  73. package/.claude/agents/engineering-autonomous-optimization-architect.md +0 -121
  74. package/.claude/agents/engineering-backend-architect.md +0 -255
  75. package/.claude/agents/engineering-china-network-engineer.md +0 -252
  76. package/.claude/agents/engineering-cms-developer.md +0 -536
  77. package/.claude/agents/engineering-code-reviewer.md +0 -76
  78. package/.claude/agents/engineering-codebase-onboarding-engineer.md +0 -173
  79. package/.claude/agents/engineering-data-engineer.md +0 -349
  80. package/.claude/agents/engineering-data-visualization-engineer.md +0 -151
  81. package/.claude/agents/engineering-database-optimizer.md +0 -188
  82. package/.claude/agents/engineering-database-reliability-engineer.md +0 -201
  83. package/.claude/agents/engineering-desktop-app-engineer.md +0 -209
  84. package/.claude/agents/engineering-developer-tooling-engineer.md +0 -153
  85. package/.claude/agents/engineering-devops-automator.md +0 -385
  86. package/.claude/agents/engineering-drupal-performance.md +0 -347
  87. package/.claude/agents/engineering-drupal-shopping-cart.md +0 -360
  88. package/.claude/agents/engineering-electrical-engineer.md +0 -575
  89. package/.claude/agents/engineering-email-intelligence-engineer.md +0 -390
  90. package/.claude/agents/engineering-embedded-firmware-engineer.md +0 -196
  91. package/.claude/agents/engineering-feishu-integration-developer.md +0 -606
  92. package/.claude/agents/engineering-filament-optimization-specialist.md +0 -283
  93. package/.claude/agents/engineering-finops-engineer.md +0 -164
  94. package/.claude/agents/engineering-frontend-developer.md +0 -257
  95. package/.claude/agents/engineering-gaussdb-expert.md +0 -334
  96. package/.claude/agents/engineering-git-workflow-master.md +0 -98
  97. package/.claude/agents/engineering-i18n-engineer.md +0 -214
  98. package/.claude/agents/engineering-identity-access-engineer.md +0 -217
  99. package/.claude/agents/engineering-incident-response-commander.md +0 -444
  100. package/.claude/agents/engineering-iot-fleet-engineer.md +0 -148
  101. package/.claude/agents/engineering-it-service-manager.md +0 -561
  102. package/.claude/agents/engineering-knowledge-graph-engineer.md +0 -372
  103. package/.claude/agents/engineering-llm-post-training-engineer.md +0 -166
  104. package/.claude/agents/engineering-minimal-change-engineer.md +0 -207
  105. package/.claude/agents/engineering-mobile-app-builder.md +0 -493
  106. package/.claude/agents/engineering-mobile-release-engineer.md +0 -164
  107. package/.claude/agents/engineering-multi-agent-systems-architect.md +0 -600
  108. package/.claude/agents/engineering-network-engineer.md +0 -245
  109. package/.claude/agents/engineering-orgscript-engineer.md +0 -113
  110. package/.claude/agents/engineering-payments-billing-engineer.md +0 -228
  111. package/.claude/agents/engineering-pdf-engine-architect.md +0 -696
  112. package/.claude/agents/engineering-platform-engineer.md +0 -270
  113. package/.claude/agents/engineering-privacy-engineer.md +0 -152
  114. package/.claude/agents/engineering-prompt-engineer.md +0 -209
  115. package/.claude/agents/engineering-rag-pipeline-engineer.md +0 -450
  116. package/.claude/agents/engineering-rapid-prototyper.md +0 -466
  117. package/.claude/agents/engineering-realtime-collaboration-engineer.md +0 -200
  118. package/.claude/agents/engineering-rust-refactoring-specialist.md +0 -313
  119. package/.claude/agents/engineering-search-relevance-engineer.md +0 -237
  120. package/.claude/agents/engineering-section-508-specialist.md +0 -339
  121. package/.claude/agents/engineering-senior-developer.md +0 -176
  122. package/.claude/agents/engineering-servicenow-developer-mentor.md +0 -180
  123. package/.claude/agents/engineering-software-architect.md +0 -112
  124. package/.claude/agents/engineering-solidity-smart-contract-engineer.md +0 -522
  125. package/.claude/agents/engineering-sre.md +0 -90
  126. package/.claude/agents/engineering-technical-writer.md +0 -393
  127. package/.claude/agents/engineering-universal-document-compiler.md +0 -370
  128. package/.claude/agents/engineering-uswds-developer.md +0 -340
  129. package/.claude/agents/engineering-video-streaming-engineer.md +0 -151
  130. package/.claude/agents/engineering-voice-ai-integration-engineer.md +0 -584
  131. package/.claude/agents/engineering-webassembly-engineer.md +0 -153
  132. package/.claude/agents/engineering-wechat-mini-program-developer.md +0 -356
  133. package/.claude/agents/engineering-wordpress-performance.md +0 -346
  134. package/.claude/agents/engineering-wordpress-shopping-cart.md +0 -346
  135. package/.claude/agents/esg-sustainability-officer.md +0 -396
  136. package/.claude/agents/finance-bookkeeper-controller.md +0 -260
  137. package/.claude/agents/finance-financial-analyst.md +0 -234
  138. package/.claude/agents/finance-fpa-analyst.md +0 -263
  139. package/.claude/agents/finance-investment-researcher.md +0 -272
  140. package/.claude/agents/finance-tax-strategist.md +0 -239
  141. package/.claude/agents/game-audio-engineer.md +0 -264
  142. package/.claude/agents/game-designer.md +0 -167
  143. package/.claude/agents/gis-3d-scene-developer.md +0 -111
  144. package/.claude/agents/gis-analyst.md +0 -91
  145. package/.claude/agents/gis-bim-specialist.md +0 -108
  146. package/.claude/agents/gis-cartography-designer.md +0 -150
  147. package/.claude/agents/gis-drone-reality-mapping.md +0 -120
  148. package/.claude/agents/gis-geoai-ml-engineer.md +0 -105
  149. package/.claude/agents/gis-geoprocessing-specialist.md +0 -97
  150. package/.claude/agents/gis-qa-engineer.md +0 -133
  151. package/.claude/agents/gis-solution-engineer.md +0 -101
  152. package/.claude/agents/gis-spatial-data-engineer.md +0 -97
  153. package/.claude/agents/gis-spatial-data-scientist.md +0 -111
  154. package/.claude/agents/gis-technical-consultant.md +0 -86
  155. package/.claude/agents/gis-web-gis-developer.md +0 -108
  156. package/.claude/agents/godot-gameplay-scripter.md +0 -338
  157. package/.claude/agents/godot-multiplayer-engineer.md +0 -301
  158. package/.claude/agents/godot-shader-developer.md +0 -267
  159. package/.claude/agents/government-digital-presales-consultant.md +0 -363
  160. package/.claude/agents/grant-writer.md +0 -511
  161. package/.claude/agents/healthcare-aging-parent-care-companion.md +0 -414
  162. package/.claude/agents/healthcare-clinical-evidence-agent.md +0 -231
  163. package/.claude/agents/healthcare-customer-service.md +0 -389
  164. package/.claude/agents/healthcare-innovation-strategist.md +0 -433
  165. package/.claude/agents/healthcare-marketing-compliance.md +0 -395
  166. package/.claude/agents/healthcare-sovereign-health-systems-agent.md +0 -312
  167. package/.claude/agents/hospitality-guest-services.md +0 -603
  168. package/.claude/agents/hr-onboarding.md +0 -451
  169. package/.claude/agents/identity-graph-operator.md +0 -303
  170. package/.claude/agents/language-translator.md +0 -264
  171. package/.claude/agents/legal-billing-time-tracking.md +0 -569
  172. package/.claude/agents/legal-client-intake.md +0 -492
  173. package/.claude/agents/legal-document-review.md +0 -454
  174. package/.claude/agents/level-designer.md +0 -208
  175. package/.claude/agents/loan-officer-assistant.md +0 -555
  176. package/.claude/agents/lsp-index-engineer.md +0 -320
  177. package/.claude/agents/ma-integration-manager.md +0 -427
  178. package/.claude/agents/macos-spatial-metal-engineer.md +0 -337
  179. package/.claude/agents/marketing-aeo-foundations.md +0 -264
  180. package/.claude/agents/marketing-agentic-search-optimizer.md +0 -279
  181. package/.claude/agents/marketing-ai-citation-strategist.md +0 -172
  182. package/.claude/agents/marketing-app-store-optimizer.md +0 -321
  183. package/.claude/agents/marketing-baidu-seo-specialist.md +0 -226
  184. package/.claude/agents/marketing-bilibili-content-strategist.md +0 -199
  185. package/.claude/agents/marketing-book-co-author.md +0 -110
  186. package/.claude/agents/marketing-carousel-growth-engine.md +0 -204
  187. package/.claude/agents/marketing-china-ecommerce-operator.md +0 -283
  188. package/.claude/agents/marketing-china-market-localization-strategist.md +0 -283
  189. package/.claude/agents/marketing-content-creator.md +0 -54
  190. package/.claude/agents/marketing-cross-border-ecommerce.md +0 -259
  191. package/.claude/agents/marketing-developer-community-builder.md +0 -285
  192. package/.claude/agents/marketing-douyin-strategist.md +0 -149
  193. package/.claude/agents/marketing-email-strategist.md +0 -249
  194. package/.claude/agents/marketing-global-podcast-strategist.md +0 -206
  195. package/.claude/agents/marketing-growth-hacker.md +0 -54
  196. package/.claude/agents/marketing-instagram-curator.md +0 -113
  197. package/.claude/agents/marketing-kuaishou-strategist.md +0 -223
  198. package/.claude/agents/marketing-linkedin-content-creator.md +0 -214
  199. package/.claude/agents/marketing-livestream-commerce-coach.md +0 -305
  200. package/.claude/agents/marketing-multi-platform-publisher.md +0 -217
  201. package/.claude/agents/marketing-podcast-strategist.md +0 -277
  202. package/.claude/agents/marketing-pr-communications-manager.md +0 -473
  203. package/.claude/agents/marketing-private-domain-operator.md +0 -308
  204. package/.claude/agents/marketing-reddit-community-builder.md +0 -123
  205. package/.claude/agents/marketing-seo-specialist.md +0 -370
  206. package/.claude/agents/marketing-short-video-editing-coach.md +0 -412
  207. package/.claude/agents/marketing-social-media-strategist.md +0 -125
  208. package/.claude/agents/marketing-tiktok-strategist.md +0 -125
  209. package/.claude/agents/marketing-twitter-engager.md +0 -126
  210. package/.claude/agents/marketing-video-optimization-specialist.md +0 -119
  211. package/.claude/agents/marketing-wechat-official-account.md +0 -145
  212. package/.claude/agents/marketing-weibo-strategist.md +0 -240
  213. package/.claude/agents/marketing-x-twitter-intelligence-analyst.md +0 -161
  214. package/.claude/agents/marketing-xiaohongshu-specialist.md +0 -138
  215. package/.claude/agents/marketing-zhihu-strategist.md +0 -162
  216. package/.claude/agents/medical-billing-coding-specialist.md +0 -491
  217. package/.claude/agents/narrative-designer.md +0 -243
  218. package/.claude/agents/operations-manager.md +0 -399
  219. package/.claude/agents/organizational-psychologist.md +0 -391
  220. package/.claude/agents/paid-media-auditor.md +0 -71
  221. package/.claude/agents/paid-media-creative-strategist.md +0 -71
  222. package/.claude/agents/paid-media-paid-social-strategist.md +0 -71
  223. package/.claude/agents/paid-media-ppc-strategist.md +0 -71
  224. package/.claude/agents/paid-media-programmatic-buyer.md +0 -71
  225. package/.claude/agents/paid-media-search-query-analyst.md +0 -71
  226. package/.claude/agents/paid-media-tracking-specialist.md +0 -71
  227. package/.claude/agents/personal-growth-mentor.md +0 -159
  228. package/.claude/agents/product-behavioral-nudge-engine.md +0 -83
  229. package/.claude/agents/product-dx-engineer.md +0 -332
  230. package/.claude/agents/product-feedback-synthesizer.md +0 -119
  231. package/.claude/agents/product-manager.md +0 -469
  232. package/.claude/agents/product-sprint-prioritizer.md +0 -154
  233. package/.claude/agents/product-trend-researcher.md +0 -159
  234. package/.claude/agents/project-management-experiment-tracker.md +0 -198
  235. package/.claude/agents/project-management-jira-workflow-steward.md +0 -233
  236. package/.claude/agents/project-management-meeting-notes-specialist.md +0 -95
  237. package/.claude/agents/project-management-project-shepherd.md +0 -194
  238. package/.claude/agents/project-management-studio-operations.md +0 -200
  239. package/.claude/agents/project-management-studio-producer.md +0 -203
  240. package/.claude/agents/project-manager-senior.md +0 -135
  241. package/.claude/agents/real-estate-buyer-seller.md +0 -596
  242. package/.claude/agents/recruitment-specialist.md +0 -515
  243. package/.claude/agents/report-distribution-agent.md +0 -65
  244. package/.claude/agents/research-synthesist.md +0 -136
  245. package/.claude/agents/resume-tailor.md +0 -230
  246. package/.claude/agents/retail-customer-returns.md +0 -566
  247. package/.claude/agents/roblox-avatar-creator.md +0 -297
  248. package/.claude/agents/roblox-experience-designer.md +0 -306
  249. package/.claude/agents/roblox-systems-scripter.md +0 -332
  250. package/.claude/agents/sales-account-strategist.md +0 -227
  251. package/.claude/agents/sales-coach.md +0 -271
  252. package/.claude/agents/sales-data-extraction-agent.md +0 -67
  253. package/.claude/agents/sales-deal-strategist.md +0 -180
  254. package/.claude/agents/sales-discovery-coach.md +0 -225
  255. package/.claude/agents/sales-engineer.md +0 -182
  256. package/.claude/agents/sales-offer-lead-gen-strategist.md +0 -257
  257. package/.claude/agents/sales-outbound-strategist.md +0 -201
  258. package/.claude/agents/sales-outreach.md +0 -425
  259. package/.claude/agents/sales-pipeline-analyst.md +0 -267
  260. package/.claude/agents/sales-proposal-strategist.md +0 -217
  261. package/.claude/agents/security-ai-generated-code-auditor.md +0 -207
  262. package/.claude/agents/security-appsec-engineer.md +0 -536
  263. package/.claude/agents/security-architect.md +0 -307
  264. package/.claude/agents/security-blockchain-security-auditor.md +0 -482
  265. package/.claude/agents/security-cloud-security-architect.md +0 -576
  266. package/.claude/agents/security-compliance-auditor.md +0 -158
  267. package/.claude/agents/security-incident-responder.md +0 -450
  268. package/.claude/agents/security-penetration-tester.md +0 -399
  269. package/.claude/agents/security-secrets-credential-engineer.md +0 -189
  270. package/.claude/agents/security-senior-secops.md +0 -760
  271. package/.claude/agents/security-threat-detection-engineer.md +0 -553
  272. package/.claude/agents/security-threat-intelligence-analyst.md +0 -661
  273. package/.claude/agents/specialized-chief-of-staff.md +0 -279
  274. package/.claude/agents/specialized-civil-engineer.md +0 -356
  275. package/.claude/agents/specialized-codebase-archaeologist.md +0 -341
  276. package/.claude/agents/specialized-cultural-intelligence-strategist.md +0 -88
  277. package/.claude/agents/specialized-developer-advocate.md +0 -317
  278. package/.claude/agents/specialized-document-generator.md +0 -55
  279. package/.claude/agents/specialized-fedramp-rmf-compliance.md +0 -378
  280. package/.claude/agents/specialized-focus-music-architect.md +0 -175
  281. package/.claude/agents/specialized-french-consulting-market.md +0 -194
  282. package/.claude/agents/specialized-korean-business-navigator.md +0 -216
  283. package/.claude/agents/specialized-master-plan-architect.md +0 -157
  284. package/.claude/agents/specialized-mcp-builder.md +0 -260
  285. package/.claude/agents/specialized-model-qa.md +0 -528
  286. package/.claude/agents/specialized-pricing-analyst.md +0 -243
  287. package/.claude/agents/specialized-salesforce-architect.md +0 -182
  288. package/.claude/agents/specialized-strategy-duel-agent.md +0 -130
  289. package/.claude/agents/specialized-workflow-architect.md +0 -597
  290. package/.claude/agents/study-abroad-advisor.md +0 -282
  291. package/.claude/agents/supply-chain-strategist.md +0 -591
  292. package/.claude/agents/support-analytics-reporter.md +0 -387
  293. package/.claude/agents/support-executive-summary-generator.md +0 -212
  294. package/.claude/agents/support-finance-tracker.md +0 -480
  295. package/.claude/agents/support-infrastructure-maintainer.md +0 -628
  296. package/.claude/agents/support-legal-compliance-checker.md +0 -591
  297. package/.claude/agents/support-support-responder.md +0 -607
  298. package/.claude/agents/technical-artist.md +0 -233
  299. package/.claude/agents/terminal-integration-specialist.md +0 -70
  300. package/.claude/agents/testing-accessibility-auditor.md +0 -327
  301. package/.claude/agents/testing-api-tester.md +0 -334
  302. package/.claude/agents/testing-evidence-collector.md +0 -210
  303. package/.claude/agents/testing-performance-benchmarker.md +0 -283
  304. package/.claude/agents/testing-reality-checker.md +0 -249
  305. package/.claude/agents/testing-test-automation-engineer.md +0 -196
  306. package/.claude/agents/testing-test-results-analyzer.md +0 -330
  307. package/.claude/agents/testing-tool-evaluator.md +0 -416
  308. package/.claude/agents/testing-workflow-optimizer.md +0 -463
  309. package/.claude/agents/unity-architect.md +0 -271
  310. package/.claude/agents/unity-editor-tool-developer.md +0 -310
  311. package/.claude/agents/unity-multiplayer-engineer.md +0 -323
  312. package/.claude/agents/unity-shader-graph-artist.md +0 -269
  313. package/.claude/agents/unreal-multiplayer-architect.md +0 -364
  314. package/.claude/agents/unreal-systems-engineer.md +0 -322
  315. package/.claude/agents/unreal-technical-artist.md +0 -256
  316. package/.claude/agents/unreal-world-builder.md +0 -273
  317. package/.claude/agents/visionos-spatial-engineer.md +0 -54
  318. package/.claude/agents/xr-cockpit-interaction-specialist.md +0 -32
  319. package/.claude/agents/xr-immersive-developer.md +0 -32
  320. package/.claude/agents/xr-interface-architect.md +0 -32
  321. package/.claude/agents/zk-steward.md +0 -211
  322. package/.claude-plugin/marketplace.json +0 -30
  323. package/.commitlintrc.json +0 -26
  324. package/.devcontainer/Dockerfile +0 -24
  325. package/.devcontainer/devcontainer.json +0 -70
  326. package/.devcontainer/docker-compose.memory.yml +0 -42
  327. package/.devcontainer/memory-stack/devcontainer.json +0 -84
  328. package/.devcontainer/post-create.sh +0 -83
  329. package/.dockerignore +0 -23
  330. package/.env.act.example +0 -15
  331. package/.env.example +0 -171
  332. package/.eslintrc.json +0 -16
  333. package/.git-blame-ignore-revs +0 -10
  334. package/.gitattributes +0 -2
  335. package/.gitguardian.yaml +0 -50
  336. package/.githooks/pre-commit +0 -6
  337. package/.pre-commit-config.yaml +0 -30
  338. package/.release-please-config-xithead.json +0 -22
  339. package/.release-please-config.json +0 -44
  340. package/.release-please-manifest-xithead.json +0 -3
  341. package/.release-please-manifest.json +0 -3
  342. package/CODE_OF_CONDUCT.md +0 -133
  343. package/CONTRIBUTING.md +0 -133
  344. package/Cargo.lock +0 -5557
  345. package/Cargo.toml +0 -121
  346. package/Dockerfile +0 -38
  347. package/Dockerfile.proxy +0 -48
  348. package/ENTERPRISE.md +0 -5
  349. package/FEATURES_ADVANCED.md +0 -311
  350. package/Headroom-2.gif +0 -0
  351. package/HeadroomDemo-Fast.gif +0 -0
  352. package/MANIFEST.in +0 -4
  353. package/MODERNIZATION_GUIDE.md +0 -358
  354. package/Makefile +0 -140
  355. package/NOTICE +0 -43
  356. package/NPM_TOKEN_SETUP.md +0 -81
  357. package/PR.md +0 -170
  358. package/PUBLISH.md +0 -77
  359. package/README_FRONTEND.md +0 -196
  360. package/REALIGNMENT/00-overview.md +0 -53
  361. package/REALIGNMENT/01-bug-list.md +0 -421
  362. package/REALIGNMENT/02-architecture.md +0 -322
  363. package/REALIGNMENT/03-phase-A-lockdown.md +0 -420
  364. package/REALIGNMENT/04-phase-B-live-zone.md +0 -470
  365. package/REALIGNMENT/05-phase-C-rust-proxy.md +0 -329
  366. package/REALIGNMENT/06-phase-D-bedrock-vertex.md +0 -222
  367. package/REALIGNMENT/07-phase-E-cache-stabilization.md +0 -338
  368. package/REALIGNMENT/08-phase-F-auth-mode.md +0 -254
  369. package/REALIGNMENT/09-phase-G-rtk-observability.md +0 -194
  370. package/REALIGNMENT/10-phase-H-python-retirement.md +0 -214
  371. package/REALIGNMENT/11-phase-I-test-infra.md +0 -385
  372. package/REALIGNMENT/12-decisions-needed.md +0 -196
  373. package/REALIGNMENT/INDEX.md +0 -82
  374. package/REFACTORING_CAMPAIGN.md +0 -277
  375. package/RESTRUCTURE_PLAN.md +0 -100
  376. package/RUST_DEV.md +0 -361
  377. package/SECURITY.md +0 -65
  378. package/SETUP_AUTO_PUBLISH.md +0 -164
  379. package/TESTING-copilot-subscription.md +0 -153
  380. package/codecov.yml +0 -34
  381. package/crates/headroom-core/Cargo.toml +0 -165
  382. package/crates/headroom-core/benches/auth_mode.rs +0 -74
  383. package/crates/headroom-core/benches/ccr_store.rs +0 -224
  384. package/crates/headroom-core/benches/tokenizer.rs +0 -52
  385. package/crates/headroom-core/config/pipeline.toml +0 -151
  386. package/crates/headroom-core/proptest-regressions/transforms/tag_protector.txt +0 -9
  387. package/crates/headroom-core/src/auth_mode.rs +0 -250
  388. package/crates/headroom-core/src/cache_control.rs +0 -414
  389. package/crates/headroom-core/src/ccr/backends/in_memory.rs +0 -317
  390. package/crates/headroom-core/src/ccr/backends/mod.rs +0 -152
  391. package/crates/headroom-core/src/ccr/backends/redis.rs +0 -146
  392. package/crates/headroom-core/src/ccr/backends/sqlite.rs +0 -205
  393. package/crates/headroom-core/src/ccr/mod.rs +0 -119
  394. package/crates/headroom-core/src/compression_policy.rs +0 -505
  395. package/crates/headroom-core/src/lib.rs +0 -33
  396. package/crates/headroom-core/src/relevance/base.rs +0 -139
  397. package/crates/headroom-core/src/relevance/bm25.rs +0 -385
  398. package/crates/headroom-core/src/relevance/embedding.rs +0 -354
  399. package/crates/headroom-core/src/relevance/hybrid.rs +0 -364
  400. package/crates/headroom-core/src/relevance/mod.rs +0 -64
  401. package/crates/headroom-core/src/signals/keyword_detector.rs +0 -433
  402. package/crates/headroom-core/src/signals/line_importance.rs +0 -84
  403. package/crates/headroom-core/src/signals/mod.rs +0 -61
  404. package/crates/headroom-core/src/signals/tiered.rs +0 -141
  405. package/crates/headroom-core/src/tokenizer/estimator.rs +0 -152
  406. package/crates/headroom-core/src/tokenizer/hf_impl.rs +0 -314
  407. package/crates/headroom-core/src/tokenizer/mod.rs +0 -56
  408. package/crates/headroom-core/src/tokenizer/registry.rs +0 -342
  409. package/crates/headroom-core/src/tokenizer/tiktoken_impl.rs +0 -265
  410. package/crates/headroom-core/src/transforms/adaptive_sizer.rs +0 -610
  411. package/crates/headroom-core/src/transforms/anchor_selector.rs +0 -1189
  412. package/crates/headroom-core/src/transforms/content_detector.rs +0 -769
  413. package/crates/headroom-core/src/transforms/detection.rs +0 -222
  414. package/crates/headroom-core/src/transforms/diff_compressor.rs +0 -1685
  415. package/crates/headroom-core/src/transforms/live_zone.rs +0 -2967
  416. package/crates/headroom-core/src/transforms/log_compressor.rs +0 -1295
  417. package/crates/headroom-core/src/transforms/magika_detector.rs +0 -395
  418. package/crates/headroom-core/src/transforms/mod.rs +0 -64
  419. package/crates/headroom-core/src/transforms/pipeline/config.rs +0 -331
  420. package/crates/headroom-core/src/transforms/pipeline/mod.rs +0 -103
  421. package/crates/headroom-core/src/transforms/pipeline/offloads/diff_noise.rs +0 -524
  422. package/crates/headroom-core/src/transforms/pipeline/offloads/diff_offload.rs +0 -279
  423. package/crates/headroom-core/src/transforms/pipeline/offloads/json_offload.rs +0 -400
  424. package/crates/headroom-core/src/transforms/pipeline/offloads/log_offload.rs +0 -284
  425. package/crates/headroom-core/src/transforms/pipeline/offloads/mod.rs +0 -34
  426. package/crates/headroom-core/src/transforms/pipeline/offloads/search_offload.rs +0 -331
  427. package/crates/headroom-core/src/transforms/pipeline/orchestrator.rs +0 -848
  428. package/crates/headroom-core/src/transforms/pipeline/reformats/json_minifier.rs +0 -175
  429. package/crates/headroom-core/src/transforms/pipeline/reformats/log_template.rs +0 -545
  430. package/crates/headroom-core/src/transforms/pipeline/reformats/mod.rs +0 -12
  431. package/crates/headroom-core/src/transforms/pipeline/traits.rs +0 -338
  432. package/crates/headroom-core/src/transforms/recommendations.rs +0 -329
  433. package/crates/headroom-core/src/transforms/safety.rs +0 -215
  434. package/crates/headroom-core/src/transforms/search_compressor.rs +0 -902
  435. package/crates/headroom-core/src/transforms/smart_crusher/analyzer.rs +0 -1262
  436. package/crates/headroom-core/src/transforms/smart_crusher/anchors.rs +0 -407
  437. package/crates/headroom-core/src/transforms/smart_crusher/builder.rs +0 -263
  438. package/crates/headroom-core/src/transforms/smart_crusher/classifier.rs +0 -214
  439. package/crates/headroom-core/src/transforms/smart_crusher/compaction/classifier.rs +0 -283
  440. package/crates/headroom-core/src/transforms/smart_crusher/compaction/compactor.rs +0 -733
  441. package/crates/headroom-core/src/transforms/smart_crusher/compaction/formatter.rs +0 -961
  442. package/crates/headroom-core/src/transforms/smart_crusher/compaction/ir.rs +0 -252
  443. package/crates/headroom-core/src/transforms/smart_crusher/compaction/mod.rs +0 -127
  444. package/crates/headroom-core/src/transforms/smart_crusher/compaction/walker.rs +0 -397
  445. package/crates/headroom-core/src/transforms/smart_crusher/config.rs +0 -173
  446. package/crates/headroom-core/src/transforms/smart_crusher/constraints.rs +0 -159
  447. package/crates/headroom-core/src/transforms/smart_crusher/crusher.rs +0 -1665
  448. package/crates/headroom-core/src/transforms/smart_crusher/crushers.rs +0 -865
  449. package/crates/headroom-core/src/transforms/smart_crusher/error_keywords.rs +0 -77
  450. package/crates/headroom-core/src/transforms/smart_crusher/field_detect.rs +0 -393
  451. package/crates/headroom-core/src/transforms/smart_crusher/hashing.rs +0 -72
  452. package/crates/headroom-core/src/transforms/smart_crusher/mod.rs +0 -81
  453. package/crates/headroom-core/src/transforms/smart_crusher/observer.rs +0 -66
  454. package/crates/headroom-core/src/transforms/smart_crusher/orchestration.rs +0 -459
  455. package/crates/headroom-core/src/transforms/smart_crusher/outliers.rs +0 -507
  456. package/crates/headroom-core/src/transforms/smart_crusher/planning.rs +0 -904
  457. package/crates/headroom-core/src/transforms/smart_crusher/statistics.rs +0 -510
  458. package/crates/headroom-core/src/transforms/smart_crusher/stats_math.rs +0 -287
  459. package/crates/headroom-core/src/transforms/smart_crusher/traits.rs +0 -203
  460. package/crates/headroom-core/src/transforms/smart_crusher/types.rs +0 -263
  461. package/crates/headroom-core/src/transforms/tag_protector.rs +0 -1272
  462. package/crates/headroom-core/src/transforms/unidiff_detector.rs +0 -232
  463. package/crates/headroom-parity/Cargo.toml +0 -26
  464. package/crates/headroom-parity/examples/diff_fixture.rs +0 -66
  465. package/crates/headroom-parity/src/bin/parity_run.rs +0 -78
  466. package/crates/headroom-parity/src/lib.rs +0 -613
  467. package/crates/headroom-proxy/Cargo.toml +0 -119
  468. package/crates/headroom-proxy/data/model_prices_and_context_window.json +0 -39767
  469. package/crates/headroom-proxy/src/bedrock/auth_mode_layer.rs +0 -192
  470. package/crates/headroom-proxy/src/bedrock/envelope.rs +0 -239
  471. package/crates/headroom-proxy/src/bedrock/eventstream.rs +0 -769
  472. package/crates/headroom-proxy/src/bedrock/eventstream_to_sse.rs +0 -459
  473. package/crates/headroom-proxy/src/bedrock/invoke.rs +0 -735
  474. package/crates/headroom-proxy/src/bedrock/invoke_streaming.rs +0 -1098
  475. package/crates/headroom-proxy/src/bedrock/mod.rs +0 -66
  476. package/crates/headroom-proxy/src/bedrock/sigv4.rs +0 -324
  477. package/crates/headroom-proxy/src/bedrock/vendor.rs +0 -82
  478. package/crates/headroom-proxy/src/cache_stabilization/anthropic_cache_control.rs +0 -698
  479. package/crates/headroom-proxy/src/cache_stabilization/drift_detector.rs +0 -683
  480. package/crates/headroom-proxy/src/cache_stabilization/mod.rs +0 -61
  481. package/crates/headroom-proxy/src/cache_stabilization/openai_cache_key.rs +0 -600
  482. package/crates/headroom-proxy/src/cache_stabilization/tool_def_normalize.rs +0 -514
  483. package/crates/headroom-proxy/src/cache_stabilization/volatile_detector.rs +0 -720
  484. package/crates/headroom-proxy/src/compression/anthropic.rs +0 -92
  485. package/crates/headroom-proxy/src/compression/live_zone_anthropic.rs +0 -1311
  486. package/crates/headroom-proxy/src/compression/live_zone_openai.rs +0 -660
  487. package/crates/headroom-proxy/src/compression/live_zone_responses.rs +0 -678
  488. package/crates/headroom-proxy/src/compression/mod.rs +0 -127
  489. package/crates/headroom-proxy/src/compression/model_limits.rs +0 -211
  490. package/crates/headroom-proxy/src/config.rs +0 -646
  491. package/crates/headroom-proxy/src/error.rs +0 -69
  492. package/crates/headroom-proxy/src/handlers/chat_completions.rs +0 -100
  493. package/crates/headroom-proxy/src/handlers/conversations.rs +0 -241
  494. package/crates/headroom-proxy/src/handlers/mod.rs +0 -13
  495. package/crates/headroom-proxy/src/handlers/responses.rs +0 -256
  496. package/crates/headroom-proxy/src/headers.rs +0 -288
  497. package/crates/headroom-proxy/src/health.rs +0 -41
  498. package/crates/headroom-proxy/src/lib.rs +0 -21
  499. package/crates/headroom-proxy/src/main.rs +0 -141
  500. package/crates/headroom-proxy/src/observability/cache_hit_rate.rs +0 -340
  501. package/crates/headroom-proxy/src/observability/compression_ratio.rs +0 -158
  502. package/crates/headroom-proxy/src/observability/metric_names.rs +0 -174
  503. package/crates/headroom-proxy/src/observability/mod.rs +0 -68
  504. package/crates/headroom-proxy/src/observability/prometheus.rs +0 -394
  505. package/crates/headroom-proxy/src/observability/proxy_metrics.rs +0 -368
  506. package/crates/headroom-proxy/src/proxy.rs +0 -1619
  507. package/crates/headroom-proxy/src/responses_items.rs +0 -565
  508. package/crates/headroom-proxy/src/sse/anthropic.rs +0 -415
  509. package/crates/headroom-proxy/src/sse/framing.rs +0 -366
  510. package/crates/headroom-proxy/src/sse/mod.rs +0 -40
  511. package/crates/headroom-proxy/src/sse/openai_chat.rs +0 -231
  512. package/crates/headroom-proxy/src/sse/openai_responses.rs +0 -458
  513. package/crates/headroom-proxy/src/vertex/adc.rs +0 -315
  514. package/crates/headroom-proxy/src/vertex/envelope.rs +0 -167
  515. package/crates/headroom-proxy/src/vertex/mod.rs +0 -277
  516. package/crates/headroom-proxy/src/vertex/raw_predict.rs +0 -490
  517. package/crates/headroom-proxy/src/vertex/stream_raw_predict.rs +0 -49
  518. package/crates/headroom-proxy/src/websocket.rs +0 -246
  519. package/crates/headroom-py/Cargo.toml +0 -37
  520. package/crates/headroom-py/build.rs +0 -77
  521. package/crates/headroom-py/glibc_compat.c +0 -170
  522. package/crates/headroom-py/src/lib.rs +0 -1655
  523. package/deny.toml +0 -32
  524. package/docker/differential-network-capture/Dockerfile.runner +0 -14
  525. package/docker/differential-network-capture/docker-compose.yml +0 -142
  526. package/docker/differential-network-capture/run-claude-lane.sh +0 -24
  527. package/docker/docker-compose.native.yml +0 -44
  528. package/docker-bake.hcl +0 -88
  529. package/docker-compose.yml +0 -80
  530. package/e2e/_lib/make_shim.ps1 +0 -24
  531. package/e2e/_lib/make_shim.sh +0 -28
  532. package/e2e/docker-native-install.sh +0 -120
  533. package/e2e/init/Dockerfile +0 -79
  534. package/e2e/wrap/Dockerfile +0 -115
  535. package/examples/07-context-compression.ipynb +0 -279
  536. package/examples/deployment/macos-launchagent/com.headroom.proxy.plist.template +0 -65
  537. package/examples/deployment/macos-launchagent/install.sh +0 -227
  538. package/examples/deployment/macos-launchagent/shell-integration.sh +0 -74
  539. package/examples/deployment/macos-launchagent/uninstall.sh +0 -145
  540. package/headroom-savings.png +0 -0
  541. package/headroom_learn.gif +0 -0
  542. package/llms.txt +0 -67
  543. package/mkdocs.yml +0 -136
  544. package/npm/bin/xithead.js +0 -366
  545. package/npm/bin/xtream-head.js +0 -366
  546. package/npm/index.d.ts +0 -57
  547. package/npm/index.js +0 -139
  548. package/npm/package.json +0 -55
  549. package/npm/postinstall.js +0 -43
  550. package/plugins/headroom-agent-hooks/.claude-plugin/plugin.json +0 -17
  551. package/plugins/headroom-agent-hooks/hooks/hooks.json +0 -29
  552. package/plugins/headroom-oauth2/LICENSE +0 -3
  553. package/plugins/headroom-oauth2/SPEC.md +0 -115
  554. package/plugins/headroom-oauth2/pyproject.toml +0 -48
  555. package/plugins/hermes/headroom_retrieve/plugin.yaml +0 -6
  556. package/plugins/openclaw/hook-shim/HOOK.md +0 -21
  557. package/plugins/openclaw/hook-shim/handler.js +0 -3
  558. package/plugins/openclaw/openclaw.plugin.json +0 -98
  559. package/plugins/openclaw/package-lock.json +0 -2692
  560. package/plugins/openclaw/package.json +0 -54
  561. package/plugins/openclaw/prepare-dist.mjs +0 -56
  562. package/plugins/openclaw/src/convert.ts +0 -418
  563. package/plugins/openclaw/src/engine.ts +0 -284
  564. package/plugins/openclaw/src/gateway-config.ts +0 -143
  565. package/plugins/openclaw/src/index.ts +0 -11
  566. package/plugins/openclaw/src/plugin/index.ts +0 -98
  567. package/plugins/openclaw/src/proxy-manager.ts +0 -477
  568. package/plugins/openclaw/src/tools/headroom-retrieve.ts +0 -76
  569. package/plugins/openclaw/test/convert.test.ts +0 -96
  570. package/plugins/openclaw/test/engine-normalization.test.ts +0 -21
  571. package/plugins/openclaw/test/engine.test.ts +0 -101
  572. package/plugins/openclaw/test/gateway-config.test.ts +0 -278
  573. package/plugins/openclaw/test/plugin-runtime-routing.test.ts +0 -141
  574. package/plugins/openclaw/test/proxy-manager.test.ts +0 -343
  575. package/plugins/openclaw/tsup.config.ts +0 -9
  576. package/pyproject.toml +0 -438
  577. package/rust-toolchain.toml +0 -16
  578. package/sdk/typescript/examples/basic-compress.ts +0 -64
  579. package/sdk/typescript/examples/ccr-retrieve.ts +0 -80
  580. package/sdk/typescript/examples/hooks-custom-compression.ts +0 -117
  581. package/sdk/typescript/examples/middleware-composition.ts +0 -59
  582. package/sdk/typescript/examples/multi-provider.ts +0 -53
  583. package/sdk/typescript/examples/openai-anthropic-adapters.ts +0 -73
  584. package/sdk/typescript/examples/shared-context-multi-agent.ts +0 -74
  585. package/sdk/typescript/examples/simulation-dry-run.ts +0 -80
  586. package/sdk/typescript/examples/streaming-chat.ts +0 -71
  587. package/sdk/typescript/examples/structured-output.ts +0 -99
  588. package/sdk/typescript/examples/tool-calling-agent.ts +0 -86
  589. package/sdk/typescript/examples/with-headroom-vercel.ts +0 -57
  590. package/sdk/typescript/package-lock.json +0 -3437
  591. package/sdk/typescript/package.json +0 -108
  592. package/sdk/typescript/src/adapters/anthropic.ts +0 -218
  593. package/sdk/typescript/src/adapters/gemini.ts +0 -83
  594. package/sdk/typescript/src/adapters/openai.ts +0 -77
  595. package/sdk/typescript/src/adapters/vercel-ai.ts +0 -131
  596. package/sdk/typescript/src/client.ts +0 -632
  597. package/sdk/typescript/src/compress.ts +0 -87
  598. package/sdk/typescript/src/errors.ts +0 -114
  599. package/sdk/typescript/src/hooks.ts +0 -113
  600. package/sdk/typescript/src/index.ts +0 -140
  601. package/sdk/typescript/src/paths.ts +0 -272
  602. package/sdk/typescript/src/shared-context.ts +0 -188
  603. package/sdk/typescript/src/simulate.ts +0 -52
  604. package/sdk/typescript/src/types/config.ts +0 -183
  605. package/sdk/typescript/src/types/models.ts +0 -314
  606. package/sdk/typescript/src/types.ts +0 -139
  607. package/sdk/typescript/src/utils/case.ts +0 -34
  608. package/sdk/typescript/src/utils/format.ts +0 -480
  609. package/sdk/typescript/src/utils/stream.ts +0 -50
  610. package/sdk/typescript/test/adapters/anthropic.test.ts +0 -217
  611. package/sdk/typescript/test/adapters/gemini.test.ts +0 -131
  612. package/sdk/typescript/test/adapters/openai.test.ts +0 -174
  613. package/sdk/typescript/test/adapters/vercel-ai.test.ts +0 -306
  614. package/sdk/typescript/test/client-expanded.test.ts +0 -333
  615. package/sdk/typescript/test/client.test.ts +0 -266
  616. package/sdk/typescript/test/compress.test.ts +0 -118
  617. package/sdk/typescript/test/config.test.ts +0 -275
  618. package/sdk/typescript/test/errors.test.ts +0 -169
  619. package/sdk/typescript/test/format-integration.test.ts +0 -252
  620. package/sdk/typescript/test/hooks.test.ts +0 -265
  621. package/sdk/typescript/test/integration.test.ts +0 -249
  622. package/sdk/typescript/test/mdx-examples.test.ts +0 -253
  623. package/sdk/typescript/test/models.test.ts +0 -318
  624. package/sdk/typescript/test/parity.test.ts +0 -337
  625. package/sdk/typescript/test/paths.test.ts +0 -447
  626. package/sdk/typescript/test/shared-context.test.ts +0 -245
  627. package/sdk/typescript/test/simulate.test.ts +0 -84
  628. package/sdk/typescript/test/types.test.ts +0 -244
  629. package/sdk/typescript/test/utils/case.test.ts +0 -129
  630. package/sdk/typescript/test/utils/detect-format.test.ts +0 -133
  631. package/sdk/typescript/test/utils/format.test.ts +0 -434
  632. package/sdk/typescript/test/vercel-ai-e2e.test.ts +0 -179
  633. package/sdk/typescript/tsup.config.ts +0 -17
  634. package/uv.lock +0 -6951
  635. package/xithead.egg-info/PKG-INFO +0 -22
  636. package/xithead.egg-info/SOURCES.txt +0 -16
  637. package/xithead.egg-info/dependency_links.txt +0 -1
  638. package/xithead.egg-info/entry_points.txt +0 -2
  639. package/xithead.egg-info/requires.txt +0 -10
  640. package/xithead.egg-info/top_level.txt +0 -2
  641. package/xithead.ps1 +0 -136
  642. package/xithead.sh +0 -129
  643. package/xithead_dist/pyproject.toml +0 -39
  644. package/xithead_dist/xithead.egg-info/PKG-INFO +0 -22
  645. package/xithead_dist/xithead.egg-info/SOURCES.txt +0 -16
  646. package/xithead_dist/xithead.egg-info/dependency_links.txt +0 -1
  647. package/xithead_dist/xithead.egg-info/entry_points.txt +0 -3
  648. package/xithead_dist/xithead.egg-info/requires.txt +0 -10
  649. package/xithead_dist/xithead.egg-info/top_level.txt +0 -2
@@ -1,1685 +0,0 @@
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
- }