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,1655 +0,0 @@
1
- //! PyO3 bindings for headroom-core. Exposed to Python as `headroom._core`.
2
- //!
3
- //! # Stage 3b — diff_compressor bridge
4
- //!
5
- //! The `DiffCompressor` family is exported here so the Python
6
- //! `ContentRouter` can route to the Rust implementation in-process via
7
- //! PyO3 instead of running the Python port. Backend selection happens in
8
- //! `headroom.transforms._rust_diff_compressor.RustBackedDiffCompressor`,
9
- //! which mirrors the Python `DiffCompressor` API one-for-one (so callers
10
- //! don't notice the swap).
11
- //!
12
- //! Why in-process: ContentRouter compresses on the proxy's hot path. Any
13
- //! IPC / subprocess / RPC bridge would dominate the cost we're trying to
14
- //! save. PyO3 calls cost ~microseconds; staying in-process is ~free.
15
-
16
- use std::collections::BTreeMap;
17
-
18
- use headroom_core::signals::{
19
- ImportanceCategory, ImportanceContext, KeywordDetector, KeywordRegistry, LineImportanceDetector,
20
- };
21
- use headroom_core::transforms::smart_crusher::compaction::DocumentCompactor;
22
- use headroom_core::transforms::smart_crusher::{
23
- CrushResult as RustCrushResult, SmartCrusher as RustSmartCrusher,
24
- SmartCrusherConfig as RustSmartCrusherConfig,
25
- };
26
- use headroom_core::transforms::tag_protector::{
27
- is_known_html_tag as rust_is_known_html_tag, known_html_tag_names as rust_known_html_tag_names,
28
- protect_tags as rust_protect_tags, restore_tags as rust_restore_tags,
29
- };
30
- use headroom_core::transforms::{
31
- compress_openai_responses_live_zone as rust_compress_openai_responses_live_zone,
32
- detect as rust_detect_chain, is_json_array_of_dicts as rust_is_json_array_of_dicts,
33
- summarize_openai_responses_no_change_reason as rust_summarize_openai_responses_no_change_reason,
34
- AuthMode as RustLiveZoneAuthMode, ContentType as RustContentType,
35
- DetectionResult as RustDetectionResult, DiffCompressionResult, DiffCompressor,
36
- DiffCompressorConfig, DiffCompressorStats, LiveZoneOutcome,
37
- LogCompressionResult as RustLogResult, LogCompressor as RustLogCompressor,
38
- LogCompressorConfig as RustLogConfig, LogCompressorStats as RustLogStats,
39
- LogFormat as RustLogFormat, LogLevel as RustLogLevel,
40
- SearchCompressionResult as RustSearchResult, SearchCompressor as RustSearchCompressor,
41
- SearchCompressorConfig as RustSearchConfig, SearchCompressorStats as RustSearchStats,
42
- };
43
- use pyo3::prelude::*;
44
- use pyo3::types::{PyBytes, PyDict};
45
-
46
- /// Identity stub used by the Python smoke test to verify linkage.
47
- #[pyfunction]
48
- fn hello() -> &'static str {
49
- headroom_core::hello()
50
- }
51
-
52
- fn type_name(v: &serde_json::Value) -> &'static str {
53
- match v {
54
- serde_json::Value::Null => "null",
55
- serde_json::Value::Bool(_) => "bool",
56
- serde_json::Value::Number(_) => "number",
57
- serde_json::Value::String(_) => "string",
58
- serde_json::Value::Array(_) => "array",
59
- serde_json::Value::Object(_) => "object",
60
- }
61
- }
62
-
63
- /// Build the dict returned by `SmartCrusher.crush_array_json`. Kept
64
- /// outside `#[pymethods]` so we can `unwrap()` `set_item` (it cannot
65
- /// fail when keys are static str literals and values are owned String /
66
- /// Option<String> / Option<&'static str>) without tripping the
67
- /// `clippy::useless_conversion` false positive that fires inside the
68
- /// pyo3 0.22 method-attribute macro.
69
- fn build_crush_array_dict<'py>(
70
- py: Python<'py>,
71
- kept_json: String,
72
- ccr_hash: Option<String>,
73
- dropped_summary: String,
74
- strategy_info: String,
75
- compacted: Option<String>,
76
- compaction_kind: Option<&'static str>,
77
- ) -> Bound<'py, PyDict> {
78
- let dict = PyDict::new(py);
79
- dict.set_item("items", kept_json).unwrap();
80
- dict.set_item("ccr_hash", ccr_hash).unwrap();
81
- dict.set_item("dropped_summary", dropped_summary).unwrap();
82
- dict.set_item("strategy_info", strategy_info).unwrap();
83
- dict.set_item("compacted", compacted).unwrap();
84
- dict.set_item("compaction_kind", compaction_kind).unwrap();
85
- dict
86
- }
87
-
88
- // ─── DiffCompressorConfig ──────────────────────────────────────────────────
89
-
90
- /// Mirror of `headroom.transforms.diff_compressor.DiffCompressorConfig`.
91
- /// Defaults match Python; constructor accepts every field as a kwarg with
92
- /// the same name and type as the Python dataclass for drop-in
93
- /// compatibility.
94
- #[pyclass(name = "DiffCompressorConfig", module = "headroom._core")]
95
- #[derive(Clone)]
96
- struct PyDiffCompressorConfig {
97
- inner: DiffCompressorConfig,
98
- }
99
-
100
- #[pymethods]
101
- impl PyDiffCompressorConfig {
102
- #[new]
103
- #[pyo3(signature = (
104
- max_context_lines = 2,
105
- max_hunks_per_file = 10,
106
- max_files = 20,
107
- always_keep_additions = true,
108
- always_keep_deletions = true,
109
- enable_ccr = true,
110
- min_lines_for_ccr = 50,
111
- min_compression_ratio_for_ccr = 0.8,
112
- ))]
113
- #[allow(clippy::too_many_arguments)]
114
- fn new(
115
- max_context_lines: usize,
116
- max_hunks_per_file: usize,
117
- max_files: usize,
118
- always_keep_additions: bool,
119
- always_keep_deletions: bool,
120
- enable_ccr: bool,
121
- min_lines_for_ccr: usize,
122
- min_compression_ratio_for_ccr: f64,
123
- ) -> Self {
124
- Self {
125
- inner: DiffCompressorConfig {
126
- max_context_lines,
127
- max_hunks_per_file,
128
- max_files,
129
- always_keep_additions,
130
- always_keep_deletions,
131
- enable_ccr,
132
- min_lines_for_ccr,
133
- min_compression_ratio_for_ccr,
134
- },
135
- }
136
- }
137
-
138
- // Read-only field accessors mirroring the Python dataclass surface.
139
- #[getter]
140
- fn max_context_lines(&self) -> usize {
141
- self.inner.max_context_lines
142
- }
143
- #[getter]
144
- fn max_hunks_per_file(&self) -> usize {
145
- self.inner.max_hunks_per_file
146
- }
147
- #[getter]
148
- fn max_files(&self) -> usize {
149
- self.inner.max_files
150
- }
151
- #[getter]
152
- fn always_keep_additions(&self) -> bool {
153
- self.inner.always_keep_additions
154
- }
155
- #[getter]
156
- fn always_keep_deletions(&self) -> bool {
157
- self.inner.always_keep_deletions
158
- }
159
- #[getter]
160
- fn enable_ccr(&self) -> bool {
161
- self.inner.enable_ccr
162
- }
163
- #[getter]
164
- fn min_lines_for_ccr(&self) -> usize {
165
- self.inner.min_lines_for_ccr
166
- }
167
- #[getter]
168
- fn min_compression_ratio_for_ccr(&self) -> f64 {
169
- self.inner.min_compression_ratio_for_ccr
170
- }
171
-
172
- fn __repr__(&self) -> String {
173
- format!(
174
- "DiffCompressorConfig(max_context_lines={}, max_hunks_per_file={}, max_files={}, \
175
- always_keep_additions={}, always_keep_deletions={}, enable_ccr={}, \
176
- min_lines_for_ccr={}, min_compression_ratio_for_ccr={})",
177
- self.inner.max_context_lines,
178
- self.inner.max_hunks_per_file,
179
- self.inner.max_files,
180
- self.inner.always_keep_additions,
181
- self.inner.always_keep_deletions,
182
- self.inner.enable_ccr,
183
- self.inner.min_lines_for_ccr,
184
- self.inner.min_compression_ratio_for_ccr,
185
- )
186
- }
187
- }
188
-
189
- // ─── DiffCompressionResult ─────────────────────────────────────────────────
190
-
191
- /// Mirror of `headroom.transforms.diff_compressor.DiffCompressionResult`.
192
- /// Read-only on the Python side: ContentRouter consumes fields, doesn't
193
- /// mutate. `compression_ratio` and `tokens_saved_estimate` are exposed as
194
- /// methods (not `@property`) — Python callers reach them via `.method()`.
195
- /// The Python adapter wraps and re-exposes them as properties for full
196
- /// dataclass compatibility.
197
- #[pyclass(name = "DiffCompressionResult", module = "headroom._core")]
198
- struct PyDiffCompressionResult {
199
- inner: DiffCompressionResult,
200
- }
201
-
202
- #[pymethods]
203
- impl PyDiffCompressionResult {
204
- #[getter]
205
- fn compressed(&self) -> &str {
206
- &self.inner.compressed
207
- }
208
- #[getter]
209
- fn original_line_count(&self) -> usize {
210
- self.inner.original_line_count
211
- }
212
- #[getter]
213
- fn compressed_line_count(&self) -> usize {
214
- self.inner.compressed_line_count
215
- }
216
- #[getter]
217
- fn files_affected(&self) -> usize {
218
- self.inner.files_affected
219
- }
220
- #[getter]
221
- fn additions(&self) -> usize {
222
- self.inner.additions
223
- }
224
- #[getter]
225
- fn deletions(&self) -> usize {
226
- self.inner.deletions
227
- }
228
- #[getter]
229
- fn hunks_kept(&self) -> usize {
230
- self.inner.hunks_kept
231
- }
232
- #[getter]
233
- fn hunks_removed(&self) -> usize {
234
- self.inner.hunks_removed
235
- }
236
- #[getter]
237
- fn cache_key(&self) -> Option<String> {
238
- self.inner.cache_key.clone()
239
- }
240
-
241
- /// Mirror of Python `@property compression_ratio`. Returns
242
- /// `compressed_line_count / original_line_count` (1.0 if input was
243
- /// empty).
244
- fn compression_ratio(&self) -> f64 {
245
- if self.inner.original_line_count == 0 {
246
- 1.0
247
- } else {
248
- self.inner.compressed_line_count as f64 / self.inner.original_line_count as f64
249
- }
250
- }
251
-
252
- /// Mirror of Python `@property tokens_saved_estimate`. Same `chars *
253
- /// 40 / 4` heuristic; bytes-equivalent numeric result.
254
- fn tokens_saved_estimate(&self) -> usize {
255
- let saved = self
256
- .inner
257
- .original_line_count
258
- .saturating_sub(self.inner.compressed_line_count);
259
- (saved * 40) / 4
260
- }
261
-
262
- fn __repr__(&self) -> String {
263
- format!(
264
- "DiffCompressionResult(compressed=<{} chars>, original_line_count={}, \
265
- compressed_line_count={}, files_affected={}, additions={}, deletions={}, \
266
- hunks_kept={}, hunks_removed={}, cache_key={:?})",
267
- self.inner.compressed.len(),
268
- self.inner.original_line_count,
269
- self.inner.compressed_line_count,
270
- self.inner.files_affected,
271
- self.inner.additions,
272
- self.inner.deletions,
273
- self.inner.hunks_kept,
274
- self.inner.hunks_removed,
275
- self.inner.cache_key,
276
- )
277
- }
278
- }
279
-
280
- // ─── DiffCompressorStats ───────────────────────────────────────────────────
281
-
282
- /// Mirror of Rust `DiffCompressorStats` — sidecar observability not
283
- /// present in the Python dataclass. Returned only from `compress_with_stats`,
284
- /// which the Python adapter exposes as a method on the wrapper. `Vec`s are
285
- /// returned as Python lists; the `BTreeMap` becomes a `dict`.
286
- #[pyclass(name = "DiffCompressorStats", module = "headroom._core")]
287
- struct PyDiffCompressorStats {
288
- inner: DiffCompressorStats,
289
- }
290
-
291
- #[pymethods]
292
- impl PyDiffCompressorStats {
293
- #[getter]
294
- fn input_lines(&self) -> usize {
295
- self.inner.input_lines
296
- }
297
- #[getter]
298
- fn output_lines(&self) -> usize {
299
- self.inner.output_lines
300
- }
301
- #[getter]
302
- fn compression_ratio(&self) -> f64 {
303
- self.inner.compression_ratio
304
- }
305
- #[getter]
306
- fn files_total(&self) -> usize {
307
- self.inner.files_total
308
- }
309
- #[getter]
310
- fn files_kept(&self) -> usize {
311
- self.inner.files_kept
312
- }
313
- #[getter]
314
- fn files_dropped(&self) -> Vec<String> {
315
- self.inner.files_dropped.clone()
316
- }
317
- #[getter]
318
- fn hunks_total(&self) -> usize {
319
- self.inner.hunks_total
320
- }
321
- #[getter]
322
- fn hunks_kept(&self) -> usize {
323
- self.inner.hunks_kept
324
- }
325
- #[getter]
326
- fn hunks_dropped(&self) -> usize {
327
- self.inner.hunks_dropped
328
- }
329
- #[getter]
330
- fn hunks_dropped_per_file(&self) -> BTreeMap<String, usize> {
331
- self.inner.hunks_dropped_per_file.clone()
332
- }
333
- #[getter]
334
- fn context_lines_input(&self) -> usize {
335
- self.inner.context_lines_input
336
- }
337
- #[getter]
338
- fn context_lines_kept(&self) -> usize {
339
- self.inner.context_lines_kept
340
- }
341
- #[getter]
342
- fn context_lines_trimmed(&self) -> usize {
343
- self.inner.context_lines_trimmed
344
- }
345
- #[getter]
346
- fn largest_hunk_kept_lines(&self) -> usize {
347
- self.inner.largest_hunk_kept_lines
348
- }
349
- #[getter]
350
- fn largest_hunk_dropped_lines(&self) -> usize {
351
- self.inner.largest_hunk_dropped_lines
352
- }
353
- #[getter]
354
- fn parse_warnings(&self) -> Vec<String> {
355
- self.inner.parse_warnings.clone()
356
- }
357
- #[getter]
358
- fn processing_duration_us(&self) -> u64 {
359
- self.inner.processing_duration_us
360
- }
361
- #[getter]
362
- fn cache_key_emitted(&self) -> bool {
363
- self.inner.cache_key_emitted
364
- }
365
- #[getter]
366
- fn ccr_skipped_reason(&self) -> Option<String> {
367
- self.inner.ccr_skipped_reason.clone()
368
- }
369
- #[getter]
370
- fn file_mode_normalizations(&self) -> Vec<(String, String)> {
371
- self.inner.file_mode_normalizations.clone()
372
- }
373
- #[getter]
374
- fn binary_files_simplified(&self) -> Vec<String> {
375
- self.inner.binary_files_simplified.clone()
376
- }
377
- }
378
-
379
- // ─── DiffCompressor ────────────────────────────────────────────────────────
380
-
381
- /// Mirror of `headroom.transforms.diff_compressor.DiffCompressor`. The
382
- /// Python adapter wraps this in `RustBackedDiffCompressor` so
383
- /// `ContentRouter` can swap backends transparently.
384
- #[pyclass(name = "DiffCompressor", module = "headroom._core")]
385
- struct PyDiffCompressor {
386
- inner: DiffCompressor,
387
- }
388
-
389
- #[pymethods]
390
- impl PyDiffCompressor {
391
- /// `__init__(config: DiffCompressorConfig | None = None)` — matches the
392
- /// Python constructor signature one-for-one.
393
- #[new]
394
- #[pyo3(signature = (config = None))]
395
- fn new(config: Option<&PyDiffCompressorConfig>) -> Self {
396
- let cfg = config.map(|c| c.inner.clone()).unwrap_or_default();
397
- Self {
398
- inner: DiffCompressor::new(cfg),
399
- }
400
- }
401
-
402
- /// `compress(content: str, context: str = "") -> DiffCompressionResult`.
403
- /// Argument order and keyword names match the Python implementation.
404
- ///
405
- /// Releases the GIL across the Rust compress call so concurrent
406
- /// Python threads (uvicorn workers, asyncio tasks) can keep
407
- /// running while we hash + parse + filter the diff. The
408
- /// `&str` inputs are copied to owned `String`s first because
409
- /// PyO3 ties their lifetime to the GIL hold.
410
- #[pyo3(signature = (content, context = ""))]
411
- fn compress(&self, py: Python<'_>, content: &str, context: &str) -> PyDiffCompressionResult {
412
- let content = content.to_string();
413
- let context = context.to_string();
414
- let inner = py.allow_threads(|| self.inner.compress(&content, &context));
415
- PyDiffCompressionResult { inner }
416
- }
417
-
418
- /// `compress_with_stats(content, context="") -> (result, stats)`.
419
- /// Sidecar API not present in Python — exposes the Rust observability
420
- /// struct alongside the parity-equal result. Returned as a 2-tuple to
421
- /// keep the call site Pythonic.
422
- #[pyo3(signature = (content, context = ""))]
423
- fn compress_with_stats(
424
- &self,
425
- py: Python<'_>,
426
- content: &str,
427
- context: &str,
428
- ) -> (PyDiffCompressionResult, PyDiffCompressorStats) {
429
- let content = content.to_string();
430
- let context = context.to_string();
431
- let (result, stats) =
432
- py.allow_threads(|| self.inner.compress_with_stats(&content, &context));
433
- (
434
- PyDiffCompressionResult { inner: result },
435
- PyDiffCompressorStats { inner: stats },
436
- )
437
- }
438
- }
439
-
440
- // ─── SmartCrusherConfig ────────────────────────────────────────────────────
441
-
442
- /// Mirror of `headroom.transforms.smart_crusher.SmartCrusherConfig`.
443
- /// Defaults match Python's dataclass byte-for-byte. The constructor
444
- /// accepts every field as a kwarg with the same name and type so the
445
- /// Python shim can pass `SmartCrusherConfig(**asdict(py_cfg))`.
446
- #[pyclass(name = "SmartCrusherConfig", module = "headroom._core")]
447
- #[derive(Clone)]
448
- struct PySmartCrusherConfig {
449
- inner: RustSmartCrusherConfig,
450
- }
451
-
452
- #[pymethods]
453
- impl PySmartCrusherConfig {
454
- #[new]
455
- #[pyo3(signature = (
456
- enabled = true,
457
- min_items_to_analyze = 5,
458
- min_tokens_to_crush = 200,
459
- variance_threshold = 2.0,
460
- uniqueness_threshold = 0.1,
461
- similarity_threshold = 0.8,
462
- max_items_after_crush = 15,
463
- preserve_change_points = true,
464
- factor_out_constants = false,
465
- include_summaries = false,
466
- use_feedback_hints = true,
467
- toin_confidence_threshold = 0.5,
468
- dedup_identical_items = true,
469
- first_fraction = 0.3,
470
- last_fraction = 0.15,
471
- relevance_threshold = 0.3,
472
- lossless_min_savings_ratio = 0.15,
473
- enable_ccr_marker = true,
474
- compaction_core_field_fraction = 0.8,
475
- compaction_heterogeneous_core_ratio = 0.6,
476
- compaction_max_flatten_inner_keys = 6,
477
- compaction_min_buckets = 2,
478
- compaction_max_buckets = 8,
479
- ))]
480
- #[allow(clippy::too_many_arguments)]
481
- fn new(
482
- enabled: bool,
483
- min_items_to_analyze: usize,
484
- min_tokens_to_crush: usize,
485
- variance_threshold: f64,
486
- uniqueness_threshold: f64,
487
- similarity_threshold: f64,
488
- max_items_after_crush: usize,
489
- preserve_change_points: bool,
490
- factor_out_constants: bool,
491
- include_summaries: bool,
492
- use_feedback_hints: bool,
493
- toin_confidence_threshold: f64,
494
- dedup_identical_items: bool,
495
- first_fraction: f64,
496
- last_fraction: f64,
497
- relevance_threshold: f64,
498
- lossless_min_savings_ratio: f64,
499
- enable_ccr_marker: bool,
500
- compaction_core_field_fraction: f64,
501
- compaction_heterogeneous_core_ratio: f64,
502
- compaction_max_flatten_inner_keys: usize,
503
- compaction_min_buckets: usize,
504
- compaction_max_buckets: usize,
505
- ) -> Self {
506
- Self {
507
- inner: RustSmartCrusherConfig {
508
- enabled,
509
- min_items_to_analyze,
510
- min_tokens_to_crush,
511
- variance_threshold,
512
- uniqueness_threshold,
513
- similarity_threshold,
514
- max_items_after_crush,
515
- preserve_change_points,
516
- factor_out_constants,
517
- include_summaries,
518
- use_feedback_hints,
519
- toin_confidence_threshold,
520
- dedup_identical_items,
521
- first_fraction,
522
- last_fraction,
523
- relevance_threshold,
524
- lossless_min_savings_ratio,
525
- enable_ccr_marker,
526
- compaction_core_field_fraction,
527
- compaction_heterogeneous_core_ratio,
528
- compaction_max_flatten_inner_keys,
529
- compaction_min_buckets,
530
- compaction_max_buckets,
531
- },
532
- }
533
- }
534
-
535
- #[getter]
536
- fn enabled(&self) -> bool {
537
- self.inner.enabled
538
- }
539
- #[getter]
540
- fn min_items_to_analyze(&self) -> usize {
541
- self.inner.min_items_to_analyze
542
- }
543
- #[getter]
544
- fn min_tokens_to_crush(&self) -> usize {
545
- self.inner.min_tokens_to_crush
546
- }
547
- #[getter]
548
- fn variance_threshold(&self) -> f64 {
549
- self.inner.variance_threshold
550
- }
551
- #[getter]
552
- fn uniqueness_threshold(&self) -> f64 {
553
- self.inner.uniqueness_threshold
554
- }
555
- #[getter]
556
- fn similarity_threshold(&self) -> f64 {
557
- self.inner.similarity_threshold
558
- }
559
- #[getter]
560
- fn max_items_after_crush(&self) -> usize {
561
- self.inner.max_items_after_crush
562
- }
563
- #[getter]
564
- fn preserve_change_points(&self) -> bool {
565
- self.inner.preserve_change_points
566
- }
567
- #[getter]
568
- fn factor_out_constants(&self) -> bool {
569
- self.inner.factor_out_constants
570
- }
571
- #[getter]
572
- fn include_summaries(&self) -> bool {
573
- self.inner.include_summaries
574
- }
575
- #[getter]
576
- fn use_feedback_hints(&self) -> bool {
577
- self.inner.use_feedback_hints
578
- }
579
- #[getter]
580
- fn toin_confidence_threshold(&self) -> f64 {
581
- self.inner.toin_confidence_threshold
582
- }
583
- #[getter]
584
- fn dedup_identical_items(&self) -> bool {
585
- self.inner.dedup_identical_items
586
- }
587
- #[getter]
588
- fn first_fraction(&self) -> f64 {
589
- self.inner.first_fraction
590
- }
591
- #[getter]
592
- fn last_fraction(&self) -> f64 {
593
- self.inner.last_fraction
594
- }
595
- #[getter]
596
- fn relevance_threshold(&self) -> f64 {
597
- self.inner.relevance_threshold
598
- }
599
- #[getter]
600
- fn enable_ccr_marker(&self) -> bool {
601
- self.inner.enable_ccr_marker
602
- }
603
- #[getter]
604
- fn lossless_min_savings_ratio(&self) -> f64 {
605
- self.inner.lossless_min_savings_ratio
606
- }
607
- #[getter]
608
- fn compaction_core_field_fraction(&self) -> f64 {
609
- self.inner.compaction_core_field_fraction
610
- }
611
- #[getter]
612
- fn compaction_heterogeneous_core_ratio(&self) -> f64 {
613
- self.inner.compaction_heterogeneous_core_ratio
614
- }
615
- #[getter]
616
- fn compaction_max_flatten_inner_keys(&self) -> usize {
617
- self.inner.compaction_max_flatten_inner_keys
618
- }
619
- #[getter]
620
- fn compaction_min_buckets(&self) -> usize {
621
- self.inner.compaction_min_buckets
622
- }
623
- #[getter]
624
- fn compaction_max_buckets(&self) -> usize {
625
- self.inner.compaction_max_buckets
626
- }
627
-
628
- fn __repr__(&self) -> String {
629
- format!(
630
- "SmartCrusherConfig(enabled={}, min_items_to_analyze={}, \
631
- min_tokens_to_crush={}, max_items_after_crush={}, \
632
- relevance_threshold={})",
633
- self.inner.enabled,
634
- self.inner.min_items_to_analyze,
635
- self.inner.min_tokens_to_crush,
636
- self.inner.max_items_after_crush,
637
- self.inner.relevance_threshold,
638
- )
639
- }
640
- }
641
-
642
- // ─── CrushResult ───────────────────────────────────────────────────────────
643
-
644
- /// Mirror of `headroom.transforms.smart_crusher.CrushResult`. Read-only;
645
- /// the Python shim builds its own dataclass instance from these
646
- /// attributes so callers that destructure with `asdict()` keep working.
647
- #[pyclass(name = "CrushResult", module = "headroom._core")]
648
- struct PyCrushResult {
649
- inner: RustCrushResult,
650
- }
651
-
652
- #[pymethods]
653
- impl PyCrushResult {
654
- #[getter]
655
- fn compressed(&self) -> &str {
656
- &self.inner.compressed
657
- }
658
- #[getter]
659
- fn original(&self) -> &str {
660
- &self.inner.original
661
- }
662
- #[getter]
663
- fn was_modified(&self) -> bool {
664
- self.inner.was_modified
665
- }
666
- #[getter]
667
- fn strategy(&self) -> &str {
668
- &self.inner.strategy
669
- }
670
-
671
- fn __repr__(&self) -> String {
672
- format!(
673
- "CrushResult(compressed=<{} chars>, was_modified={}, strategy={:?})",
674
- self.inner.compressed.len(),
675
- self.inner.was_modified,
676
- self.inner.strategy,
677
- )
678
- }
679
- }
680
-
681
- // ─── SmartCrusher ──────────────────────────────────────────────────────────
682
-
683
- /// Mirror of `headroom.transforms.smart_crusher.SmartCrusher`.
684
- ///
685
- /// Constructor accepts only `config` — Python's `relevance_config`,
686
- /// `scorer`, and `ccr_config` parameters are handled in the Python
687
- /// shim (Stage 3c.1 keeps the optional subsystems disabled in Rust;
688
- /// the shim drops those args to preserve call-site compatibility).
689
- #[pyclass(name = "SmartCrusher", module = "headroom._core")]
690
- struct PySmartCrusher {
691
- inner: RustSmartCrusher,
692
- }
693
-
694
- #[pymethods]
695
- impl PySmartCrusher {
696
- #[new]
697
- #[pyo3(signature = (config = None))]
698
- fn new(config: Option<&PySmartCrusherConfig>) -> Self {
699
- let cfg = config.map(|c| c.inner.clone()).unwrap_or_default();
700
- Self {
701
- inner: RustSmartCrusher::new(cfg),
702
- }
703
- }
704
-
705
- /// Construct WITHOUT the lossless-first compaction stage. The
706
- /// public `crush()` API runs the lossy path directly (still with
707
- /// CCR-Dropped retrieval markers populated when rows are dropped).
708
- /// Used by the legacy parity fixture harness — those fixtures
709
- /// were recorded against the pre-PR4 lossy-only behavior.
710
- #[staticmethod]
711
- #[pyo3(signature = (config = None))]
712
- fn without_compaction(config: Option<&PySmartCrusherConfig>) -> Self {
713
- let cfg = config.map(|c| c.inner.clone()).unwrap_or_default();
714
- Self {
715
- inner: RustSmartCrusher::without_compaction(cfg),
716
- }
717
- }
718
-
719
- /// Construct with the lossless-first compaction stage's formatter
720
- /// chosen by name: `"csv-schema"` (the `new()` default), `"json"`,
721
- /// or `"markdown-kv"`. Raises `ValueError` on unknown names so a
722
- /// misconfigured knob is visible instead of silently falling back.
723
- #[staticmethod]
724
- #[pyo3(signature = (config = None, format_name = "csv-schema"))]
725
- fn with_compaction_format(
726
- config: Option<&PySmartCrusherConfig>,
727
- format_name: &str,
728
- ) -> PyResult<Self> {
729
- let cfg = config.map(|c| c.inner.clone()).unwrap_or_default();
730
- match RustSmartCrusher::with_compaction_format(cfg, format_name) {
731
- Some(inner) => Ok(Self { inner }),
732
- None => Err(pyo3::exceptions::PyValueError::new_err(format!(
733
- "unknown compaction format {format_name:?}; expected one of: {}",
734
- headroom_core::transforms::smart_crusher::compaction::CompactionStage::SUPPORTED_FORMAT_NAMES.join(", ")
735
- ))),
736
- }
737
- }
738
-
739
- /// `crush(content, query="", bias=1.0) -> CrushResult`. Argument
740
- /// order and keyword names mirror the Python implementation.
741
- ///
742
- /// Releases the GIL across the Rust crush call. Concurrent Python
743
- /// threads in the proxy keep running during the JSON parse +
744
- /// recursive process_value + per-array compression work. `&str`
745
- /// inputs are copied to owned `String`s up-front since PyO3 ties
746
- /// their lifetime to the GIL hold.
747
- #[pyo3(signature = (content, query = "", bias = 1.0))]
748
- fn crush(&self, py: Python<'_>, content: &str, query: &str, bias: f64) -> PyCrushResult {
749
- let content = content.to_string();
750
- let query = query.to_string();
751
- let inner = py.allow_threads(|| self.inner.crush(&content, &query, bias));
752
- PyCrushResult { inner }
753
- }
754
-
755
- /// `smart_crush_content(content, query="", bias=1.0) -> (str, bool, str)`.
756
- /// Mirrors Python's `_smart_crush_content` — used by
757
- /// `smart_crush_tool_output` convenience function and direct
758
- /// callers that want the tuple form. Releases the GIL across the
759
- /// compute (same rationale as `crush`).
760
- #[pyo3(signature = (content, query = "", bias = 1.0))]
761
- fn smart_crush_content(
762
- &self,
763
- py: Python<'_>,
764
- content: &str,
765
- query: &str,
766
- bias: f64,
767
- ) -> (String, bool, String) {
768
- let content = content.to_string();
769
- let query = query.to_string();
770
- py.allow_threads(|| self.inner.smart_crush_content(&content, &query, bias))
771
- }
772
-
773
- /// Crush a JSON array directly and return the structured result.
774
- ///
775
- /// Input is a JSON string holding an array (`[item, item, ...]`).
776
- /// Returns a dict with:
777
- /// - `items`: JSON array string of the kept rows after compression
778
- /// - `ccr_hash`: 12-char hash if rows were dropped, else `None`
779
- /// - `dropped_summary`: `<<ccr:HASH N_rows_offloaded>>` marker
780
- /// text, empty if nothing dropped
781
- /// - `strategy_info`: debug string describing what ran (e.g.
782
- /// `"smart_sample"`, `"lossless:table"`, `"none:adaptive_at_limit"`)
783
- /// - `compacted`: rendered bytes when the lossless path won, else `None`
784
- /// - `compaction_kind`: `"table" | "buckets" | "ccr" | None`
785
- ///
786
- /// This surfaces `CrushArrayResult` to Python so tests and the proxy
787
- /// runtime can reach the CCR hash directly (rather than parsing it
788
- /// out of the prompt marker).
789
- #[pyo3(signature = (items_json, query = "", bias = 1.0))]
790
- fn crush_array_json<'py>(
791
- &self,
792
- py: Python<'py>,
793
- items_json: &str,
794
- query: &str,
795
- bias: f64,
796
- ) -> Bound<'py, PyDict> {
797
- // GIL-release pattern: own the inputs, do all heavy compute
798
- // (JSON parse, crush, re-serialize) without the GIL, then
799
- // re-acquire to build the PyDict from the owned outputs.
800
- let items_json = items_json.to_string();
801
- let query = query.to_string();
802
- let (kept_json, ccr_hash, dropped_summary, strategy_info, compacted, compaction_kind) = py
803
- .allow_threads(|| {
804
- let parsed: serde_json::Value = serde_json::from_str(&items_json)
805
- .unwrap_or_else(|e| panic!("items_json must be JSON: {e}"));
806
- let items = match parsed {
807
- serde_json::Value::Array(a) => a,
808
- other => panic!("items_json must be a JSON array, got {}", type_name(&other)),
809
- };
810
- let result = self.inner.crush_array(&items, &query, bias);
811
- let kept_json = serde_json::to_string(&serde_json::Value::Array(result.items))
812
- .expect("serialize kept items");
813
- (
814
- kept_json,
815
- result.ccr_hash,
816
- result.dropped_summary,
817
- result.strategy_info,
818
- result.compacted,
819
- result.compaction_kind,
820
- )
821
- });
822
- build_crush_array_dict(
823
- py,
824
- kept_json,
825
- ccr_hash,
826
- dropped_summary,
827
- strategy_info,
828
- compacted,
829
- compaction_kind,
830
- )
831
- }
832
-
833
- /// Run the document-level walker on `doc_json` (JSON string) and
834
- /// return the compacted document as JSON.
835
- ///
836
- /// The walker recursively descends through objects, arrays, and
837
- /// strings; tabular sub-arrays become rendered CSV+schema strings,
838
- /// long opaque blobs become `<<ccr:HASH,KIND,SIZE>>` markers (with
839
- /// originals stashed in this crusher's CCR store, so `ccr_get`
840
- /// resolves them).
841
- ///
842
- /// Distinct from `crush_array_json`: this is the lossless walker
843
- /// pass without per-array lossy crushing — useful when the caller
844
- /// wants document-shape compaction (forms, configs, mixed records)
845
- /// rather than statistical row drop.
846
- fn compact_document_json(&self, py: Python<'_>, doc_json: &str) -> String {
847
- // Heavy: JSON parse + recursive walker + tabular compaction +
848
- // re-serialize. None of it touches Python; release the GIL.
849
- let doc_json = doc_json.to_string();
850
- py.allow_threads(|| {
851
- let parsed: serde_json::Value = serde_json::from_str(&doc_json)
852
- .unwrap_or_else(|e| panic!("doc_json must be JSON: {e}"));
853
- let mut dc = DocumentCompactor::new();
854
- if let Some(store) = self.inner.ccr_store() {
855
- dc = dc.with_ccr_store(store.clone());
856
- }
857
- let out = dc.compact(parsed);
858
- serde_json::to_string(&out).expect("serialize compacted document")
859
- })
860
- }
861
-
862
- /// Look up an original payload by CCR hash.
863
- ///
864
- /// When the lossy path drops rows, it stashes the **full original**
865
- /// array into the in-memory CCR store keyed by the 12-char hash
866
- /// embedded in the prompt's `<<ccr:HASH ...>>` marker. The runtime
867
- /// (proxy server / MCP retrieval tool) calls this to serve the
868
- /// dropped rows back to the LLM on demand.
869
- ///
870
- /// Returns the canonical-JSON serialization of the original
871
- /// `[item, item, ...]` array, or `None` if the hash is unknown,
872
- /// expired, or the crusher was constructed without a CCR store.
873
- fn ccr_get(&self, hash: &str) -> Option<String> {
874
- self.inner.ccr_store().and_then(|s| s.get(hash))
875
- }
876
-
877
- /// Number of entries currently held by the CCR store. `0` if no
878
- /// store is configured. Informational; use it from tests and
879
- /// telemetry, not from the retrieval hot path.
880
- fn ccr_len(&self) -> usize {
881
- self.inner.ccr_store().map(|s| s.len()).unwrap_or(0)
882
- }
883
- }
884
-
885
- // ─── ContentDetector ───────────────────────────────────────────────────────
886
-
887
- /// Mirror of `headroom.transforms.content_detector.DetectionResult`.
888
- ///
889
- /// Field names + types match the Python dataclass exactly so the existing
890
- /// Python `ContentRouter` (which `import`s `DetectionResult` directly) can
891
- /// continue to read `.content_type`, `.confidence`, and `.metadata` without
892
- /// modification.
893
- ///
894
- /// `content_type` is exposed as the lowercase string tag (e.g.
895
- /// `"json_array"`). The Python wrapper translates it back into the
896
- /// `ContentType` enum so the call-site looks identical.
897
- #[pyclass(name = "DetectionResult", module = "headroom._core")]
898
- #[derive(Clone)]
899
- struct PyDetectionResult {
900
- inner: RustDetectionResult,
901
- }
902
-
903
- #[pymethods]
904
- impl PyDetectionResult {
905
- #[getter]
906
- fn content_type(&self) -> &'static str {
907
- self.inner.content_type.as_str()
908
- }
909
-
910
- #[getter]
911
- fn confidence(&self) -> f64 {
912
- self.inner.confidence
913
- }
914
-
915
- /// Per-type metadata bag (e.g. `{"language": "python", "pattern_matches": 5}`
916
- /// for code, `{"item_count": 3, "is_dict_array": true}` for JSON arrays).
917
- /// Returned as a fresh `dict` so callers can mutate without affecting
918
- /// the underlying Rust value.
919
- #[getter]
920
- fn metadata<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
921
- let dict = PyDict::new(py);
922
- for (k, v) in &self.inner.metadata {
923
- // Convert each JSON value into the closest Python primitive.
924
- // Detection metadata is always a flat dict of scalars (ints,
925
- // bools, strings) so we don't need to recurse.
926
- match v {
927
- serde_json::Value::Bool(b) => dict.set_item(k, b)?,
928
- serde_json::Value::Number(n) => {
929
- if let Some(i) = n.as_u64() {
930
- dict.set_item(k, i)?
931
- } else if let Some(i) = n.as_i64() {
932
- dict.set_item(k, i)?
933
- } else if let Some(f) = n.as_f64() {
934
- dict.set_item(k, f)?
935
- } else {
936
- dict.set_item(k, py.None())?
937
- }
938
- }
939
- serde_json::Value::String(s) => dict.set_item(k, s)?,
940
- serde_json::Value::Null => dict.set_item(k, py.None())?,
941
- // Detection never emits arrays / objects in metadata
942
- // today; if it ever does, fall through to JSON-string for
943
- // visibility rather than silently dropping.
944
- other => dict.set_item(k, other.to_string())?,
945
- };
946
- }
947
- Ok(dict)
948
- }
949
-
950
- fn __repr__(&self) -> String {
951
- format!(
952
- "DetectionResult(content_type={:?}, confidence={}, metadata=<{} keys>)",
953
- self.inner.content_type.as_str(),
954
- self.inner.confidence,
955
- self.inner.metadata.len()
956
- )
957
- }
958
- }
959
-
960
- /// Detect the type of `content`. Returns a `DetectionResult` with the
961
- /// same field surface as Python's dataclass.
962
- ///
963
- /// Stage-3d (PR5) wired this through the magika→unidiff→PlainText
964
- /// detection chain — the regex `content_detector` is no longer on
965
- /// the production path. The chain returns a `ContentType` only;
966
- /// we synthesize the legacy `DetectionResult` shape here with
967
- /// `confidence = 1.0` (the chain doesn't surface a probabilistic
968
- /// score) and an empty metadata bag (no production caller reads
969
- /// metadata from this binding today — see audit notes in
970
- /// `headroom/transforms/content_router.py`).
971
- ///
972
- /// Releases the GIL while detecting — magika inference and unidiff
973
- /// parsing can be substantial on large bodies, and freeing the GIL
974
- /// lets other Python threads make progress in the meantime.
975
- #[pyfunction]
976
- fn detect_content_type(py: Python<'_>, content: &str) -> PyDetectionResult {
977
- let owned = content.to_string();
978
- let content_type = py.allow_threads(move || rust_detect_chain(&owned));
979
- PyDetectionResult {
980
- inner: RustDetectionResult {
981
- content_type,
982
- confidence: 1.0,
983
- metadata: serde_json::Map::new(),
984
- },
985
- }
986
- }
987
-
988
- /// Quick check: is `content` a JSON array of dictionaries (the format
989
- /// `SmartCrusher` natively handles)?
990
- #[pyfunction]
991
- fn is_json_array_of_dicts(py: Python<'_>, content: &str) -> bool {
992
- let owned = content.to_string();
993
- py.allow_threads(move || rust_is_json_array_of_dicts(&owned))
994
- }
995
-
996
- // Suppress unused-import warning when ContentType isn't referenced
997
- // directly — `as_str()` is the public surface.
998
- const _: fn() = || {
999
- let _ = RustContentType::PlainText;
1000
- };
1001
-
1002
- // ─── signals: line-importance detector bridge ────────────────────────────
1003
- //
1004
- // One process-wide [`KeywordDetector`] is shared via `OnceLock` because
1005
- // the underlying aho-corasick automaton is stateless and cheap to clone
1006
- // nothing on call. The Python shim re-exports the keyword tables and a
1007
- // pair of thin functions; that's enough surface for the legacy
1008
- // `error_detection` callers without dragging the trait into Python.
1009
-
1010
- use std::sync::OnceLock;
1011
-
1012
- fn shared_keyword_detector() -> &'static KeywordDetector {
1013
- static DETECTOR: OnceLock<KeywordDetector> = OnceLock::new();
1014
- DETECTOR.get_or_init(KeywordDetector::new)
1015
- }
1016
-
1017
- /// Returns `Some(ctx)` for known names and `None` otherwise — caller
1018
- /// converts to PyValueError. Avoids the pyo3-0.22 + clippy
1019
- /// `useless_conversion` false positive that fires when `?` propagates a
1020
- /// `PyResult<_>` through another `PyResult<_>`.
1021
- fn ctx_from_str(name: &str) -> Option<ImportanceContext> {
1022
- match name {
1023
- "text" => Some(ImportanceContext::Text),
1024
- "search" => Some(ImportanceContext::Search),
1025
- "diff" => Some(ImportanceContext::Diff),
1026
- "log" => Some(ImportanceContext::Log),
1027
- _ => None,
1028
- }
1029
- }
1030
-
1031
- fn category_to_str(cat: ImportanceCategory) -> &'static str {
1032
- match cat {
1033
- ImportanceCategory::Error => "error",
1034
- ImportanceCategory::Warning => "warning",
1035
- ImportanceCategory::Importance => "importance",
1036
- ImportanceCategory::Security => "security",
1037
- ImportanceCategory::Markdown => "markdown",
1038
- }
1039
- }
1040
-
1041
- /// Score a line against the default Headroom keyword detector.
1042
- ///
1043
- /// Returns `Some((category | None, priority, confidence))` for known
1044
- /// contexts (`text|search|diff|log`) and `None` for an unknown context
1045
- /// — the Python shim translates `None` into `ValueError` for the
1046
- /// caller. Returning `Option` instead of `PyResult` dodges the
1047
- /// pyo3-0.22 + clippy `useless_conversion` false positive that the
1048
- /// `#[pyfunction]` macro triggers when its inner result-shape carries
1049
- /// `PyErr`. The bridge layer is the right place for this conversion;
1050
- /// keeping the Rust signature panic-free and `PyResult`-free is worth
1051
- /// a one-line shim on the Python side.
1052
- #[pyfunction]
1053
- #[pyo3(signature = (line, context = "text"))]
1054
- fn score_line(line: &str, context: &str) -> Option<(Option<&'static str>, f32, f32)> {
1055
- let ctx = ctx_from_str(context)?;
1056
- let signal = shared_keyword_detector().score(line, ctx);
1057
- Some((
1058
- signal.category.map(category_to_str),
1059
- signal.priority,
1060
- signal.confidence,
1061
- ))
1062
- }
1063
-
1064
- /// Lax substring check: does `text` contain any error indicator? Mirrors
1065
- /// Python `error_detection.content_has_error_indicators`.
1066
- #[pyfunction]
1067
- fn content_has_error_indicators(text: &str) -> bool {
1068
- shared_keyword_detector().contains_error_indicator(text)
1069
- }
1070
-
1071
- /// Snapshot of the default keyword sets, exposed as a dict so the Python
1072
- /// shim can recompile the legacy `re.Pattern` objects without
1073
- /// re-declaring keyword data on the Python side. Uses `.unwrap()` on
1074
- /// `set_item` because keys are static str literals and values are
1075
- /// `Vec<&'static str>`, which can't fail — and avoids the pyo3-0.22
1076
- /// `useless_conversion` clippy false positive.
1077
- #[pyfunction]
1078
- fn keyword_registry_snapshot(py: Python<'_>) -> Py<PyDict> {
1079
- let registry = KeywordRegistry::default_set();
1080
- let dict = PyDict::new(py);
1081
- for (key, words) in registry.as_map() {
1082
- dict.set_item(key, words).unwrap();
1083
- }
1084
- dict.unbind()
1085
- }
1086
-
1087
- // ─── search_compressor bridge (Phase 3e.2) ────────────────────────────
1088
- //
1089
- // Mirrors `headroom.transforms.search_compressor.SearchCompressor` so the
1090
- // Python shim can swap in via PyO3. The Rust implementation consumes the
1091
- // `signals::LineImportanceDetector` trait for priority scoring (instead of
1092
- // the regex registry the Python original used) and fixes the Windows-path
1093
- // + dashes-in-filename parser bugs.
1094
- //
1095
- // CCR persistence is exposed via a callback hook because the proxy's
1096
- // `CompressionStore` already lives Python-side. The Rust crate holds no
1097
- // long-lived store reference; instead the caller passes the dict back
1098
- // through the result and the Python shim writes it to the existing
1099
- // store. This avoids dragging a second CCR backend into Rust before the
1100
- // Phase 3g pipeline formalization owns CCR end-to-end.
1101
-
1102
- #[pyclass(name = "SearchCompressorConfig", module = "headroom._core")]
1103
- #[derive(Clone)]
1104
- struct PySearchCompressorConfig {
1105
- inner: RustSearchConfig,
1106
- }
1107
-
1108
- #[pymethods]
1109
- impl PySearchCompressorConfig {
1110
- #[new]
1111
- #[pyo3(signature = (
1112
- max_matches_per_file = 5,
1113
- always_keep_first = true,
1114
- always_keep_last = true,
1115
- max_total_matches = 30,
1116
- max_files = 15,
1117
- context_keywords = vec![],
1118
- boost_errors = true,
1119
- enable_ccr = true,
1120
- min_matches_for_ccr = 10,
1121
- min_compression_ratio_for_ccr = 0.8,
1122
- group_by_file = false,
1123
- ))]
1124
- #[allow(clippy::too_many_arguments)]
1125
- fn new(
1126
- max_matches_per_file: usize,
1127
- always_keep_first: bool,
1128
- always_keep_last: bool,
1129
- max_total_matches: usize,
1130
- max_files: usize,
1131
- context_keywords: Vec<String>,
1132
- boost_errors: bool,
1133
- enable_ccr: bool,
1134
- min_matches_for_ccr: usize,
1135
- min_compression_ratio_for_ccr: f64,
1136
- group_by_file: bool,
1137
- ) -> Self {
1138
- Self {
1139
- inner: RustSearchConfig {
1140
- max_matches_per_file,
1141
- always_keep_first,
1142
- always_keep_last,
1143
- max_total_matches,
1144
- max_files,
1145
- context_keywords,
1146
- boost_errors,
1147
- enable_ccr,
1148
- min_matches_for_ccr,
1149
- min_compression_ratio_for_ccr,
1150
- group_by_file,
1151
- },
1152
- }
1153
- }
1154
- }
1155
-
1156
- #[pyclass(name = "SearchCompressionResult", module = "headroom._core")]
1157
- struct PySearchCompressionResult {
1158
- inner: RustSearchResult,
1159
- stats: RustSearchStats,
1160
- }
1161
-
1162
- #[pymethods]
1163
- impl PySearchCompressionResult {
1164
- #[getter]
1165
- fn compressed(&self) -> &str {
1166
- &self.inner.compressed
1167
- }
1168
- #[getter]
1169
- fn original(&self) -> &str {
1170
- &self.inner.original
1171
- }
1172
- #[getter]
1173
- fn original_match_count(&self) -> usize {
1174
- self.inner.original_match_count
1175
- }
1176
- #[getter]
1177
- fn compressed_match_count(&self) -> usize {
1178
- self.inner.compressed_match_count
1179
- }
1180
- #[getter]
1181
- fn files_affected(&self) -> usize {
1182
- self.inner.files_affected
1183
- }
1184
- #[getter]
1185
- fn compression_ratio(&self) -> f64 {
1186
- self.inner.compression_ratio
1187
- }
1188
- #[getter]
1189
- fn cache_key(&self) -> Option<&str> {
1190
- self.inner.cache_key.as_deref()
1191
- }
1192
- #[getter]
1193
- fn summaries<'py>(&self, py: Python<'py>) -> Bound<'py, PyDict> {
1194
- let dict = PyDict::new(py);
1195
- for (k, v) in &self.inner.summaries {
1196
- dict.set_item(k, v).unwrap();
1197
- }
1198
- dict
1199
- }
1200
- /// Sidecar stats — same shape every Rust transform uses for OTel.
1201
- #[getter]
1202
- fn lines_unparsed(&self) -> usize {
1203
- self.stats.lines_unparsed
1204
- }
1205
- #[getter]
1206
- fn files_dropped(&self) -> usize {
1207
- self.stats.files_dropped
1208
- }
1209
- #[getter]
1210
- fn ccr_emitted(&self) -> bool {
1211
- self.stats.ccr_emitted
1212
- }
1213
- #[getter]
1214
- fn ccr_skip_reason(&self) -> Option<&str> {
1215
- self.stats.ccr_skip_reason
1216
- }
1217
- }
1218
-
1219
- #[pyclass(name = "SearchCompressor", module = "headroom._core")]
1220
- struct PySearchCompressor {
1221
- inner: RustSearchCompressor,
1222
- }
1223
-
1224
- #[pymethods]
1225
- impl PySearchCompressor {
1226
- #[new]
1227
- #[pyo3(signature = (config = None))]
1228
- fn new(config: Option<PySearchCompressorConfig>) -> Self {
1229
- let cfg = config.map(|c| c.inner).unwrap_or_default();
1230
- Self {
1231
- inner: RustSearchCompressor::new(cfg),
1232
- }
1233
- }
1234
-
1235
- /// Compress `content`. CCR persistence is the caller's responsibility
1236
- /// — the Rust side never writes to the store. If the result needs a
1237
- /// CCR marker, `cache_key` will be populated and the Python shim
1238
- /// writes the original to the existing `CompressionStore`. This
1239
- /// matches Python's existing CCR plumbing and avoids dragging a
1240
- /// second backend into the Rust crate.
1241
- ///
1242
- /// (Internally the Rust CcrStore trait is used for unit tests; the
1243
- /// PyO3 surface stays Python-CCR-friendly.)
1244
- #[pyo3(signature = (content, context = "", bias = 1.0))]
1245
- fn compress(
1246
- &self,
1247
- py: Python<'_>,
1248
- content: &str,
1249
- context: &str,
1250
- bias: f64,
1251
- ) -> PySearchCompressionResult {
1252
- // Synthesize a tiny in-memory store so the Rust path can
1253
- // populate `cache_key`; the Python side reads `cache_key` and
1254
- // writes the original to its own `CompressionStore` if it
1255
- // wants persistence beyond the request lifecycle.
1256
- let owned = content.to_string();
1257
- let owned_ctx = context.to_string();
1258
- let (result, stats) = py.allow_threads(move || {
1259
- let store = headroom_core::ccr::InMemoryCcrStore::new();
1260
- let (r, s) = self
1261
- .inner
1262
- .compress_with_store(&owned, &owned_ctx, bias, Some(&store));
1263
- (r, s)
1264
- });
1265
- PySearchCompressionResult {
1266
- inner: result,
1267
- stats,
1268
- }
1269
- }
1270
- }
1271
-
1272
- /// Parse one grep/ripgrep line into `(file, line_number, content)`. Used
1273
- /// by the Python shim's `_parse_search_results` so the bug-fixed parser
1274
- /// runs even when callers use the legacy internal helpers (which exist
1275
- /// only for backwards-compat with the existing test surface).
1276
- #[pyfunction]
1277
- fn parse_search_lines(content: &str) -> Vec<(String, u64, String)> {
1278
- let compressor = RustSearchCompressor::new(RustSearchConfig::default());
1279
- let mut stats = RustSearchStats::default();
1280
- let parsed = compressor.parse_search_results(content, &mut stats);
1281
- let mut out = Vec::new();
1282
- for fm in parsed.values() {
1283
- for m in &fm.matches {
1284
- out.push((m.file.clone(), m.line_number, m.content.clone()));
1285
- }
1286
- }
1287
- out
1288
- }
1289
-
1290
- // ─── log_compressor bridge (Phase 3e.5) ───────────────────────────────
1291
- //
1292
- // Mirrors `headroom.transforms.log_compressor.LogCompressor`. Same CCR
1293
- // pattern as search_compressor: Rust emits a `cache_key`, Python shim
1294
- // writes the original to the production `CompressionStore`.
1295
-
1296
- #[pyclass(name = "LogCompressorConfig", module = "headroom._core")]
1297
- #[derive(Clone)]
1298
- struct PyLogCompressorConfig {
1299
- inner: RustLogConfig,
1300
- }
1301
-
1302
- #[pymethods]
1303
- impl PyLogCompressorConfig {
1304
- #[new]
1305
- #[pyo3(signature = (
1306
- max_errors = 10,
1307
- error_context_lines = 3,
1308
- keep_first_error = true,
1309
- keep_last_error = true,
1310
- max_stack_traces = 3,
1311
- stack_trace_max_lines = 20,
1312
- max_warnings = 5,
1313
- dedupe_warnings = true,
1314
- keep_summary_lines = true,
1315
- max_total_lines = 100,
1316
- enable_ccr = true,
1317
- min_lines_for_ccr = 50,
1318
- min_compression_ratio_for_ccr = 0.5,
1319
- ))]
1320
- #[allow(clippy::too_many_arguments)]
1321
- fn new(
1322
- max_errors: usize,
1323
- error_context_lines: usize,
1324
- keep_first_error: bool,
1325
- keep_last_error: bool,
1326
- max_stack_traces: usize,
1327
- stack_trace_max_lines: usize,
1328
- max_warnings: usize,
1329
- dedupe_warnings: bool,
1330
- keep_summary_lines: bool,
1331
- max_total_lines: usize,
1332
- enable_ccr: bool,
1333
- min_lines_for_ccr: usize,
1334
- min_compression_ratio_for_ccr: f64,
1335
- ) -> Self {
1336
- Self {
1337
- inner: RustLogConfig {
1338
- max_errors,
1339
- error_context_lines,
1340
- keep_first_error,
1341
- keep_last_error,
1342
- max_stack_traces,
1343
- stack_trace_max_lines,
1344
- max_warnings,
1345
- dedupe_warnings,
1346
- keep_summary_lines,
1347
- max_total_lines,
1348
- enable_ccr,
1349
- min_lines_for_ccr,
1350
- min_compression_ratio_for_ccr,
1351
- },
1352
- }
1353
- }
1354
- }
1355
-
1356
- #[pyclass(name = "LogCompressionResult", module = "headroom._core")]
1357
- struct PyLogCompressionResult {
1358
- inner: RustLogResult,
1359
- stats: RustLogStats,
1360
- }
1361
-
1362
- #[pymethods]
1363
- impl PyLogCompressionResult {
1364
- #[getter]
1365
- fn compressed(&self) -> &str {
1366
- &self.inner.compressed
1367
- }
1368
- #[getter]
1369
- fn original(&self) -> &str {
1370
- &self.inner.original
1371
- }
1372
- #[getter]
1373
- fn original_line_count(&self) -> usize {
1374
- self.inner.original_line_count
1375
- }
1376
- #[getter]
1377
- fn compressed_line_count(&self) -> usize {
1378
- self.inner.compressed_line_count
1379
- }
1380
- #[getter]
1381
- fn format_detected(&self) -> &'static str {
1382
- self.inner.format_detected.as_str()
1383
- }
1384
- #[getter]
1385
- fn compression_ratio(&self) -> f64 {
1386
- self.inner.compression_ratio
1387
- }
1388
- #[getter]
1389
- fn cache_key(&self) -> Option<&str> {
1390
- self.inner.cache_key.as_deref()
1391
- }
1392
- #[getter]
1393
- fn stats<'py>(&self, py: Python<'py>) -> Bound<'py, PyDict> {
1394
- let dict = PyDict::new(py);
1395
- for (k, v) in &self.inner.stats {
1396
- dict.set_item(k, v).unwrap();
1397
- }
1398
- dict
1399
- }
1400
- // Sidecar diagnostics
1401
- #[getter]
1402
- fn stack_traces_seen(&self) -> usize {
1403
- self.stats.stack_traces_seen
1404
- }
1405
- #[getter]
1406
- fn stack_traces_kept(&self) -> usize {
1407
- self.stats.stack_traces_kept
1408
- }
1409
- #[getter]
1410
- fn warnings_dropped_by_dedupe(&self) -> usize {
1411
- self.stats.warnings_dropped_by_dedupe
1412
- }
1413
- #[getter]
1414
- fn ccr_emitted(&self) -> bool {
1415
- self.stats.ccr_emitted
1416
- }
1417
- #[getter]
1418
- fn ccr_skip_reason(&self) -> Option<&str> {
1419
- self.stats.ccr_skip_reason
1420
- }
1421
- }
1422
-
1423
- #[pyclass(name = "LogCompressor", module = "headroom._core")]
1424
- struct PyLogCompressor {
1425
- inner: RustLogCompressor,
1426
- }
1427
-
1428
- #[pymethods]
1429
- impl PyLogCompressor {
1430
- #[new]
1431
- #[pyo3(signature = (config = None))]
1432
- fn new(config: Option<PyLogCompressorConfig>) -> Self {
1433
- let cfg = config.map(|c| c.inner).unwrap_or_default();
1434
- Self {
1435
- inner: RustLogCompressor::new(cfg),
1436
- }
1437
- }
1438
-
1439
- /// Compress `content`. Same CCR pattern as search_compressor: Rust
1440
- /// emits the `cache_key`; the Python shim is responsible for
1441
- /// writing the original to the production `CompressionStore`.
1442
- #[pyo3(signature = (content, bias = 1.0))]
1443
- fn compress(&self, py: Python<'_>, content: &str, bias: f64) -> PyLogCompressionResult {
1444
- let owned = content.to_string();
1445
- let (result, stats) = py.allow_threads(move || {
1446
- let store = headroom_core::ccr::InMemoryCcrStore::new();
1447
- let (r, s) = self.inner.compress_with_store(&owned, bias, Some(&store));
1448
- (r, s)
1449
- });
1450
- PyLogCompressionResult {
1451
- inner: result,
1452
- stats,
1453
- }
1454
- }
1455
- }
1456
-
1457
- /// Helper for the Python shim's `_detect_format`.
1458
- #[pyfunction]
1459
- fn detect_log_format(lines: Vec<String>) -> &'static str {
1460
- let compressor = RustLogCompressor::new(RustLogConfig::default());
1461
- let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
1462
- compressor.detect_format(&refs).as_str()
1463
- }
1464
-
1465
- /// Suppress unused-import warnings for the LogLevel/LogFormat imports
1466
- /// kept for future expansion (the Python shim consumes them via
1467
- /// detect_log_format and the result format_detected getter).
1468
- const _: fn() = || {
1469
- let _ = RustLogFormat::Generic;
1470
- let _ = RustLogLevel::Unknown;
1471
- };
1472
-
1473
- // ─── tag_protector bridge (Phase 3e.4) ───────────────────────────────────
1474
- //
1475
- // Mirrors `headroom.transforms.tag_protector.{protect_tags,restore_tags,
1476
- // is_html_tag,KNOWN_HTML_TAGS}`. The Rust walker is single-pass and
1477
- // fixes five real bugs the Python original carried (see crate-level
1478
- // docs in `tag_protector.rs`). The GIL is released during the walk
1479
- // because the algorithm holds no Python references.
1480
-
1481
- /// Replace custom workflow tags in `text` with opaque placeholders so
1482
- /// downstream ML compressors can't accidentally drop them.
1483
- ///
1484
- /// Returns `(cleaned_text, blocks)` where `blocks` is a list of
1485
- /// `(placeholder, original)` tuples for `restore_tags`.
1486
- #[pyfunction]
1487
- #[pyo3(signature = (text, compress_tagged_content = false))]
1488
- fn protect_tags(
1489
- py: Python<'_>,
1490
- text: &str,
1491
- compress_tagged_content: bool,
1492
- ) -> (String, Vec<(String, String)>) {
1493
- let owned = text.to_string();
1494
- py.allow_threads(move || {
1495
- let (cleaned, blocks, _stats) = rust_protect_tags(&owned, compress_tagged_content);
1496
- (cleaned, blocks)
1497
- })
1498
- }
1499
-
1500
- /// Splice protected blocks back into `text`. Missing placeholders fall
1501
- /// back to appending the original block (lossy-compression incident).
1502
- #[pyfunction]
1503
- fn restore_tags(py: Python<'_>, text: &str, blocks: Vec<(String, String)>) -> String {
1504
- let owned = text.to_string();
1505
- py.allow_threads(move || rust_restore_tags(&owned, &blocks))
1506
- }
1507
-
1508
- /// Case-insensitive HTML5 tag check. The Python shim uses this to
1509
- /// preserve the legacy private `_is_html_tag` import surface for tests.
1510
- #[pyfunction]
1511
- fn is_html_tag(name: &str) -> bool {
1512
- rust_is_known_html_tag(name)
1513
- }
1514
-
1515
- /// Return the canonical HTML5 tag name list. The Python shim
1516
- /// reconstructs `KNOWN_HTML_TAGS` from this so callers that import the
1517
- /// frozenset (the existing test does) continue to work without
1518
- /// re-declaring the set in two languages.
1519
- #[pyfunction]
1520
- fn known_html_tag_names() -> Vec<&'static str> {
1521
- rust_known_html_tag_names().to_vec()
1522
- }
1523
-
1524
- // ─── Module init ───────────────────────────────────────────────────────────
1525
-
1526
- /// Apply OpenAI `/v1/responses` live-zone compression to a request body.
1527
- ///
1528
- /// Hot-fix entry point added 2026-05-06: re-enables `/v1/responses`
1529
- /// compression on the Python proxy after PR-C5 retired the Python
1530
- /// pipeline. PR-C5's "Rust handles it" claim assumed the standalone
1531
- /// `crates/headroom-proxy` binary would sit in front of Python; that
1532
- /// binary is not deployed by the CLI (`headroom proxy`,
1533
- /// `headroom wrap codex`). This binding lets the Python proxy call
1534
- /// the live-zone dispatcher inline so Codex `/v1/responses` traffic
1535
- /// is compressed end-to-end.
1536
- ///
1537
- /// # Arguments
1538
- /// * `body` — raw request body bytes (post memory-injection).
1539
- /// * `auth_mode` — one of `"payg"`, `"oauth"`, `"subscription"`,
1540
- /// `"unknown"`. Currently unused by the dispatcher (the policy
1541
- /// gating is upstream); accepted for forward-compat.
1542
- /// * `model` — model name from the request body. Empty string defaults
1543
- /// to `headroom_core::transforms::live_zone::DEFAULT_MODEL`.
1544
- ///
1545
- /// # Returns
1546
- /// `(body, modified)`:
1547
- /// * Modified: `(new_body_bytes, True)` — caller forwards the new bytes.
1548
- /// * Unchanged / passthrough: `(input_bytes, False)` — caller forwards
1549
- /// the original.
1550
- ///
1551
- /// # Failure mode
1552
- /// Never raises. The dispatcher's `LiveZoneError` outcomes (body not
1553
- /// JSON, no `messages`/`input` array) are passthrough conditions, not
1554
- /// failures — matching the Rust proxy's
1555
- /// `compress_openai_responses_request` contract.
1556
- #[pyfunction]
1557
- #[pyo3(signature = (body, auth_mode = "payg", model = ""))]
1558
- fn compress_openai_responses_live_zone(
1559
- py: Python<'_>,
1560
- body: &[u8],
1561
- auth_mode: &str,
1562
- model: &str,
1563
- ) -> (Py<PyBytes>, bool, u64, Vec<String>, Option<String>) {
1564
- let mode = match auth_mode.to_ascii_lowercase().as_str() {
1565
- "payg" => RustLiveZoneAuthMode::Payg,
1566
- "oauth" => RustLiveZoneAuthMode::OAuth,
1567
- "subscription" => RustLiveZoneAuthMode::Subscription,
1568
- _ => RustLiveZoneAuthMode::Unknown,
1569
- };
1570
- let model_str = if model.is_empty() {
1571
- headroom_core::transforms::live_zone::DEFAULT_MODEL
1572
- } else {
1573
- model
1574
- };
1575
-
1576
- match rust_compress_openai_responses_live_zone(body, mode, model_str) {
1577
- Ok(LiveZoneOutcome::NoChange { manifest }) => {
1578
- let saved = manifest.tokens_saved() as u64;
1579
- let transforms: Vec<String> = manifest
1580
- .transforms_applied()
1581
- .into_iter()
1582
- .map(String::from)
1583
- .collect();
1584
- let reason = rust_summarize_openai_responses_no_change_reason(&manifest).to_string();
1585
- (
1586
- PyBytes::new(py, body).unbind(),
1587
- false,
1588
- saved,
1589
- transforms,
1590
- Some(reason),
1591
- )
1592
- }
1593
- Ok(LiveZoneOutcome::Modified { new_body, manifest }) => {
1594
- // `RawValue::get` returns the underlying serialized JSON
1595
- // as `&str`; bytes are valid UTF-8 by construction.
1596
- let bytes = new_body.get().as_bytes();
1597
- let saved = manifest.tokens_saved() as u64;
1598
- let transforms: Vec<String> = manifest
1599
- .transforms_applied()
1600
- .into_iter()
1601
- .map(String::from)
1602
- .collect();
1603
- (
1604
- PyBytes::new(py, bytes).unbind(),
1605
- true,
1606
- saved,
1607
- transforms,
1608
- None,
1609
- )
1610
- }
1611
- Err(_) => {
1612
- // BodyNotJson / NoMessagesArray are non-fatal: nothing to
1613
- // compress, fall through to passthrough byte-for-byte.
1614
- (
1615
- PyBytes::new(py, body).unbind(),
1616
- false,
1617
- 0,
1618
- Vec::new(),
1619
- Some("dispatch_error".to_string()),
1620
- )
1621
- }
1622
- }
1623
- }
1624
-
1625
- #[pymodule]
1626
- fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
1627
- m.add_function(wrap_pyfunction!(hello, m)?)?;
1628
- m.add_class::<PyDiffCompressorConfig>()?;
1629
- m.add_class::<PyDiffCompressionResult>()?;
1630
- m.add_class::<PyDiffCompressorStats>()?;
1631
- m.add_class::<PyDiffCompressor>()?;
1632
- m.add_class::<PySearchCompressorConfig>()?;
1633
- m.add_class::<PySearchCompressionResult>()?;
1634
- m.add_class::<PySearchCompressor>()?;
1635
- m.add_function(wrap_pyfunction!(parse_search_lines, m)?)?;
1636
- m.add_class::<PySmartCrusherConfig>()?;
1637
- m.add_class::<PyCrushResult>()?;
1638
- m.add_class::<PySmartCrusher>()?;
1639
- m.add_class::<PyDetectionResult>()?;
1640
- m.add_class::<PyLogCompressorConfig>()?;
1641
- m.add_class::<PyLogCompressionResult>()?;
1642
- m.add_class::<PyLogCompressor>()?;
1643
- m.add_function(wrap_pyfunction!(detect_log_format, m)?)?;
1644
- m.add_function(wrap_pyfunction!(protect_tags, m)?)?;
1645
- m.add_function(wrap_pyfunction!(restore_tags, m)?)?;
1646
- m.add_function(wrap_pyfunction!(is_html_tag, m)?)?;
1647
- m.add_function(wrap_pyfunction!(known_html_tag_names, m)?)?;
1648
- m.add_function(wrap_pyfunction!(detect_content_type, m)?)?;
1649
- m.add_function(wrap_pyfunction!(is_json_array_of_dicts, m)?)?;
1650
- m.add_function(wrap_pyfunction!(score_line, m)?)?;
1651
- m.add_function(wrap_pyfunction!(content_has_error_indicators, m)?)?;
1652
- m.add_function(wrap_pyfunction!(keyword_registry_snapshot, m)?)?;
1653
- m.add_function(wrap_pyfunction!(compress_openai_responses_live_zone, m)?)?;
1654
- Ok(())
1655
- }