thumbgate 0.9.10

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