thumbgate 0.9.9

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 (369) hide show
  1. package/.claude-plugin/README.md +134 -0
  2. package/.claude-plugin/bundle/icon.png +0 -0
  3. package/.claude-plugin/bundle/icon.svg +18 -0
  4. package/.claude-plugin/bundle/server/index.js +24 -0
  5. package/.claude-plugin/marketplace.json +36 -0
  6. package/.claude-plugin/plugin.json +21 -0
  7. package/.well-known/mcp/server-card.json +231 -0
  8. package/LICENSE +21 -0
  9. package/README.md +375 -0
  10. package/adapters/README.md +9 -0
  11. package/adapters/amp/skills/rlhf-feedback/SKILL.md +22 -0
  12. package/adapters/chatgpt/INSTALL.md +83 -0
  13. package/adapters/chatgpt/openapi.yaml +1281 -0
  14. package/adapters/claude/.mcp.json +14 -0
  15. package/adapters/codex/config.toml +9 -0
  16. package/adapters/gemini/function-declarations.json +224 -0
  17. package/adapters/mcp/server-stdio.js +788 -0
  18. package/adapters/opencode/opencode.json +15 -0
  19. package/bin/cli.js +1483 -0
  20. package/bin/memory.sh +64 -0
  21. package/bin/obsidian-sync.sh +20 -0
  22. package/bin/postinstall.js +37 -0
  23. package/config/build-metadata.json +4 -0
  24. package/config/e2e-critical-flows.json +45 -0
  25. package/config/gate-templates.json +77 -0
  26. package/config/gates/claim-verification.json +29 -0
  27. package/config/gates/computer-use.json +39 -0
  28. package/config/gates/default.json +117 -0
  29. package/config/github-about.json +25 -0
  30. package/config/mcp-allowlists.json +135 -0
  31. package/config/model-tiers.json +33 -0
  32. package/config/partner-routing.json +132 -0
  33. package/config/policy-bundles/constrained-v1.json +64 -0
  34. package/config/policy-bundles/default-v1.json +91 -0
  35. package/config/rubrics/default-v1.json +52 -0
  36. package/config/skill-packs/react-testing.json +23 -0
  37. package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
  38. package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
  39. package/config/skill-specs/pr-reviewer.json +9 -0
  40. package/config/skill-specs/release-status.json +9 -0
  41. package/config/skill-specs/ticket-triage.json +9 -0
  42. package/config/subagent-profiles.json +32 -0
  43. package/config/tessl-tiles.json +29 -0
  44. package/config/thumbgate-settings.managed.json +12 -0
  45. package/openapi/openapi.yaml +1281 -0
  46. package/package.json +286 -0
  47. package/plugins/amp-skill/INSTALL.md +52 -0
  48. package/plugins/amp-skill/SKILL.md +64 -0
  49. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
  50. package/plugins/claude-codex-bridge/.mcp.json +12 -0
  51. package/plugins/claude-codex-bridge/INSTALL.md +43 -0
  52. package/plugins/claude-codex-bridge/README.md +46 -0
  53. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
  54. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
  55. package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
  56. package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
  57. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
  58. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
  59. package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
  60. package/plugins/claude-skill/INSTALL.md +55 -0
  61. package/plugins/claude-skill/SKILL.md +46 -0
  62. package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
  63. package/plugins/codex-profile/.mcp.json +12 -0
  64. package/plugins/codex-profile/AGENTS.md +20 -0
  65. package/plugins/codex-profile/INSTALL.md +66 -0
  66. package/plugins/codex-profile/README.md +37 -0
  67. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
  68. package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
  69. package/plugins/cursor-marketplace/LICENSE +21 -0
  70. package/plugins/cursor-marketplace/README.md +124 -0
  71. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
  72. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  73. package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
  74. package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
  75. package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
  76. package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
  77. package/plugins/cursor-marketplace/mcp.json +12 -0
  78. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
  79. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
  80. package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
  81. package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
  82. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
  83. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
  84. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
  85. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
  86. package/plugins/gemini-extension/INSTALL.md +92 -0
  87. package/plugins/gemini-extension/gemini_prompt.txt +14 -0
  88. package/plugins/gemini-extension/tool_contract.json +45 -0
  89. package/plugins/opencode-profile/INSTALL.md +57 -0
  90. package/public/assets/instagram-card.png +0 -0
  91. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  92. package/public/blog.html +400 -0
  93. package/public/dashboard.html +1093 -0
  94. package/public/guide.html +317 -0
  95. package/public/index.html +1195 -0
  96. package/public/learn/agent-harness-pattern.html +180 -0
  97. package/public/learn/ai-agent-persistent-memory.html +202 -0
  98. package/public/learn/learn.css +45 -0
  99. package/public/learn/mcp-pre-action-gates-explained.html +172 -0
  100. package/public/learn/stop-ai-agent-force-push.html +134 -0
  101. package/public/learn/vibe-coding-safety-net.html +142 -0
  102. package/public/learn.html +213 -0
  103. package/public/lessons.html +650 -0
  104. package/public/vercel.json +8 -0
  105. package/scripts/__pycache__/train_from_feedback.cpython-314.pyc +0 -0
  106. package/scripts/a2ui-engine.js +73 -0
  107. package/scripts/access-anomaly-detector.js +12 -0
  108. package/scripts/adk-consolidator.js +266 -0
  109. package/scripts/agent-readiness.js +220 -0
  110. package/scripts/agent-security-hardening.js +227 -0
  111. package/scripts/agentic-data-pipeline.js +847 -0
  112. package/scripts/analytics-report.js +328 -0
  113. package/scripts/analytics-window.js +158 -0
  114. package/scripts/async-job-runner.js +1001 -0
  115. package/scripts/audit-trail.js +398 -0
  116. package/scripts/auto-promote-gates.js +293 -0
  117. package/scripts/auto-wire-hooks.js +316 -0
  118. package/scripts/autonomous-sales-agent.js +39 -0
  119. package/scripts/autoresearch-runner.js +216 -0
  120. package/scripts/background-agent-governance.js +237 -0
  121. package/scripts/behavioral-extraction.js +93 -0
  122. package/scripts/belief-update.js +84 -0
  123. package/scripts/billing.js +2438 -0
  124. package/scripts/bot-detector.js +50 -0
  125. package/scripts/budget-guard.js +173 -0
  126. package/scripts/build-claude-mcpb.js +189 -0
  127. package/scripts/build-metadata.js +97 -0
  128. package/scripts/check-congruence.js +322 -0
  129. package/scripts/cli-feedback.js +135 -0
  130. package/scripts/cli-telemetry.js +87 -0
  131. package/scripts/cloudflare-dynamic-sandbox.js +315 -0
  132. package/scripts/code-reasoning.js +350 -0
  133. package/scripts/codegraph-context.js +466 -0
  134. package/scripts/commercial-offer.js +56 -0
  135. package/scripts/computer-use-firewall.js +250 -0
  136. package/scripts/context-engine.js +694 -0
  137. package/scripts/contextfs.js +1287 -0
  138. package/scripts/conversation-context.js +119 -0
  139. package/scripts/creator-campaigns.js +239 -0
  140. package/scripts/daemon-manager.js +108 -0
  141. package/scripts/daily-digest.js +11 -0
  142. package/scripts/dashboard-render-spec.js +395 -0
  143. package/scripts/dashboard.js +1058 -0
  144. package/scripts/data-governance.js +173 -0
  145. package/scripts/delegation-runtime.js +900 -0
  146. package/scripts/deploy-gcp.sh +44 -0
  147. package/scripts/deploy-policy.js +231 -0
  148. package/scripts/disagreement-mining.js +315 -0
  149. package/scripts/dispatch-brief.js +159 -0
  150. package/scripts/distribution-surfaces.js +44 -0
  151. package/scripts/dpo-optimizer.js +206 -0
  152. package/scripts/ensure-repo-bootstrap.js +129 -0
  153. package/scripts/ephemeral-agent-store.js +219 -0
  154. package/scripts/eval-harness.js +56 -0
  155. package/scripts/evolution-state.js +241 -0
  156. package/scripts/experiment-tracker.js +267 -0
  157. package/scripts/export-databricks-bundle.js +242 -0
  158. package/scripts/export-dpo-pairs.js +344 -0
  159. package/scripts/export-kto-pairs.js +309 -0
  160. package/scripts/export-training.js +450 -0
  161. package/scripts/failure-diagnostics.js +558 -0
  162. package/scripts/feedback-attribution.js +313 -0
  163. package/scripts/feedback-fallback.js +110 -0
  164. package/scripts/feedback-history-distiller.js +391 -0
  165. package/scripts/feedback-inbox-read.js +162 -0
  166. package/scripts/feedback-loop.js +1887 -0
  167. package/scripts/feedback-paths.js +145 -0
  168. package/scripts/feedback-quality.js +139 -0
  169. package/scripts/feedback-root-consolidator.js +238 -0
  170. package/scripts/feedback-schema.js +426 -0
  171. package/scripts/feedback-session.js +286 -0
  172. package/scripts/feedback-to-memory.js +185 -0
  173. package/scripts/feedback-to-rules.js +164 -0
  174. package/scripts/filesystem-search.js +405 -0
  175. package/scripts/funnel-analytics.js +35 -0
  176. package/scripts/gate-satisfy.js +42 -0
  177. package/scripts/gate-stats.js +116 -0
  178. package/scripts/gate-templates.js +70 -0
  179. package/scripts/gates-engine.js +816 -0
  180. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  181. package/scripts/generate-pretool-hook.sh +40 -0
  182. package/scripts/github-about.js +350 -0
  183. package/scripts/github-outreach.js +65 -0
  184. package/scripts/gtm-revenue-loop.js +520 -0
  185. package/scripts/hallucination-detector.js +226 -0
  186. package/scripts/hf-papers.js +317 -0
  187. package/scripts/history-distiller.js +200 -0
  188. package/scripts/hook-auto-capture.sh +100 -0
  189. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  190. package/scripts/hook-stop-self-score.sh +51 -0
  191. package/scripts/hook-stop-verify-deploy.sh +31 -0
  192. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  193. package/scripts/hook-verify-before-done.sh +20 -0
  194. package/scripts/hosted-config.js +156 -0
  195. package/scripts/hybrid-feedback-context.js +675 -0
  196. package/scripts/install-mcp.js +159 -0
  197. package/scripts/intent-router.js +392 -0
  198. package/scripts/internal-agent-bootstrap.js +490 -0
  199. package/scripts/jsonl-watcher.js +155 -0
  200. package/scripts/lesson-db.js +613 -0
  201. package/scripts/lesson-inference.js +310 -0
  202. package/scripts/lesson-retrieval.js +95 -0
  203. package/scripts/lesson-rotation.js +137 -0
  204. package/scripts/lesson-search.js +644 -0
  205. package/scripts/lesson-synthesis.js +196 -0
  206. package/scripts/license.js +50 -0
  207. package/scripts/local-model-profile.js +384 -0
  208. package/scripts/markdown-escape.js +12 -0
  209. package/scripts/marketing-experiment.js +671 -0
  210. package/scripts/mcp-config.js +149 -0
  211. package/scripts/mcp-policy.js +99 -0
  212. package/scripts/memalign-recall.js +111 -0
  213. package/scripts/memory-firewall.js +222 -0
  214. package/scripts/memory-migration.js +296 -0
  215. package/scripts/meta-policy.js +190 -0
  216. package/scripts/metered-billing.js +16 -0
  217. package/scripts/model-tier-router.js +301 -0
  218. package/scripts/money-watcher.js +71 -0
  219. package/scripts/multi-hop-recall.js +240 -0
  220. package/scripts/natural-language-harness.js +330 -0
  221. package/scripts/obsidian-export.js +713 -0
  222. package/scripts/operational-dashboard.js +103 -0
  223. package/scripts/operational-summary.js +93 -0
  224. package/scripts/optimize-context.js +17 -0
  225. package/scripts/org-dashboard.js +201 -0
  226. package/scripts/partner-orchestration.js +146 -0
  227. package/scripts/per-step-scoring.js +165 -0
  228. package/scripts/perplexity-marketing.js +466 -0
  229. package/scripts/pii-scanner.js +153 -0
  230. package/scripts/plan-gate.js +154 -0
  231. package/scripts/post-everywhere.js +308 -0
  232. package/scripts/post-to-x-retry.sh +22 -0
  233. package/scripts/post-to-x.js +369 -0
  234. package/scripts/pr-manager.js +236 -0
  235. package/scripts/predictive-insights.js +356 -0
  236. package/scripts/principle-extractor.js +162 -0
  237. package/scripts/pro-features.js +40 -0
  238. package/scripts/pro-local-dashboard.js +174 -0
  239. package/scripts/problem-detail.js +53 -0
  240. package/scripts/product-feedback.js +134 -0
  241. package/scripts/profile-router.js +245 -0
  242. package/scripts/prompt-dlp.js +221 -0
  243. package/scripts/prompt-guard.js +83 -0
  244. package/scripts/prove-adapters.js +863 -0
  245. package/scripts/prove-attribution.js +365 -0
  246. package/scripts/prove-automation.js +653 -0
  247. package/scripts/prove-autoresearch.js +304 -0
  248. package/scripts/prove-claim-verification.js +277 -0
  249. package/scripts/prove-cloudflare-sandbox.js +163 -0
  250. package/scripts/prove-data-pipeline.js +410 -0
  251. package/scripts/prove-data-quality.js +227 -0
  252. package/scripts/prove-evolution.js +352 -0
  253. package/scripts/prove-harnesses.js +287 -0
  254. package/scripts/prove-intelligence.js +259 -0
  255. package/scripts/prove-lancedb.js +371 -0
  256. package/scripts/prove-local-intelligence.js +342 -0
  257. package/scripts/prove-loop-closure.js +263 -0
  258. package/scripts/prove-predictive-insights.js +357 -0
  259. package/scripts/prove-runtime.js +350 -0
  260. package/scripts/prove-seo-gsd.js +234 -0
  261. package/scripts/prove-settings.js +279 -0
  262. package/scripts/prove-subway-upgrades.js +277 -0
  263. package/scripts/prove-tessl.js +229 -0
  264. package/scripts/prove-training-export.js +327 -0
  265. package/scripts/prove-workflow-contract.js +116 -0
  266. package/scripts/prove-xmemory.js +332 -0
  267. package/scripts/publish-decision.js +133 -0
  268. package/scripts/pulse.js +80 -0
  269. package/scripts/rate-limiter.js +125 -0
  270. package/scripts/reddit-dm-outreach.js +182 -0
  271. package/scripts/reddit-monitor-cron.sh +26 -0
  272. package/scripts/reflector-agent.js +221 -0
  273. package/scripts/reminder-engine.js +132 -0
  274. package/scripts/revenue-status.js +472 -0
  275. package/scripts/risk-scorer.js +459 -0
  276. package/scripts/rlaif-self-audit.js +129 -0
  277. package/scripts/rlhf_session_start.sh +32 -0
  278. package/scripts/rubric-engine.js +230 -0
  279. package/scripts/schedule-manager.js +251 -0
  280. package/scripts/secret-scanner.js +414 -0
  281. package/scripts/self-heal.js +147 -0
  282. package/scripts/self-healing-check.js +188 -0
  283. package/scripts/semantic-layer.js +98 -0
  284. package/scripts/seo-gsd.js +1153 -0
  285. package/scripts/settings-hierarchy.js +214 -0
  286. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  287. package/scripts/skill-exporter.js +262 -0
  288. package/scripts/skill-generator.js +446 -0
  289. package/scripts/skill-materializer.js +134 -0
  290. package/scripts/skill-packs.js +136 -0
  291. package/scripts/skill-proposer.js +99 -0
  292. package/scripts/skill-quality-tracker.js +282 -0
  293. package/scripts/slo-alert-engine.js +14 -0
  294. package/scripts/slow-loop.js +72 -0
  295. package/scripts/social-analytics/db/schema.sql +32 -0
  296. package/scripts/social-analytics/db/social-analytics.db +0 -0
  297. package/scripts/social-analytics/digest.js +256 -0
  298. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  299. package/scripts/social-analytics/instagram-thumbgate-post.js +107 -0
  300. package/scripts/social-analytics/load-env.js +46 -0
  301. package/scripts/social-analytics/mcp-server.js +289 -0
  302. package/scripts/social-analytics/normalizer.js +580 -0
  303. package/scripts/social-analytics/notify.js +162 -0
  304. package/scripts/social-analytics/poll-all.js +92 -0
  305. package/scripts/social-analytics/pollers/github.js +195 -0
  306. package/scripts/social-analytics/pollers/instagram.js +253 -0
  307. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  308. package/scripts/social-analytics/pollers/plausible.js +247 -0
  309. package/scripts/social-analytics/pollers/reddit.js +306 -0
  310. package/scripts/social-analytics/pollers/threads.js +233 -0
  311. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  312. package/scripts/social-analytics/pollers/x.js +227 -0
  313. package/scripts/social-analytics/pollers/youtube.js +304 -0
  314. package/scripts/social-analytics/pollers/zernio.js +183 -0
  315. package/scripts/social-analytics/publish-instagram-thumbgate.js +98 -0
  316. package/scripts/social-analytics/publish-thumbgate-launch.js +316 -0
  317. package/scripts/social-analytics/publishers/devto.js +122 -0
  318. package/scripts/social-analytics/publishers/instagram.js +317 -0
  319. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  320. package/scripts/social-analytics/publishers/reddit.js +390 -0
  321. package/scripts/social-analytics/publishers/threads.js +275 -0
  322. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  323. package/scripts/social-analytics/publishers/x.js +259 -0
  324. package/scripts/social-analytics/publishers/youtube.js +223 -0
  325. package/scripts/social-analytics/publishers/zernio.js +378 -0
  326. package/scripts/social-analytics/run-digest.js +34 -0
  327. package/scripts/social-analytics/store.js +257 -0
  328. package/scripts/social-analytics/utm.js +143 -0
  329. package/scripts/social-pipeline.js +2628 -0
  330. package/scripts/social-quality-gate.js +18 -0
  331. package/scripts/social-reply-monitor.js +445 -0
  332. package/scripts/status-dashboard.js +155 -0
  333. package/scripts/statusline-lesson.js +16 -0
  334. package/scripts/statusline-tower.js +8 -0
  335. package/scripts/statusline.sh +116 -0
  336. package/scripts/stripe-live-status.js +115 -0
  337. package/scripts/subagent-profiles.js +79 -0
  338. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  339. package/scripts/sync-github-about.js +52 -0
  340. package/scripts/sync-version.js +447 -0
  341. package/scripts/synthetic-dpo.js +234 -0
  342. package/scripts/telemetry-analytics.js +821 -0
  343. package/scripts/tessl-export.js +371 -0
  344. package/scripts/test-coverage.js +120 -0
  345. package/scripts/thompson-sampling.js +417 -0
  346. package/scripts/thumbgate-search.js +189 -0
  347. package/scripts/tool-kpi-tracker.js +12 -0
  348. package/scripts/tool-registry.js +811 -0
  349. package/scripts/train_from_feedback.py +933 -0
  350. package/scripts/user-profile.js +78 -0
  351. package/scripts/validate-feedback.js +581 -0
  352. package/scripts/validate-workflow-contract.js +287 -0
  353. package/scripts/vector-store.js +197 -0
  354. package/scripts/verification-loop.js +291 -0
  355. package/scripts/verify-obsidian-setup.sh +269 -0
  356. package/scripts/verify-run.js +269 -0
  357. package/scripts/webhook-delivery.js +62 -0
  358. package/scripts/weekly-auto-post.js +124 -0
  359. package/scripts/workflow-runs.js +154 -0
  360. package/scripts/workflow-sprint-intake.js +475 -0
  361. package/scripts/workspace-evolver.js +374 -0
  362. package/scripts/x-autonomous-marketing.js +139 -0
  363. package/scripts/xmemory-lite.js +405 -0
  364. package/skills/agent-memory/SKILL.md +97 -0
  365. package/skills/rlhf-feedback/SKILL.md +49 -0
  366. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  367. package/skills/solve-architecture-autonomy/tool.js +33 -0
  368. package/skills/thumbgate/SKILL.md +114 -0
  369. package/src/api/server.js +4206 -0
