xithead 1.4.0 → 1.5.0

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