xithead 1.5.0 → 1.5.2

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