@@ -0,0 +1,933 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Thompson Sampling Feedback Model Trainer
4
+
5
+ Beta-Bernoulli Thompson Sampling for per-category reliability estimation.
6
+ Reads from feedback-log.jsonl and builds a Bayesian model of Claude's
7
+ performance across different task categories.
8
+
9
+ Usage:
10
+ python train_from_feedback.py --train # Full rebuild from JSONL
11
+ python train_from_feedback.py --incremental # Update with latest entry
12
+ python train_from_feedback.py --reliability # Print reliability table
13
+ python train_from_feedback.py --sample # Sample from posteriors
14
+ python train_from_feedback.py --snapshot # Save model snapshot
15
+ python train_from_feedback.py --dpo-train # DPO batch optimization (Feb 2026)
16
+ python train_from_feedback.py --config config.json # Use custom categories
17
+
18
+ This script only reads and writes local feedback artifacts under the active ThumbGate feedback directory.
19
+ Those runtime outputs are git-ignored even though this utility is intentionally versioned.
20
+ """
21
+
22
+ import json
23
+ import math
24
+ import random
25
+ import argparse
26
+ import os
27
+ from datetime import datetime
28
+ from pathlib import Path
29
+ from typing import Dict, List, Any, Optional, Tuple
30
+
31
+ # Configuration
32
+ PROJECT_ROOT = Path(__file__).parent.parent
33
+
34
+ def resolve_feedback_dir() -> Path:
35
+ env_dir = os.environ.get("THUMBGATE_FEEDBACK_DIR")
36
+ if env_dir:
37
+ return Path(env_dir)
38
+
39
+ local_thumbgate = PROJECT_ROOT / ".thumbgate"
40
+ if local_thumbgate.exists():
41
+ return local_thumbgate
42
+
43
+ local_rlhf = PROJECT_ROOT / ".rlhf"
44
+ if local_rlhf.exists():
45
+ return local_rlhf
46
+
47
+ local_legacy = PROJECT_ROOT / ".claude" / "memory" / "feedback"
48
+ if local_legacy.exists():
49
+ return local_legacy
50
+
51
+ return Path.home() / ".thumbgate" / "projects" / PROJECT_ROOT.name
52
+
53
+ FEEDBACK_DIR = resolve_feedback_dir()
54
+ FEEDBACK_LOG = FEEDBACK_DIR / "feedback-log.jsonl"
55
+ MODEL_FILE = FEEDBACK_DIR / "feedback_model.json"
56
+ SNAPSHOTS_DIR = FEEDBACK_DIR / "model_snapshots"
57
+
58
+ # Default categories (overridden by --config)
59
+ DEFAULT_CATEGORIES = {
60
+ "code_edit": {
61
+ "keywords": ["edit", "write", "implement", "refactor", "fix", "update", "create file"],
62
+ "tools": ["Edit", "Write", "MultiEdit"],
63
+ },
64
+ "git": {
65
+ "keywords": ["commit", "push", "branch", "merge", "pr", "pull request", "rebase", "cherry-pick"],
66
+ "tools": ["Bash"],
67
+ },
68
+ "testing": {
69
+ "keywords": ["test", "jest", "coverage", "reassure", "perf", "spec", "mock", "assert"],
70
+ "tools": [],
71
+ },
72
+ "pr_review": {
73
+ "keywords": ["review", "pr comment", "resolve", "minimize", "thread", "feedback"],
74
+ "tools": [],
75
+ },
76
+ "search": {
77
+ "keywords": ["search", "find", "grep", "glob", "explore", "where is", "look for"],
78
+ "tools": ["Grep", "Glob", "Read"],
79
+ },
80
+ "architecture": {
81
+ "keywords": ["architecture", "design", "pattern", "structure", "fsd", "module", "navigation"],
82
+ "tools": [],
83
+ },
84
+ "security": {
85
+ "keywords": ["security", "secret", "vulnerability", "injection", "xss", "owasp", "trufflehog"],
86
+ "tools": [],
87
+ },
88
+ "debugging": {
89
+ "keywords": ["debug", "error", "crash", "stack trace", "log", "diagnose", "investigate"],
90
+ "tools": [],
91
+ },
92
+ }
93
+
94
+ # Time decay configuration (2026 upgrade: exponential decay with half-life)
95
+ # Step decay (legacy)
96
+ DECAY_WEIGHTS = {
97
+ 7: 1.0, # < 7 days: full weight
98
+ 30: 0.5, # 7-30 days: half weight
99
+ None: 0.25 # > 30 days: quarter weight
100
+ }
101
+
102
+ # Exponential decay (2026 best practice)
103
+ # Half-life of 7 days: feedback loses half its weight every 7 days
104
+ HALF_LIFE_DAYS = 7.0
105
+ USE_EXPONENTIAL_DECAY = True # Toggle between step and exponential
106
+
107
+
108
+ def ensure_category(model: Dict[str, Any], category_name: str) -> None:
109
+ """Ensure a category exists with uniform Beta priors."""
110
+ categories = model.setdefault("categories", {})
111
+ if category_name in categories:
112
+ return
113
+
114
+ categories[category_name] = {
115
+ "alpha": 1.0,
116
+ "beta": 1.0,
117
+ "samples": 0,
118
+ "last_updated": None,
119
+ }
120
+
121
+
122
+ def load_config(config_path: Optional[str]) -> Dict:
123
+ """Load category configuration from file or use defaults."""
124
+ if config_path:
125
+ path = Path(config_path)
126
+ if path.exists():
127
+ return json.loads(path.read_text())
128
+ return DEFAULT_CATEGORIES
129
+
130
+
131
+ def load_model(categories: Optional[Dict[str, Any]] = None) -> Dict:
132
+ """Load existing model or create with uniform priors."""
133
+ if MODEL_FILE.exists():
134
+ try:
135
+ return json.loads(MODEL_FILE.read_text())
136
+ except json.JSONDecodeError:
137
+ pass
138
+ return create_initial_model(categories or DEFAULT_CATEGORIES)
139
+
140
+
141
+ def create_initial_model(categories: Dict) -> Dict:
142
+ """Create model with uniform Beta(1,1) priors for all categories."""
143
+ model = {
144
+ "version": 1,
145
+ "created": datetime.now().isoformat(),
146
+ "updated": datetime.now().isoformat(),
147
+ "total_entries": 0,
148
+ "categories": {},
149
+ }
150
+ for cat_name in categories:
151
+ ensure_category(model, cat_name)
152
+ return model
153
+
154
+
155
+ def save_model(model: Dict):
156
+ """Save model to disk."""
157
+ # Resolve and verify path stays within trusted local ThumbGate roots (CodeQL S2083)
158
+ resolved = MODEL_FILE.resolve()
159
+ allowed_roots = [PROJECT_ROOT.resolve(), FEEDBACK_DIR.resolve()]
160
+ if not any(str(resolved).startswith(str(root)) for root in allowed_roots):
161
+ raise ValueError(f"Model path escapes allowed ThumbGate roots: {resolved}")
162
+ resolved.parent.mkdir(parents=True, exist_ok=True)
163
+ model["updated"] = datetime.now().isoformat()
164
+ resolved.write_text(json.dumps(model, indent=2))
165
+
166
+
167
+ def time_decay_weight(timestamp_str: str) -> float:
168
+ """Compute time decay weight for a feedback entry.
169
+
170
+ 2026 Upgrade: Supports both step decay and exponential decay.
171
+ Exponential decay uses half-life formula: weight = 2^(-age/half_life)
172
+ """
173
+ try:
174
+ ts_clean = timestamp_str.replace("Z", "").split("+")[0]
175
+ entry_time = datetime.fromisoformat(ts_clean)
176
+ except (ValueError, AttributeError):
177
+ return DECAY_WEIGHTS[None]
178
+
179
+ age_days = (datetime.now() - entry_time).days
180
+
181
+ if USE_EXPONENTIAL_DECAY:
182
+ # Exponential decay: weight = 2^(-age/half_life)
183
+ # At age=0: weight=1.0, at age=half_life: weight=0.5, etc.
184
+ weight = 2 ** (-age_days / HALF_LIFE_DAYS)
185
+ return max(weight, 0.01) # Floor at 1% to prevent zero weights
186
+ else:
187
+ # Legacy step decay
188
+ for threshold, weight in sorted(DECAY_WEIGHTS.items(), key=lambda x: (x[0] is None, x[0])):
189
+ if threshold is not None and age_days < threshold:
190
+ return weight
191
+ return DECAY_WEIGHTS[None]
192
+
193
+
194
+ def classify_entry(entry: Dict, categories: Dict) -> List[str]:
195
+ """Classify a feedback entry into categories based on keywords/tools."""
196
+ matched = []
197
+
198
+ # Build searchable text from entry
199
+ context = (entry.get("context", "") or "").lower()
200
+ message = (entry.get("message", "") or "").lower()
201
+ last_action = (entry.get("last_action", "") or "").lower()
202
+ last_tool = (entry.get("last_tool", "") or "").lower()
203
+ tags = entry.get("tags", [])
204
+ if isinstance(tags, list):
205
+ tags_str = " ".join(t.lower() for t in tags)
206
+ else:
207
+ tags_str = ""
208
+
209
+ searchable = f"{context} {message} {last_action} {tags_str}"
210
+
211
+ for cat_name, cat_config in categories.items():
212
+ keywords = cat_config.get("keywords", [])
213
+ tools = cat_config.get("tools", [])
214
+
215
+ # Check keyword match
216
+ keyword_match = any(kw.lower() in searchable for kw in keywords)
217
+
218
+ # Check tool match
219
+ tool_match = any(t.lower() in last_tool for t in tools) if tools else False
220
+
221
+ if keyword_match or tool_match:
222
+ matched.append(cat_name)
223
+
224
+ return matched if matched else ["uncategorized"]
225
+
226
+
227
+ def load_feedback_entries() -> List[Dict]:
228
+ """Load all feedback entries from JSONL."""
229
+ if not FEEDBACK_LOG.exists():
230
+ return []
231
+
232
+ entries = []
233
+ with open(FEEDBACK_LOG) as f:
234
+ for line in f:
235
+ line = line.strip()
236
+ if not line:
237
+ continue
238
+ try:
239
+ entries.append(json.loads(line))
240
+ except json.JSONDecodeError:
241
+ continue
242
+ return entries
243
+
244
+
245
+ def is_positive(entry: Dict) -> bool:
246
+ """Determine if a feedback entry is positive."""
247
+ if entry.get("reward", 0) > 0:
248
+ return True
249
+ # rlhf uses signal field: 'positive' or 'negative'
250
+ signal = entry.get("signal", "").lower()
251
+ if signal in ("positive", "up", "thumbsup"):
252
+ return True
253
+ feedback = entry.get("feedback", "").lower()
254
+ return feedback in ("positive", "up", "thumbsup")
255
+
256
+
257
+ def train_full(categories: Dict) -> Dict:
258
+ """Full rebuild: read all entries, compute posteriors."""
259
+ entries = load_feedback_entries()
260
+ model = create_initial_model(categories)
261
+ model["total_entries"] = len(entries)
262
+
263
+ # Ensure uncategorized exists
264
+ ensure_category(model, "uncategorized")
265
+
266
+ for entry in entries:
267
+ weight = time_decay_weight(entry.get("timestamp", ""))
268
+ cats = classify_entry(entry, categories)
269
+ positive = is_positive(entry)
270
+
271
+ for cat in cats:
272
+ ensure_category(model, cat)
273
+
274
+ if positive:
275
+ model["categories"][cat]["alpha"] += weight
276
+ else:
277
+ model["categories"][cat]["beta"] += weight
278
+
279
+ model["categories"][cat]["samples"] += 1
280
+ model["categories"][cat]["last_updated"] = entry.get("timestamp")
281
+
282
+ save_model(model)
283
+ return model
284
+
285
+
286
+ def train_incremental(categories: Dict) -> Dict:
287
+ """Incremental update: process only the latest entry."""
288
+ entries = load_feedback_entries()
289
+ if not entries:
290
+ return load_model(categories)
291
+
292
+ model = load_model(categories)
293
+
294
+ # Ensure all categories exist
295
+ for cat_name in categories:
296
+ ensure_category(model, cat_name)
297
+ ensure_category(model, "uncategorized")
298
+
299
+ latest = entries[-1]
300
+ weight = time_decay_weight(latest.get("timestamp", ""))
301
+ cats = classify_entry(latest, categories)
302
+ positive = is_positive(latest)
303
+
304
+ for cat in cats:
305
+ ensure_category(model, cat)
306
+
307
+ if positive:
308
+ model["categories"][cat]["alpha"] += weight
309
+ else:
310
+ model["categories"][cat]["beta"] += weight
311
+
312
+ model["categories"][cat]["samples"] += 1
313
+ model["categories"][cat]["last_updated"] = latest.get("timestamp")
314
+
315
+ model["total_entries"] = len(entries)
316
+ save_model(model)
317
+ return model
318
+
319
+
320
+ def compute_reliability(model: Dict) -> List[Tuple[str, float, float, float, int, float]]:
321
+ """Compute reliability (posterior mean) for each category."""
322
+ results = []
323
+ for cat_name, params in model.get("categories", {}).items():
324
+ alpha = params["alpha"]
325
+ beta_val = params["beta"]
326
+ samples = params["samples"]
327
+
328
+ # Posterior mean of Beta distribution: alpha / (alpha + beta)
329
+ reliability = alpha / (alpha + beta_val) if (alpha + beta_val) > 0 else 0.5
330
+
331
+ # 95% credible interval width (approximate)
332
+ # For Beta(a,b): variance = ab / ((a+b)^2 * (a+b+1))
333
+ total = alpha + beta_val
334
+ if total > 0 and (total + 1) > 0:
335
+ variance = (alpha * beta_val) / (total * total * (total + 1))
336
+ ci_width = 2 * 1.96 * math.sqrt(variance)
337
+ else:
338
+ ci_width = 1.0
339
+
340
+ results.append((cat_name, alpha, beta_val, reliability, samples, ci_width))
341
+
342
+ return sorted(results, key=lambda x: -x[3])
343
+
344
+
345
+ def sample_posteriors(model: Dict) -> Dict[str, float]:
346
+ """Thompson Sampling: draw from each category's posterior."""
347
+ samples = {}
348
+ for cat_name, params in model.get("categories", {}).items():
349
+ alpha = max(params["alpha"], 0.01)
350
+ beta_val = max(params["beta"], 0.01)
351
+ samples[cat_name] = random.betavariate(alpha, beta_val)
352
+ return samples
353
+
354
+
355
+ def save_snapshot(model: Dict) -> Path:
356
+ """Save a timestamped snapshot for lift comparison."""
357
+ SNAPSHOTS_DIR.mkdir(parents=True, exist_ok=True)
358
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
359
+ snapshot_file = SNAPSHOTS_DIR / f"model_{timestamp}.json"
360
+ snapshot_file.write_text(json.dumps(model, indent=2))
361
+ return snapshot_file
362
+
363
+
364
+ # ============================================
365
+ # META-POLICY RULES (2026 Best Practice)
366
+ # Consolidate repeated mistakes into reusable rules
367
+ # Based on: Meta-Policy Reflexion (arXiv:2509.03990)
368
+ # ============================================
369
+
370
+ META_POLICY_FILE = FEEDBACK_DIR / "meta_policy_rules.json"
371
+
372
+
373
+ def extract_meta_policy_rules(min_occurrences: int = 3) -> List[Dict[str, Any]]:
374
+ """Extract reusable rules from repeated negative feedback patterns.
375
+
376
+ Feb 2026 Upgrade: Recency + intensity weighted confidence.
377
+ - Recent mistakes weigh more than old ones (exponential decay)
378
+ - High-intensity feedback (user frustration) boosts confidence faster
379
+ - Rules include trend analysis (improving vs deteriorating)
380
+
381
+ Args:
382
+ min_occurrences: Minimum times a pattern must appear to become a rule
383
+
384
+ Returns:
385
+ List of meta-policy rules with condition, action, weighted confidence
386
+ """
387
+ entries = load_feedback_entries()
388
+ negative_entries = [e for e in entries if not is_positive(e)]
389
+
390
+ if len(negative_entries) < min_occurrences:
391
+ return []
392
+
393
+ # Group by category
394
+ category_patterns: Dict[str, List[Dict]] = {}
395
+ for entry in negative_entries:
396
+ cats = classify_entry(entry, DEFAULT_CATEGORIES)
397
+ for cat in cats:
398
+ if cat not in category_patterns:
399
+ category_patterns[cat] = []
400
+ category_patterns[cat].append(entry)
401
+
402
+ # Also count positive entries per category for trend analysis
403
+ positive_entries = [e for e in entries if is_positive(e)]
404
+ category_positives: Dict[str, int] = {}
405
+ for entry in positive_entries:
406
+ cats = classify_entry(entry, DEFAULT_CATEGORIES)
407
+ for cat in cats:
408
+ category_positives[cat] = category_positives.get(cat, 0) + 1
409
+
410
+ rules = []
411
+ for category, patterns in category_patterns.items():
412
+ if len(patterns) >= min_occurrences:
413
+ # Feb 2026: Recency + intensity weighted confidence
414
+ weighted_sum = 0.0
415
+ total_weight = 0.0
416
+ recent_count = 0 # Last 7 days
417
+ recent_positive = 0
418
+
419
+ for e in patterns:
420
+ recency = time_decay_weight(e.get("timestamp", ""))
421
+ intensity = e.get("intensity", 3) / 5.0 # Normalize to 0-1
422
+ weight = recency * (0.5 + 0.5 * intensity) # Blend recency + intensity
423
+ weighted_sum += weight
424
+ total_weight += 1.0
425
+
426
+ # Track recent entries
427
+ try:
428
+ ts = e.get("timestamp", "").replace("Z", "").split("+")[0]
429
+ entry_time = datetime.fromisoformat(ts)
430
+ if (datetime.now() - entry_time).days <= 7:
431
+ recent_count += 1
432
+ except (ValueError, AttributeError):
433
+ pass
434
+
435
+ # Count recent positives for trend
436
+ for e in positive_entries:
437
+ cats = classify_entry(e, DEFAULT_CATEGORIES)
438
+ if category in cats:
439
+ try:
440
+ ts = e.get("timestamp", "").replace("Z", "").split("+")[0]
441
+ entry_time = datetime.fromisoformat(ts)
442
+ if (datetime.now() - entry_time).days <= 7:
443
+ recent_positive += 1
444
+ except (ValueError, AttributeError):
445
+ pass
446
+
447
+ # Weighted confidence: base + recency-weighted adjustment
448
+ avg_weighted = weighted_sum / total_weight if total_weight > 0 else 0
449
+ confidence = min(0.95, 0.4 + (avg_weighted * 0.3) + (len(patterns) * 0.05))
450
+
451
+ # Trend: improving or deteriorating
452
+ total_positives = category_positives.get(category, 0)
453
+ pos_ratio = total_positives / (total_positives + len(patterns)) if (total_positives + len(patterns)) > 0 else 0
454
+ if recent_count == 0 and recent_positive > 0:
455
+ trend = "improving"
456
+ elif recent_count > 2 and recent_positive == 0:
457
+ trend = "deteriorating"
458
+ elif recent_count > recent_positive:
459
+ trend = "needs_attention"
460
+ else:
461
+ trend = "stable"
462
+
463
+ rule = {
464
+ "id": f"rule_{category}_{len(patterns)}",
465
+ "category": category,
466
+ "occurrences": len(patterns),
467
+ "confidence": round(confidence, 3),
468
+ "weighted_confidence": round(avg_weighted, 4),
469
+ "trend": trend,
470
+ "recent_negatives_7d": recent_count,
471
+ "recent_positives_7d": recent_positive,
472
+ "positive_ratio": round(pos_ratio, 3),
473
+ "created": datetime.now().isoformat(),
474
+ "condition": f"When working on {category} tasks",
475
+ "action": f"Pay extra attention - {len(patterns)} past mistakes in this area",
476
+ "examples": [
477
+ e.get("context", e.get("message", ""))[:100]
478
+ for e in sorted(patterns, key=lambda x: x.get("timestamp", ""), reverse=True)[:3]
479
+ ],
480
+ }
481
+
482
+ # Category-specific rules
483
+ if category == "git":
484
+ rule["action"] = "VERIFY git operations before executing - check branch, status, diff"
485
+ elif category == "code_edit":
486
+ rule["action"] = "READ the file first, understand context before editing"
487
+ elif category == "testing":
488
+ rule["action"] = "Run tests after changes, don't assume they pass"
489
+ elif category == "pr_review":
490
+ rule["action"] = "Address ALL review comments, don't just minimize"
491
+ elif category == "debugging":
492
+ rule["action"] = "Verify the fix actually works - don't claim success without evidence"
493
+
494
+ rules.append(rule)
495
+
496
+ # Sort by confidence descending (most urgent first)
497
+ rules.sort(key=lambda r: r["confidence"], reverse=True)
498
+ return rules
499
+
500
+
501
+ def save_meta_policy_rules(rules: List[Dict[str, Any]]):
502
+ """Save extracted rules to disk."""
503
+ META_POLICY_FILE.parent.mkdir(parents=True, exist_ok=True)
504
+ with open(META_POLICY_FILE, "w") as f:
505
+ json.dump({
506
+ "updated": datetime.now().isoformat(),
507
+ "rule_count": len(rules),
508
+ "rules": rules,
509
+ }, f, indent=2)
510
+
511
+
512
+ def load_meta_policy_rules() -> List[Dict[str, Any]]:
513
+ """Load existing meta-policy rules."""
514
+ if not META_POLICY_FILE.exists():
515
+ return []
516
+ try:
517
+ with open(META_POLICY_FILE) as f:
518
+ data = json.load(f)
519
+ return data.get("rules", [])
520
+ except (json.JSONDecodeError, KeyError):
521
+ return []
522
+
523
+
524
+ # ============================================
525
+ # DPO-STYLE BATCH OPTIMIZATION (Feb 2026)
526
+ # Direct Preference Optimization without explicit reward model.
527
+ # Builds preference pairs from positive/negative feedback,
528
+ # then adjusts category priors more aggressively than
529
+ # simple counting — mimicking DPO's closed-form update.
530
+ #
531
+ # Reference: Rafailov et al. 2023 (arXiv:2305.18290)
532
+ # ============================================
533
+
534
+ DPO_MODEL_FILE = FEEDBACK_DIR / "dpo_model.json"
535
+ DPO_BETA = 0.1 # Temperature parameter (lower = more aggressive preference following)
536
+
537
+
538
+ def _override_dpo_beta(value: float):
539
+ """Override DPO_BETA at module level."""
540
+ global DPO_BETA
541
+ DPO_BETA = value
542
+
543
+
544
+ def build_preference_pairs(categories: Dict) -> Dict[str, List[Tuple[Dict, Dict]]]:
545
+ """Build (chosen, rejected) preference pairs per category.
546
+
547
+ For each category, pair the most recent positive entry with the most
548
+ recent negative entry. This creates implicit preference data without
549
+ needing explicit A/B comparisons.
550
+ """
551
+ entries = load_feedback_entries()
552
+ if not entries:
553
+ return {}
554
+
555
+ # Classify entries by category and sentiment
556
+ cat_positives: Dict[str, List[Dict]] = {}
557
+ cat_negatives: Dict[str, List[Dict]] = {}
558
+
559
+ for entry in entries:
560
+ cats = classify_entry(entry, categories)
561
+ for cat in cats:
562
+ if is_positive(entry):
563
+ cat_positives.setdefault(cat, []).append(entry)
564
+ else:
565
+ cat_negatives.setdefault(cat, []).append(entry)
566
+
567
+ # Build pairs: each positive paired with closest-in-time negative
568
+ pairs: Dict[str, List[Tuple[Dict, Dict]]] = {}
569
+ all_cats = set(list(cat_positives.keys()) + list(cat_negatives.keys()))
570
+
571
+ for cat in all_cats:
572
+ pos = cat_positives.get(cat, [])
573
+ neg = cat_negatives.get(cat, [])
574
+ if not pos or not neg:
575
+ continue
576
+
577
+ cat_pairs = []
578
+ # Sort by timestamp
579
+ pos_sorted = sorted(pos, key=lambda e: e.get("timestamp", ""))
580
+ neg_sorted = sorted(neg, key=lambda e: e.get("timestamp", ""))
581
+
582
+ # Pair each positive with the nearest negative (greedy matching)
583
+ used_neg = set()
584
+ for p in pos_sorted:
585
+ best_neg = None
586
+ best_dist = float("inf")
587
+ for i, n in enumerate(neg_sorted):
588
+ if i in used_neg:
589
+ continue
590
+ try:
591
+ p_ts = datetime.fromisoformat(p.get("timestamp", "").replace("Z", "").split("+")[0])
592
+ n_ts = datetime.fromisoformat(n.get("timestamp", "").replace("Z", "").split("+")[0])
593
+ dist = abs((p_ts - n_ts).total_seconds())
594
+ except (ValueError, AttributeError):
595
+ dist = float("inf")
596
+ if dist < best_dist:
597
+ best_dist = dist
598
+ best_neg = i
599
+ if best_neg is not None:
600
+ used_neg.add(best_neg)
601
+ cat_pairs.append((p, neg_sorted[best_neg]))
602
+
603
+ if cat_pairs:
604
+ pairs[cat] = cat_pairs
605
+
606
+ return pairs
607
+
608
+
609
+ def dpo_log_ratio(chosen_weight: float, rejected_weight: float, beta: float = DPO_BETA) -> float:
610
+ """Compute DPO implicit reward difference.
611
+
612
+ DPO loss: -log(sigmoid(beta * (log pi(chosen) - log pi(rejected))))
613
+ We use time-decay weights as proxy for log-probabilities.
614
+
615
+ Returns adjustment to apply to category alpha/beta parameters.
616
+ """
617
+ # Avoid log(0)
618
+ chosen_weight = max(chosen_weight, 0.01)
619
+ rejected_weight = max(rejected_weight, 0.01)
620
+
621
+ log_ratio = math.log(chosen_weight) - math.log(rejected_weight)
622
+ sigmoid = 1.0 / (1.0 + math.exp(-beta * log_ratio))
623
+
624
+ # Scale adjustment: larger preference gap → larger update
625
+ adjustment = (sigmoid - 0.5) * 2 # Range: -1 to 1
626
+ return adjustment
627
+
628
+
629
+ def train_dpo(categories: Dict) -> Dict:
630
+ """DPO-style batch optimization (Feb 2026 upgrade).
631
+
632
+ Instead of simple counting, uses preference pairs to compute
633
+ direct policy updates. Works alongside Thompson Sampling:
634
+ - Thompson Sampling: online exploration (per-feedback updates)
635
+ - DPO: batch exploitation (accumulated preference pairs)
636
+
637
+ The DPO adjustment is applied on top of the Thompson model.
638
+ """
639
+ pairs = build_preference_pairs(categories)
640
+ if not pairs:
641
+ print("No preference pairs found. Need both positive and negative feedback per category.")
642
+ return load_model(categories)
643
+
644
+ model = load_model(categories)
645
+
646
+ dpo_adjustments = {}
647
+
648
+ for cat, cat_pairs in pairs.items():
649
+ if cat not in model["categories"]:
650
+ continue
651
+
652
+ total_adjustment = 0.0
653
+ for chosen, rejected in cat_pairs:
654
+ chosen_weight = time_decay_weight(chosen.get("timestamp", ""))
655
+ rejected_weight = time_decay_weight(rejected.get("timestamp", ""))
656
+
657
+ # Compute DPO-style adjustment
658
+ adj = dpo_log_ratio(chosen_weight, rejected_weight)
659
+ total_adjustment += adj
660
+
661
+ # Average adjustment over all pairs
662
+ avg_adjustment = total_adjustment / len(cat_pairs) if cat_pairs else 0
663
+
664
+ # Apply DPO adjustment to model parameters
665
+ # Positive adjustment → boost alpha (more reliable)
666
+ # Negative adjustment → boost beta (less reliable)
667
+ if avg_adjustment > 0:
668
+ boost = avg_adjustment * len(cat_pairs) * 0.5 # Scale by pair count
669
+ model["categories"][cat]["alpha"] += boost
670
+ else:
671
+ penalty = abs(avg_adjustment) * len(cat_pairs) * 0.5
672
+ model["categories"][cat]["beta"] += penalty
673
+
674
+ dpo_adjustments[cat] = {
675
+ "pairs": len(cat_pairs),
676
+ "avg_adjustment": round(avg_adjustment, 4),
677
+ "direction": "boost" if avg_adjustment > 0 else "penalize",
678
+ }
679
+
680
+ # Save DPO metadata
681
+ dpo_meta = {
682
+ "updated": datetime.now().isoformat(),
683
+ "beta": DPO_BETA,
684
+ "total_pairs": sum(len(p) for p in pairs.values()),
685
+ "categories": dpo_adjustments,
686
+ }
687
+ DPO_MODEL_FILE.parent.mkdir(parents=True, exist_ok=True)
688
+ with open(DPO_MODEL_FILE, "w") as f:
689
+ json.dump(dpo_meta, f, indent=2)
690
+
691
+ save_model(model)
692
+ return model
693
+
694
+
695
+ def print_dpo_results(model: Dict):
696
+ """Print DPO training results."""
697
+ if not DPO_MODEL_FILE.exists():
698
+ print("\nNo DPO model found. Run --dpo-train first.")
699
+ return
700
+
701
+ with open(DPO_MODEL_FILE) as f:
702
+ dpo_meta = json.load(f)
703
+
704
+ print()
705
+ print("=" * 60)
706
+ print("DPO BATCH OPTIMIZATION RESULTS (Feb 2026)")
707
+ print("=" * 60)
708
+ print(f" Beta (temperature): {dpo_meta.get('beta', DPO_BETA)}")
709
+ print(f" Total preference pairs: {dpo_meta.get('total_pairs', 0)}")
710
+ print(f" Updated: {dpo_meta.get('updated', 'never')}")
711
+ print()
712
+
713
+ for cat, adj in sorted(
714
+ dpo_meta.get("categories", {}).items(),
715
+ key=lambda x: abs(x[1].get("avg_adjustment", 0)),
716
+ reverse=True,
717
+ ):
718
+ direction = adj.get("direction", "none")
719
+ arrow = "+" if direction == "boost" else "-"
720
+ bar_val = abs(adj.get("avg_adjustment", 0)) * 10
721
+ bar = "#" * min(10, int(bar_val)) + "-" * max(0, 10 - int(bar_val))
722
+ print(f" {cat:<20s} [{bar}] {arrow}{abs(adj.get('avg_adjustment', 0)):.4f} ({adj.get('pairs', 0)} pairs)")
723
+
724
+ print()
725
+ print(" DPO adjusts Thompson Sampling priors based on preference pairs.")
726
+ print(" Run --reliability to see combined effect.")
727
+ print("=" * 60)
728
+
729
+
730
+ def print_meta_policy_rules():
731
+ """Print meta-policy rules for session context."""
732
+ rules = load_meta_policy_rules()
733
+
734
+ print()
735
+ print("=" * 60)
736
+ print("META-POLICY RULES (Recency + Intensity Weighted)")
737
+ print("=" * 60)
738
+
739
+ if not rules:
740
+ print("\n No rules extracted yet. Need more feedback data.")
741
+ print(" Run --extract-rules after accumulating feedback.")
742
+ else:
743
+ for rule in rules:
744
+ conf_bar = "#" * int(rule["confidence"] * 10)
745
+ trend = rule.get("trend", "unknown")
746
+ trend_icon = {"improving": "+", "deteriorating": "!", "needs_attention": "?", "stable": "="}
747
+ trend_char = trend_icon.get(trend, "?")
748
+ print(f"\n [{rule['category'].upper()}] Confidence: [{conf_bar}] {rule['confidence']:.0%} (trend: {trend_char} {trend})")
749
+ print(f" Condition: {rule['condition']}")
750
+ print(f" Action: {rule['action']}")
751
+ print(f" Based on: {rule['occurrences']} negatives | Positive ratio: {rule.get('positive_ratio', 0):.0%}")
752
+ recent_neg = rule.get("recent_negatives_7d", 0)
753
+ recent_pos = rule.get("recent_positives_7d", 0)
754
+ if recent_neg or recent_pos:
755
+ print(f" Last 7d: {recent_neg} neg / {recent_pos} pos")
756
+
757
+ print("\n" + "=" * 60)
758
+
759
+
760
+ def print_reliability_table(model: Dict):
761
+ """Print formatted reliability table."""
762
+ results = compute_reliability(model)
763
+
764
+ print()
765
+ print("=" * 78)
766
+ print("THOMPSON SAMPLING RELIABILITY TABLE")
767
+ print("=" * 78)
768
+ print()
769
+ print(f" Model updated: {model.get('updated', 'never')}")
770
+ print(f" Total entries: {model.get('total_entries', 0)}")
771
+ print()
772
+ print(f" {'Category':<20s} | {'Alpha':>7s} | {'Beta':>7s} | {'Reliability':>12s} | {'Samples':>7s} | {'CI Width':>8s}")
773
+ print(" " + "-" * 74)
774
+
775
+ for cat, alpha, beta_val, reliability, samples, ci_width in results:
776
+ # Visual bar
777
+ bar_len = int(reliability * 10)
778
+ bar = "#" * bar_len + "-" * (10 - bar_len)
779
+
780
+ print(f" {cat:<20s} | {alpha:>7.1f} | {beta_val:>7.1f} | [{bar}] {reliability:>4.0%} | {samples:>7d} | {ci_width:>7.3f}")
781
+
782
+ print()
783
+ print("=" * 78)
784
+
785
+ # Summary
786
+ if results:
787
+ best = results[0]
788
+ worst = results[-1]
789
+ print(f" Best: {best[0]} ({best[3]:.0%})")
790
+ print(f" Worst: {worst[0]} ({worst[3]:.0%})")
791
+ print()
792
+
793
+ # Categories needing attention (reliability < 50% with 3+ samples)
794
+ weak = [r for r in results if r[3] < 0.5 and r[4] >= 3]
795
+ if weak:
796
+ print(" Categories needing improvement:")
797
+ for cat, _, _, rel, samp, _ in weak:
798
+ print(f" - {cat}: {rel:.0%} ({samp} samples)")
799
+ print()
800
+
801
+ print("=" * 78)
802
+
803
+
804
+ def print_samples(model: Dict):
805
+ """Print Thompson-sampled probabilities."""
806
+ samples = sample_posteriors(model)
807
+
808
+ print()
809
+ print("=" * 50)
810
+ print("THOMPSON SAMPLING (Single Draw)")
811
+ print("=" * 50)
812
+ print()
813
+
814
+ for cat, prob in sorted(samples.items(), key=lambda x: -x[1]):
815
+ bar = "#" * int(prob * 20) + "-" * (20 - int(prob * 20))
816
+ print(f" {cat:<20s} [{bar}] {prob:.3f}")
817
+
818
+ print()
819
+ print(" (Each run produces different samples - this is expected)")
820
+ print("=" * 50)
821
+
822
+
823
+ def main():
824
+ parser = argparse.ArgumentParser(description="Thompson Sampling Feedback Model Trainer (2026)")
825
+ parser.add_argument("--train", action="store_true", help="Full rebuild from JSONL")
826
+ parser.add_argument("--incremental", action="store_true", help="Update with latest entry")
827
+ parser.add_argument("--reliability", action="store_true", help="Print reliability table")
828
+ parser.add_argument("--sample", action="store_true", help="Sample from posteriors")
829
+ parser.add_argument("--snapshot", action="store_true", help="Save model snapshot")
830
+ parser.add_argument("--extract-rules", action="store_true", help="Extract meta-policy rules (2026)")
831
+ parser.add_argument("--show-rules", action="store_true", help="Show meta-policy rules")
832
+ parser.add_argument("--dpo-train", action="store_true", help="DPO batch optimization (Feb 2026)")
833
+ parser.add_argument("--dpo-beta", type=float, default=DPO_BETA, help="DPO temperature parameter")
834
+ parser.add_argument("--config", type=str, help="Path to custom categories JSON")
835
+ parser.add_argument("--json", action="store_true", help="Output as JSON (for hook consumption)")
836
+
837
+ args = parser.parse_args()
838
+
839
+ categories = load_config(args.config)
840
+
841
+ if args.train:
842
+ model = train_full(categories)
843
+ # Auto-run DPO batch optimization on full train (Feb 2026: autonomous)
844
+ dpo_model = train_dpo(categories)
845
+ # Auto-extract meta-policy rules with recency+intensity weighting
846
+ rules = extract_meta_policy_rules()
847
+ save_meta_policy_rules(rules)
848
+ if args.json:
849
+ print(json.dumps({"status": "trained", "entries": model["total_entries"], "dpo": True, "rules": len(rules)}))
850
+ else:
851
+ print(f"Trained model from {model['total_entries']} entries.")
852
+ print(f"DPO batch optimization applied. Meta-policy rules: {len(rules)}.")
853
+ print(f"Saved to: {MODEL_FILE}")
854
+ print_reliability_table(dpo_model)
855
+
856
+ elif args.incremental:
857
+ model = train_incremental(categories)
858
+ if args.json:
859
+ print(json.dumps({"status": "updated", "entries": model["total_entries"]}))
860
+ else:
861
+ print(f"Incremental update complete. Total entries: {model['total_entries']}")
862
+
863
+ elif args.reliability:
864
+ model = load_model(categories)
865
+ if args.json:
866
+ results = compute_reliability(model)
867
+ output = {
868
+ "updated": model.get("updated"),
869
+ "total_entries": model.get("total_entries", 0),
870
+ "categories": {
871
+ cat: {"alpha": a, "beta": b, "reliability": r, "samples": s, "ci_width": ci}
872
+ for cat, a, b, r, s, ci in results
873
+ },
874
+ }
875
+ print(json.dumps(output, indent=2))
876
+ else:
877
+ print_reliability_table(model)
878
+
879
+ elif args.sample:
880
+ model = load_model(categories)
881
+ if args.json:
882
+ samples = sample_posteriors(model)
883
+ print(json.dumps(samples, indent=2))
884
+ else:
885
+ print_samples(model)
886
+
887
+ elif args.snapshot:
888
+ model = load_model(categories)
889
+ snapshot_file = save_snapshot(model)
890
+ if args.json:
891
+ print(json.dumps({"snapshot": str(snapshot_file)}))
892
+ else:
893
+ print(f"Snapshot saved: {snapshot_file}")
894
+
895
+ elif args.extract_rules:
896
+ rules = extract_meta_policy_rules()
897
+ save_meta_policy_rules(rules)
898
+ if args.json:
899
+ print(json.dumps({"status": "extracted", "rule_count": len(rules), "rules": rules}))
900
+ else:
901
+ print(f"Extracted {len(rules)} meta-policy rules.")
902
+ print(f"Saved to: {META_POLICY_FILE}")
903
+ print_meta_policy_rules()
904
+
905
+ elif args.show_rules:
906
+ if args.json:
907
+ rules = load_meta_policy_rules()
908
+ print(json.dumps({"rules": rules}, indent=2))
909
+ else:
910
+ print_meta_policy_rules()
911
+
912
+ elif args.dpo_train:
913
+ # Override DPO_BETA via module-level reassignment
914
+ _override_dpo_beta(args.dpo_beta)
915
+ model = train_dpo(categories)
916
+ if args.json:
917
+ dpo_meta = {}
918
+ if DPO_MODEL_FILE.exists():
919
+ with open(DPO_MODEL_FILE) as f:
920
+ dpo_meta = json.load(f)
921
+ print(json.dumps({"status": "dpo_trained", **dpo_meta}))
922
+ else:
923
+ print(f"DPO batch optimization complete.")
924
+ print(f"Saved to: {DPO_MODEL_FILE}")
925
+ print_dpo_results(model)
926
+ print_reliability_table(model)
927
+
928
+ else:
929
+ parser.print_help()
930
+
931
+
932
+ if __name__ == "__main__":
933
+ main()