thumbgate 1.4.2 → 1.4.4

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 (279) hide show
  1. package/.claude-plugin/README.md +45 -34
  2. package/.claude-plugin/marketplace.json +3 -3
  3. package/.claude-plugin/plugin.json +3 -3
  4. package/.well-known/llms.txt +1 -1
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +26 -2
  7. package/adapters/README.md +4 -1
  8. package/adapters/claude/.mcp.json +2 -2
  9. package/adapters/codex/config.toml +2 -2
  10. package/adapters/mcp/server-stdio.js +10 -4
  11. package/adapters/opencode/opencode.json +1 -1
  12. package/bin/cli.js +246 -90
  13. package/config/mcp-allowlists.json +11 -3
  14. package/package.json +184 -21
  15. package/scripts/audit-trail.js +25 -15
  16. package/scripts/auto-wire-hooks.js +127 -0
  17. package/scripts/cli-demo.js +102 -0
  18. package/scripts/cli-schema.js +285 -0
  19. package/scripts/cli-status.js +166 -0
  20. package/scripts/cross-encoder-reranker.js +235 -0
  21. package/scripts/explore-subcommands.js +277 -0
  22. package/scripts/explore.js +569 -0
  23. package/scripts/feedback-loop.js +20 -6
  24. package/scripts/lesson-inference.js +7 -1
  25. package/scripts/lesson-reranker.js +263 -0
  26. package/scripts/lesson-retrieval.js +34 -17
  27. package/scripts/lesson-search.js +69 -0
  28. package/scripts/perplexity-client.js +210 -0
  29. package/scripts/reflector-agent.js +2 -2
  30. package/scripts/statusline-local-stats.js +3 -1
  31. package/scripts/statusline.sh +12 -11
  32. package/src/api/server.js +178 -17
  33. package/src/index.js +3 -0
  34. package/.claude-plugin/bundle/icon.png +0 -0
  35. package/.claude-plugin/bundle/icon.svg +0 -18
  36. package/.claude-plugin/bundle/server/index.js +0 -24
  37. package/adapters/chatgpt/INSTALL.md +0 -138
  38. package/bin/memory.sh +0 -64
  39. package/bin/obsidian-sync.sh +0 -20
  40. package/plugins/amp-skill/INSTALL.md +0 -52
  41. package/plugins/amp-skill/SKILL.md +0 -64
  42. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +0 -22
  43. package/plugins/claude-codex-bridge/.mcp.json +0 -14
  44. package/plugins/claude-codex-bridge/INSTALL.md +0 -43
  45. package/plugins/claude-codex-bridge/README.md +0 -46
  46. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +0 -286
  47. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +0 -24
  48. package/plugins/claude-codex-bridge/skills/result/SKILL.md +0 -22
  49. package/plugins/claude-codex-bridge/skills/review/SKILL.md +0 -28
  50. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +0 -27
  51. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +0 -21
  52. package/plugins/claude-codex-bridge/skills/status/SKILL.md +0 -19
  53. package/plugins/claude-skill/INSTALL.md +0 -55
  54. package/plugins/claude-skill/SKILL.md +0 -46
  55. package/plugins/codex-profile/.codex-plugin/plugin.json +0 -43
  56. package/plugins/codex-profile/.mcp.json +0 -14
  57. package/plugins/codex-profile/AGENTS.md +0 -20
  58. package/plugins/codex-profile/INSTALL.md +0 -89
  59. package/plugins/codex-profile/README.md +0 -61
  60. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +0 -23
  61. package/plugins/cursor-marketplace/CHANGELOG.md +0 -30
  62. package/plugins/cursor-marketplace/LICENSE +0 -21
  63. package/plugins/cursor-marketplace/README.md +0 -124
  64. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +0 -31
  65. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  66. package/plugins/cursor-marketplace/commands/capture-feedback.md +0 -33
  67. package/plugins/cursor-marketplace/commands/check-gates.md +0 -25
  68. package/plugins/cursor-marketplace/commands/show-lessons.md +0 -27
  69. package/plugins/cursor-marketplace/hooks/hooks.json +0 -10
  70. package/plugins/cursor-marketplace/mcp.json +0 -14
  71. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +0 -34
  72. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +0 -30
  73. package/plugins/cursor-marketplace/rules/session-continuity.mdc +0 -28
  74. package/plugins/cursor-marketplace/scripts/gate-check.sh +0 -21
  75. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +0 -48
  76. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +0 -31
  77. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +0 -30
  78. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +0 -33
  79. package/plugins/gemini-extension/INSTALL.md +0 -92
  80. package/plugins/gemini-extension/gemini_prompt.txt +0 -14
  81. package/plugins/gemini-extension/tool_contract.json +0 -45
  82. package/plugins/opencode-profile/INSTALL.md +0 -57
  83. package/public/assets/instagram-card.png +0 -0
  84. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  85. package/public/blog.html +0 -474
  86. package/public/compare/mem0.html +0 -189
  87. package/public/compare/speclock.html +0 -180
  88. package/public/compare.html +0 -310
  89. package/public/dashboard.html +0 -1100
  90. package/public/guide.html +0 -317
  91. package/public/guides/claude-code-prevent-repeated-mistakes.html +0 -161
  92. package/public/guides/codex-cli-guardrails.html +0 -158
  93. package/public/guides/cursor-prevent-repeated-mistakes.html +0 -161
  94. package/public/guides/pre-action-gates.html +0 -162
  95. package/public/guides/stop-repeated-ai-agent-mistakes.html +0 -159
  96. package/public/index.html +0 -1128
  97. package/public/js/buyer-intent.js +0 -252
  98. package/public/learn/agent-harness-pattern.html +0 -180
  99. package/public/learn/ai-agent-persistent-memory.html +0 -203
  100. package/public/learn/learn.css +0 -45
  101. package/public/learn/mcp-pre-action-gates-explained.html +0 -172
  102. package/public/learn/stop-ai-agent-force-push.html +0 -134
  103. package/public/learn/vibe-coding-safety-net.html +0 -142
  104. package/public/learn.html +0 -274
  105. package/public/lessons.html +0 -967
  106. package/public/llm-context.md +0 -140
  107. package/public/pro.html +0 -1087
  108. package/public/vercel.json +0 -8
  109. package/scripts/a2ui-engine.js +0 -73
  110. package/scripts/adk-consolidator.js +0 -274
  111. package/scripts/agent-security-hardening.js +0 -225
  112. package/scripts/ai-search-visibility.js +0 -142
  113. package/scripts/autonomous-sales-agent.js +0 -39
  114. package/scripts/autoresearch-runner.js +0 -216
  115. package/scripts/background-agent-governance.js +0 -229
  116. package/scripts/behavioral-extraction.js +0 -93
  117. package/scripts/budget-enforcer.js +0 -173
  118. package/scripts/budget-guard.js +0 -173
  119. package/scripts/build-claude-mcpb.js +0 -255
  120. package/scripts/build-codex-plugin.js +0 -152
  121. package/scripts/capture-railway-diagnostics.sh +0 -97
  122. package/scripts/changeset-check.js +0 -372
  123. package/scripts/check-congruence.js +0 -443
  124. package/scripts/computer-use-firewall.js +0 -280
  125. package/scripts/content-engine/linkedin-content-generator.js +0 -154
  126. package/scripts/content-engine/output/linkedin-memento-validation.md +0 -17
  127. package/scripts/content-engine/output/linkedin-posts-2026-04-09.md +0 -175
  128. package/scripts/content-engine/reddit-thread-finder.js +0 -154
  129. package/scripts/context-engine.js +0 -710
  130. package/scripts/daily-digest.js +0 -11
  131. package/scripts/data-governance.js +0 -173
  132. package/scripts/deploy-gcp.sh +0 -44
  133. package/scripts/deploy-policy.js +0 -249
  134. package/scripts/disagreement-mining.js +0 -315
  135. package/scripts/dpo-optimizer.js +0 -206
  136. package/scripts/ensure-repo-bootstrap.js +0 -130
  137. package/scripts/ephemeral-agent-store.js +0 -212
  138. package/scripts/eval-harness.js +0 -56
  139. package/scripts/export-kto-pairs.js +0 -309
  140. package/scripts/export-training.js +0 -446
  141. package/scripts/feedback-fallback.js +0 -111
  142. package/scripts/feedback-inbox-read.js +0 -162
  143. package/scripts/feedback-root-consolidator.js +0 -233
  144. package/scripts/feedback-to-memory.js +0 -185
  145. package/scripts/gate-satisfy.js +0 -42
  146. package/scripts/generate-paperbanana-diagrams.sh +0 -99
  147. package/scripts/generate-pretool-hook.sh +0 -40
  148. package/scripts/github-about.js +0 -430
  149. package/scripts/github-outreach.js +0 -65
  150. package/scripts/gtm-revenue-loop.js +0 -535
  151. package/scripts/hallucination-detector.js +0 -226
  152. package/scripts/hf-papers.js +0 -317
  153. package/scripts/hook-auto-capture.sh +0 -100
  154. package/scripts/hook-stop-pr-thread-check.sh +0 -68
  155. package/scripts/hook-stop-self-score.sh +0 -51
  156. package/scripts/hook-stop-verify-deploy.sh +0 -31
  157. package/scripts/hook-verify-before-done.sh +0 -20
  158. package/scripts/managed-dpo-export.js +0 -91
  159. package/scripts/markdown-escape.js +0 -12
  160. package/scripts/marketing-experiment.js +0 -657
  161. package/scripts/memalign-recall.js +0 -111
  162. package/scripts/memory-migration.js +0 -296
  163. package/scripts/meta-policy.js +0 -190
  164. package/scripts/metered-billing.js +0 -16
  165. package/scripts/model-tier-router.js +0 -310
  166. package/scripts/money-watcher.js +0 -218
  167. package/scripts/multi-hop-recall.js +0 -240
  168. package/scripts/per-step-scoring.js +0 -163
  169. package/scripts/perplexity-marketing.js +0 -466
  170. package/scripts/pii-scanner.js +0 -153
  171. package/scripts/plan-gate.js +0 -154
  172. package/scripts/post-everywhere.js +0 -341
  173. package/scripts/post-to-x-retry.sh +0 -22
  174. package/scripts/post-to-x.js +0 -369
  175. package/scripts/pr-manager.js +0 -421
  176. package/scripts/principle-extractor.js +0 -162
  177. package/scripts/pro-features.js +0 -41
  178. package/scripts/prompt-dlp.js +0 -222
  179. package/scripts/prove-adapters.js +0 -860
  180. package/scripts/prove-attribution.js +0 -361
  181. package/scripts/prove-automation.js +0 -651
  182. package/scripts/prove-autoresearch.js +0 -304
  183. package/scripts/prove-claim-verification.js +0 -277
  184. package/scripts/prove-cloudflare-sandbox.js +0 -161
  185. package/scripts/prove-data-pipeline.js +0 -408
  186. package/scripts/prove-data-quality.js +0 -227
  187. package/scripts/prove-evolution.js +0 -352
  188. package/scripts/prove-harnesses.js +0 -287
  189. package/scripts/prove-intelligence.js +0 -257
  190. package/scripts/prove-lancedb.js +0 -425
  191. package/scripts/prove-local-intelligence.js +0 -340
  192. package/scripts/prove-loop-closure.js +0 -263
  193. package/scripts/prove-packaged-runtime.js +0 -326
  194. package/scripts/prove-predictive-insights.js +0 -355
  195. package/scripts/prove-runtime.js +0 -363
  196. package/scripts/prove-seo-gsd.js +0 -234
  197. package/scripts/prove-settings.js +0 -279
  198. package/scripts/prove-subway-upgrades.js +0 -277
  199. package/scripts/prove-tessl.js +0 -229
  200. package/scripts/prove-training-export.js +0 -325
  201. package/scripts/prove-workflow-contract.js +0 -112
  202. package/scripts/prove-xmemory.js +0 -332
  203. package/scripts/publish-decision.js +0 -159
  204. package/scripts/ralph-loop.js +0 -376
  205. package/scripts/ralph-mode-ci.js +0 -331
  206. package/scripts/reddit-dm-outreach.js +0 -192
  207. package/scripts/reddit-monitor-cron.sh +0 -26
  208. package/scripts/reminder-engine.js +0 -132
  209. package/scripts/revenue-status.js +0 -472
  210. package/scripts/rotate-stripe-webhook-secret.js +0 -314
  211. package/scripts/schedule-manager.js +0 -249
  212. package/scripts/self-healing-check.js +0 -193
  213. package/scripts/shieldcortex-memory-firewall-runner.mjs +0 -53
  214. package/scripts/skill-exporter.js +0 -260
  215. package/scripts/skill-materializer.js +0 -134
  216. package/scripts/skill-packs.js +0 -136
  217. package/scripts/skill-proposer.js +0 -99
  218. package/scripts/skill-quality-tracker.js +0 -282
  219. package/scripts/slow-loop.js +0 -72
  220. package/scripts/social-analytics/db/analytics.sqlite +0 -0
  221. package/scripts/social-analytics/db/schema.sql +0 -32
  222. package/scripts/social-analytics/digest.js +0 -256
  223. package/scripts/social-analytics/engagement-audit.js +0 -185
  224. package/scripts/social-analytics/generate-instagram-card.js +0 -97
  225. package/scripts/social-analytics/instagram-thumbgate-post.js +0 -111
  226. package/scripts/social-analytics/install-growth-automation.js +0 -114
  227. package/scripts/social-analytics/load-env.js +0 -77
  228. package/scripts/social-analytics/mcp-server.js +0 -289
  229. package/scripts/social-analytics/normalizer.js +0 -580
  230. package/scripts/social-analytics/notify.js +0 -162
  231. package/scripts/social-analytics/poll-all.js +0 -107
  232. package/scripts/social-analytics/pollers/github.js +0 -195
  233. package/scripts/social-analytics/pollers/instagram.js +0 -253
  234. package/scripts/social-analytics/pollers/linkedin.js +0 -340
  235. package/scripts/social-analytics/pollers/plausible.js +0 -245
  236. package/scripts/social-analytics/pollers/reddit.js +0 -306
  237. package/scripts/social-analytics/pollers/threads.js +0 -233
  238. package/scripts/social-analytics/pollers/tiktok.js +0 -203
  239. package/scripts/social-analytics/pollers/x.js +0 -227
  240. package/scripts/social-analytics/pollers/youtube.js +0 -304
  241. package/scripts/social-analytics/pollers/zernio.js +0 -183
  242. package/scripts/social-analytics/publish-instagram-thumbgate.js +0 -104
  243. package/scripts/social-analytics/publish-thumbgate-launch.js +0 -322
  244. package/scripts/social-analytics/publishers/devto.js +0 -122
  245. package/scripts/social-analytics/publishers/instagram.js +0 -317
  246. package/scripts/social-analytics/publishers/linkedin.js +0 -294
  247. package/scripts/social-analytics/publishers/reddit.js +0 -385
  248. package/scripts/social-analytics/publishers/threads.js +0 -275
  249. package/scripts/social-analytics/publishers/tiktok.js +0 -217
  250. package/scripts/social-analytics/publishers/x.js +0 -259
  251. package/scripts/social-analytics/publishers/youtube.js +0 -223
  252. package/scripts/social-analytics/publishers/zernio.js +0 -539
  253. package/scripts/social-analytics/reconcile-thumbgate-campaign.js +0 -165
  254. package/scripts/social-analytics/run-digest.js +0 -34
  255. package/scripts/social-analytics/schedule-thumbgate-campaign.js +0 -275
  256. package/scripts/social-analytics/store.js +0 -455
  257. package/scripts/social-analytics/sync-launch-assets.js +0 -185
  258. package/scripts/social-analytics/utm.js +0 -143
  259. package/scripts/social-pipeline.js +0 -2626
  260. package/scripts/social-post-hourly.js +0 -228
  261. package/scripts/social-quality-gate.js +0 -134
  262. package/scripts/social-reply-monitor.js +0 -592
  263. package/scripts/status-dashboard.js +0 -155
  264. package/scripts/stripe-live-status.js +0 -115
  265. package/scripts/subagent-profiles.js +0 -79
  266. package/scripts/sync-branch-protection.js +0 -340
  267. package/scripts/sync-gh-secrets-from-env.sh +0 -70
  268. package/scripts/sync-github-about.js +0 -55
  269. package/scripts/sync-version.js +0 -479
  270. package/scripts/synthetic-dpo.js +0 -234
  271. package/scripts/tessl-export.js +0 -369
  272. package/scripts/test-coverage.js +0 -128
  273. package/scripts/thumbgate_session_start.sh +0 -32
  274. package/scripts/train_from_feedback.py +0 -929
  275. package/scripts/validate-feedback.js +0 -581
  276. package/scripts/verify-obsidian-setup.sh +0 -269
  277. package/scripts/verify-run.js +0 -269
  278. package/scripts/weekly-auto-post.js +0 -124
  279. package/scripts/x-autonomous-marketing.js +0 -139
@@ -0,0 +1,285 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * cli-schema.js — single source of truth for thumbgate CLI commands.
5
+ *
6
+ * Inspired by Cloudflare's schema-first CLI architecture: one definition
7
+ * drives both the CLI help text and the explore TUI command browser.
8
+ * MCP tool bindings are listed via `mcpTool` so the two surfaces stay in sync.
9
+ *
10
+ * Groups: capture | discovery | gates | export | ops | advanced
11
+ */
12
+
13
+ const CLI_COMMANDS = [
14
+ // -------------------------------------------------------------------------
15
+ // Capture
16
+ // -------------------------------------------------------------------------
17
+ {
18
+ name: 'capture',
19
+ aliases: ['feedback'],
20
+ description: 'Capture an up/down signal — turns feedback into a stored lesson',
21
+ group: 'capture',
22
+ mcpTool: 'capture_feedback',
23
+ flags: [
24
+ { name: 'feedback', type: 'string', required: true, description: 'Signal: up or down' },
25
+ { name: 'context', type: 'string', description: 'One-line reason' },
26
+ { name: 'what-went-wrong', type: 'string', description: 'Root cause (negative feedback)' },
27
+ { name: 'what-to-change', type: 'string', description: 'Specific fix required' },
28
+ { name: 'what-worked', type: 'string', description: 'What succeeded (positive feedback)' },
29
+ { name: 'tags', type: 'string', description: 'Comma-separated tags' },
30
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
31
+ ],
32
+ },
33
+
34
+ // -------------------------------------------------------------------------
35
+ // Discovery
36
+ // -------------------------------------------------------------------------
37
+ {
38
+ name: 'explore',
39
+ description: 'Interactive TUI — browse lessons, gates, stats, and rules keyboard-first',
40
+ group: 'discovery',
41
+ flags: [
42
+ { name: 'json', type: 'boolean', description: 'Output as JSON (non-interactive)' },
43
+ { name: 'limit', type: 'number', description: 'Max items (default 20)' },
44
+ ],
45
+ },
46
+ {
47
+ name: 'lessons',
48
+ aliases: ['search-lessons'],
49
+ description: 'Search promoted lessons and show linked corrective actions',
50
+ group: 'discovery',
51
+ mcpTool: 'search_lessons',
52
+ flags: [
53
+ { name: 'query', type: 'string', description: 'Search query (positional arg also works)' },
54
+ { name: 'limit', type: 'number', description: 'Max results (default 10)' },
55
+ { name: 'tags', type: 'string', description: 'Comma-separated tag filter' },
56
+ { name: 'category', type: 'string', description: 'error | learning | preference' },
57
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
58
+ { name: 'local', type: 'boolean', description: 'Use local storage (default)' },
59
+ { name: 'remote', type: 'boolean', description: 'Fetch from hosted Railway instance' },
60
+ ],
61
+ },
62
+ {
63
+ name: 'stats',
64
+ description: 'Feedback analytics — approval rate, Revenue-at-Risk, recent trend',
65
+ group: 'discovery',
66
+ mcpTool: 'feedback_stats',
67
+ flags: [
68
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
69
+ { name: 'remote', type: 'boolean', description: 'Fetch from hosted Railway instance' },
70
+ ],
71
+ },
72
+ {
73
+ name: 'gate-stats',
74
+ description: 'Gate engine statistics — active gates, blocks, warns, time saved',
75
+ group: 'discovery',
76
+ flags: [
77
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
78
+ ],
79
+ },
80
+ {
81
+ name: 'summary',
82
+ description: 'Human-readable feedback summary',
83
+ group: 'discovery',
84
+ mcpTool: 'feedback_summary',
85
+ flags: [
86
+ { name: 'recent', type: 'number', description: 'Number of recent entries (default 20)' },
87
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
88
+ ],
89
+ },
90
+ {
91
+ name: 'doctor',
92
+ description: 'Audit runtime isolation, bootstrap context, and permission tier',
93
+ group: 'discovery',
94
+ flags: [
95
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
96
+ ],
97
+ },
98
+ {
99
+ name: 'lesson-health',
100
+ aliases: ['stale'],
101
+ description: 'Report on stale lessons (>60d inactive) with optional auto-archive',
102
+ group: 'discovery',
103
+ flags: [
104
+ { name: 'archive', type: 'boolean', description: 'Auto-archive lessons >90d inactive' },
105
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
106
+ ],
107
+ },
108
+
109
+ // -------------------------------------------------------------------------
110
+ // Gates
111
+ // -------------------------------------------------------------------------
112
+ {
113
+ name: 'gate-check',
114
+ description: 'PreToolUse hook: pipe tool JSON via stdin, get ALLOW/BLOCK verdict',
115
+ group: 'gates',
116
+ flags: [],
117
+ },
118
+ {
119
+ name: 'force-gate',
120
+ description: 'Immediately create a blocking gate from a pattern string',
121
+ group: 'gates',
122
+ flags: [
123
+ { name: 'pattern', type: 'string', description: 'Pattern to block (positional)' },
124
+ ],
125
+ },
126
+ {
127
+ name: 'rules',
128
+ description: 'Generate prevention rules from repeated failure patterns',
129
+ group: 'gates',
130
+ mcpTool: 'prevention_rules',
131
+ flags: [
132
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
133
+ ],
134
+ },
135
+
136
+ // -------------------------------------------------------------------------
137
+ // Export
138
+ // -------------------------------------------------------------------------
139
+ {
140
+ name: 'export-dpo',
141
+ aliases: ['dpo'],
142
+ description: 'Export DPO training pairs (prompt/chosen/rejected JSONL)',
143
+ group: 'export',
144
+ flags: [
145
+ { name: 'output', type: 'string', description: 'Output file path' },
146
+ ],
147
+ },
148
+ {
149
+ name: 'export-databricks',
150
+ aliases: ['databricks'],
151
+ description: 'Export feedback + proof artifacts as a Databricks-ready analytics bundle',
152
+ group: 'export',
153
+ flags: [],
154
+ },
155
+ {
156
+ name: 'obsidian-export',
157
+ description: 'Export all feedback as interlinked Obsidian markdown notes',
158
+ group: 'export',
159
+ flags: [
160
+ { name: 'vault-path', type: 'string', description: 'Obsidian vault path' },
161
+ { name: 'output-dir', type: 'string', description: 'Output subdirectory (default: AI-Memories/thumbgate)' },
162
+ ],
163
+ },
164
+
165
+ // -------------------------------------------------------------------------
166
+ // Ops
167
+ // -------------------------------------------------------------------------
168
+ {
169
+ name: 'status',
170
+ description: 'Agent-friendly health check — gates, lessons, feedback, enforcement',
171
+ group: 'discovery',
172
+ flags: [
173
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
174
+ ],
175
+ },
176
+ {
177
+ name: 'demo',
178
+ description: 'Simulated walkthrough — see ThumbGate block a bad action in 10 seconds',
179
+ group: 'ops',
180
+ flags: [
181
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
182
+ ],
183
+ },
184
+ {
185
+ name: 'init',
186
+ description: 'Scaffold .thumbgate/ config and wire agent hooks',
187
+ group: 'ops',
188
+ flags: [
189
+ { name: 'agent', type: 'string', description: 'Target agent: claude-code | cursor | codex | gemini | amp' },
190
+ { name: 'wire-hooks', type: 'boolean', description: 'Wire hooks only (skip scaffold)' },
191
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
192
+ ],
193
+ },
194
+ {
195
+ name: 'serve',
196
+ description: 'Start MCP server on stdio — connect any MCP-compatible agent',
197
+ group: 'ops',
198
+ flags: [],
199
+ },
200
+ {
201
+ name: 'dashboard',
202
+ description: 'Full ThumbGate dashboard — approval rate, gate stats, prevention impact',
203
+ group: 'ops',
204
+ flags: [],
205
+ },
206
+ {
207
+ name: 'self-heal',
208
+ description: 'Run self-healing check and auto-fix known issues',
209
+ group: 'ops',
210
+ flags: [
211
+ { name: 'check', type: 'boolean', description: 'Check only, no fixes' },
212
+ ],
213
+ },
214
+ {
215
+ name: 'import-doc',
216
+ aliases: ['import-document'],
217
+ description: 'Import a local policy/runbook and propose reviewable gate candidates',
218
+ group: 'ops',
219
+ flags: [
220
+ { name: 'file', type: 'string', description: 'Path to document' },
221
+ ],
222
+ },
223
+ {
224
+ name: 'meta-agent',
225
+ description: 'Run meta-agent loop: generate, evaluate, and promote prevention rules',
226
+ group: 'advanced',
227
+ flags: [
228
+ { name: 'dry-run', type: 'boolean', description: 'Preview rules without writing' },
229
+ { name: 'status', type: 'boolean', description: 'Show last run summary' },
230
+ ],
231
+ },
232
+ {
233
+ name: 'pro',
234
+ description: `Solo dashboard + exports side lane (${'19'}/mo · ${'149'}/yr)`,
235
+ group: 'ops',
236
+ flags: [
237
+ { name: 'upgrade', type: 'boolean', description: 'Install Pro configs into .thumbgate/' },
238
+ { name: 'info', type: 'boolean', description: 'Show Pro feature list' },
239
+ ],
240
+ },
241
+ ];
242
+
243
+ /**
244
+ * Return the command definition for a given name or alias.
245
+ */
246
+ function findCommand(name) {
247
+ return CLI_COMMANDS.find(
248
+ (cmd) => cmd.name === name || (cmd.aliases || []).includes(name),
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Return commands grouped by their group field.
254
+ */
255
+ function groupedCommands() {
256
+ const groups = {};
257
+ for (const cmd of CLI_COMMANDS) {
258
+ const g = cmd.group || 'other';
259
+ if (!groups[g]) groups[g] = [];
260
+ groups[g].push(cmd);
261
+ }
262
+ return groups;
263
+ }
264
+
265
+ /**
266
+ * Generate a compact help string for a single command.
267
+ * Format: name [aliases] description [--flag ...]
268
+ */
269
+ function commandHelpLine(cmd, opts = {}) {
270
+ const { showFlags = false } = opts;
271
+ const nameCol = 22;
272
+ const nameStr = [cmd.name, ...(cmd.aliases || []).slice(0, 1)].join(' | ');
273
+ const pad = ' '.repeat(Math.max(1, nameCol - nameStr.length));
274
+ let line = ` ${nameStr}${pad}${cmd.description}`;
275
+ if (cmd.mcpTool) line += ` [mcp:${cmd.mcpTool}]`;
276
+ if (showFlags && cmd.flags.length > 0) {
277
+ const flagStr = cmd.flags
278
+ .map((f) => `--${f.name}${f.required ? ' (required)' : ''}`)
279
+ .join(' ');
280
+ line += `\n ${flagStr}`;
281
+ }
282
+ return line;
283
+ }
284
+
285
+ module.exports = { CLI_COMMANDS, findCommand, groupedCommands, commandHelpLine };
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * cli-status.js — agent-friendly health check for ThumbGate.
6
+ *
7
+ * Combines feedback stats, gate stats, lesson count, and agent detection
8
+ * into a single JSON-friendly payload.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ function detectAgent(projectDir) {
15
+ if (fs.existsSync(path.join(projectDir, '.claude'))) return 'claude-code';
16
+ if (fs.existsSync(path.join(projectDir, '.cursorrules'))) return 'cursor';
17
+ if (fs.existsSync(path.join(projectDir, '.cursor'))) return 'cursor';
18
+ if (fs.existsSync(path.join(projectDir, '.codex'))) return 'codex';
19
+ if (fs.existsSync(path.join(projectDir, '.gemini'))) return 'gemini';
20
+ if (fs.existsSync(path.join(projectDir, '.amp'))) return 'amp';
21
+ return null;
22
+ }
23
+
24
+ function generateAgentStatus(options = {}) {
25
+ const PKG_ROOT = options.pkgRoot || path.join(__dirname, '..');
26
+ const projectDir = options.projectDir || process.cwd();
27
+
28
+ // Feedback paths
29
+ const { getFeedbackPaths, readJSONL, analyzeFeedback } = require(path.join(PKG_ROOT, 'scripts', 'feedback-loop'));
30
+ const paths = getFeedbackPaths();
31
+
32
+ // Feedback entries
33
+ const feedbackEntries = readJSONL(paths.FEEDBACK_LOG_PATH);
34
+ const memoryEntries = readJSONL(paths.MEMORY_LOG_PATH);
35
+
36
+ // Gate stats
37
+ let gateData = { totalGates: 0, autoPromotedGates: 0, manualGates: 0, totalBlocked: 0 };
38
+ try {
39
+ const { calculateStats } = require(path.join(PKG_ROOT, 'scripts', 'gate-stats'));
40
+ gateData = calculateStats();
41
+ } catch { /* gate-stats not available */ }
42
+
43
+ // Prevention rules count
44
+ let preventionRuleCount = 0;
45
+ if (fs.existsSync(paths.PREVENTION_RULES_PATH)) {
46
+ const rulesContent = fs.readFileSync(paths.PREVENTION_RULES_PATH, 'utf-8');
47
+ const ruleHeaders = rulesContent.match(/^## /gm);
48
+ preventionRuleCount = ruleHeaders ? ruleHeaders.length : 0;
49
+ }
50
+
51
+ // Last feedback timestamp
52
+ const lastFeedback = feedbackEntries.length > 0
53
+ ? feedbackEntries[feedbackEntries.length - 1]
54
+ : null;
55
+ const lastFeedbackTimestamp = lastFeedback
56
+ ? (lastFeedback.timestamp || lastFeedback.createdAt || null)
57
+ : null;
58
+
59
+ // Agent detection
60
+ const agent = detectAgent(projectDir);
61
+
62
+ // Enforcement check: is there at least one blocking gate?
63
+ const hasBlockingGates = gateData.totalGates > 0;
64
+ const hasPreToolHook = (() => {
65
+ try {
66
+ const settingsPath = path.join(projectDir, '.claude', 'settings.json');
67
+ if (!fs.existsSync(settingsPath)) return false;
68
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
69
+ return Boolean(
70
+ settings.hooks &&
71
+ settings.hooks.PreToolUse &&
72
+ settings.hooks.PreToolUse.length > 0
73
+ );
74
+ } catch { return false; }
75
+ })();
76
+ const enforcementActive = hasBlockingGates || hasPreToolHook;
77
+
78
+ // Config
79
+ const configPath = path.join(projectDir, '.thumbgate', 'config.json');
80
+ let config = null;
81
+ try {
82
+ if (fs.existsSync(configPath)) {
83
+ config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
84
+ }
85
+ } catch { /* ignore */ }
86
+
87
+ // Version
88
+ let version = 'unknown';
89
+ try {
90
+ version = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8')).version;
91
+ } catch { /* ignore */ }
92
+
93
+ return {
94
+ version,
95
+ agent,
96
+ enforcementActive,
97
+ gates: {
98
+ total: gateData.totalGates,
99
+ manual: gateData.manualGates,
100
+ autoPromoted: gateData.autoPromotedGates,
101
+ blocking: gateData.blockGates || 0,
102
+ warning: gateData.warnGates || 0,
103
+ },
104
+ lessons: memoryEntries.length,
105
+ feedback: {
106
+ total: feedbackEntries.length,
107
+ positive: feedbackEntries.filter(e => e.signal === 'positive').length,
108
+ negative: feedbackEntries.filter(e => e.signal === 'negative').length,
109
+ },
110
+ preventionRules: preventionRuleCount,
111
+ lastFeedbackTimestamp,
112
+ feedbackDir: paths.FEEDBACK_DIR,
113
+ initialized: Boolean(config),
114
+ };
115
+ }
116
+
117
+ function formatStatus(data) {
118
+ const BD = '\x1b[1m';
119
+ const RST = '\x1b[0m';
120
+ const G = '\x1b[32m';
121
+ const R = '\x1b[31m';
122
+ const C = '\x1b[36m';
123
+ const Y = '\x1b[33m';
124
+ const D = '\x1b[90m';
125
+
126
+ const lines = [];
127
+ lines.push('');
128
+ lines.push(`${BD}thumbgate status${RST} v${data.version}`);
129
+ lines.push('─'.repeat(50));
130
+
131
+ // Scope badge
132
+ const scope = '[LOCAL]';
133
+ lines.push(` ${C}${scope}${RST} ${data.feedbackDir}`);
134
+ lines.push('');
135
+
136
+ // Core metrics
137
+ const enfBadge = data.enforcementActive
138
+ ? `${G}[ACTIVE]${RST}`
139
+ : `${Y}[LEARNING]${RST}`;
140
+ lines.push(` Enforcement : ${enfBadge}`);
141
+ lines.push(` Agent : ${data.agent || 'none detected'}`);
142
+ lines.push(` Gates : ${data.gates.total} (${data.gates.blocking} block, ${data.gates.warning} warn)`);
143
+ lines.push(` Lessons : ${data.lessons}`);
144
+ lines.push(` Prevention Rules: ${data.preventionRules}`);
145
+ lines.push('');
146
+ lines.push(` Feedback : ${data.feedback.total} total (${G}${data.feedback.positive} up${RST}, ${R}${data.feedback.negative} down${RST})`);
147
+ if (data.lastFeedbackTimestamp) {
148
+ const ago = relativeTime(data.lastFeedbackTimestamp);
149
+ lines.push(` Last Feedback : ${ago} ${D}(${data.lastFeedbackTimestamp})${RST}`);
150
+ } else {
151
+ lines.push(` Last Feedback : ${D}none${RST}`);
152
+ }
153
+ lines.push('');
154
+
155
+ return lines.join('\n');
156
+ }
157
+
158
+ function relativeTime(ts) {
159
+ if (!ts) return '';
160
+ const d = Math.floor((Date.now() - new Date(ts).getTime()) / 86400000);
161
+ if (d === 0) return 'today';
162
+ if (d === 1) return '1 day ago';
163
+ return `${d} days ago`;
164
+ }
165
+
166
+ module.exports = { generateAgentStatus, formatStatus };
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Cross-Encoder Reranker for ThumbGate lesson retrieval.
6
+ *
7
+ * Two-stage retrieval:
8
+ * Stage 1: Fast candidate retrieval (existing bigram Jaccard + keyword matching)
9
+ * Stage 2: Cross-encoder reranking scores query-document pairs jointly
10
+ *
11
+ * The cross-encoder evaluates the query AND each lesson together (not independently),
12
+ * catching false positives that keyword/vector search misses.
13
+ *
14
+ * Architecture reference: "Advanced RAG Retrieval: Cross-Encoders & Reranking"
15
+ * (Towards Data Science, April 2026)
16
+ *
17
+ * When LLM is available (ANTHROPIC_API_KEY), uses Claude as the cross-encoder.
18
+ * Falls back to enhanced heuristic scoring when LLM is unavailable.
19
+ */
20
+
21
+ const { retrieveRelevantLessons, scoreRelevance, buildActionSignature } = require('./lesson-retrieval');
22
+
23
+ /**
24
+ * Heuristic cross-encoder: scores a (query, document) pair jointly.
25
+ * Unlike bi-encoder (independent embeddings), this examines the pair together
26
+ * to find semantic relationships that keyword matching misses.
27
+ */
28
+ function heuristicCrossEncode(query, document) {
29
+ const queryLower = (query || '').toLowerCase();
30
+ const docLower = (document || '').toLowerCase();
31
+
32
+ let score = 0;
33
+
34
+ // 1. Exact substring containment (strongest signal)
35
+ if (queryLower.length > 3 && docLower.length > 3 &&
36
+ (docLower.includes(queryLower) || queryLower.includes(docLower))) {
37
+ score += 0.9;
38
+ return Math.min(score, 1);
39
+ }
40
+
41
+ // 2. Shared noun phrases (not just tokens — consecutive word pairs)
42
+ const queryPhrases = extractPhrases(queryLower);
43
+ const docPhrases = extractPhrases(docLower);
44
+ const phraseOverlap = queryPhrases.filter((p) => docPhrases.includes(p));
45
+ score += Math.min(phraseOverlap.length * 0.15, 0.5);
46
+
47
+ // 3. Semantic category matching
48
+ const categories = {
49
+ destructive: ['delete', 'remove', 'drop', 'destroy', 'wipe', 'truncate', 'rm -rf', 'force-push', 'reset --hard'],
50
+ git: ['git', 'push', 'pull', 'merge', 'rebase', 'branch', 'commit', 'checkout', 'stash'],
51
+ database: ['sql', 'query', 'table', 'migration', 'schema', 'database', 'insert', 'update', 'select'],
52
+ deploy: ['deploy', 'release', 'publish', 'railway', 'vercel', 'heroku', 'npm publish'],
53
+ security: ['secret', 'token', 'api key', 'password', 'credential', 'env', '.env', 'pem'],
54
+ file: ['edit', 'write', 'create', 'modify', 'config', 'package.json', 'readme'],
55
+ };
56
+
57
+ for (const [, terms] of Object.entries(categories)) {
58
+ const queryHit = terms.some((t) => queryLower.includes(t));
59
+ const docHit = terms.some((t) => docLower.includes(t));
60
+ if (queryHit && docHit) {
61
+ score += 0.25;
62
+ break; // Only count strongest category match
63
+ }
64
+ }
65
+
66
+ // 4. Action-target alignment (e.g., "git push" in query matches "push to main" in doc)
67
+ const queryVerbs = extractVerbs(queryLower);
68
+ const docVerbs = extractVerbs(docLower);
69
+ const verbOverlap = queryVerbs.filter((v) => docVerbs.includes(v));
70
+ score += Math.min(verbOverlap.length * 0.1, 0.3);
71
+
72
+ // 5. Negation alignment (both about what NOT to do)
73
+ const queryNegated = /\b(don'?t|never|avoid|block|prevent|stop)\b/.test(queryLower);
74
+ const docNegated = /\b(don'?t|never|avoid|block|prevent|stop)\b/.test(docLower);
75
+ if (queryNegated && docNegated) score += 0.1;
76
+
77
+ return Math.min(score, 1);
78
+ }
79
+
80
+ /**
81
+ * LLM cross-encoder: uses Claude to score relevance of query-document pairs.
82
+ * More accurate but requires API key and costs tokens.
83
+ */
84
+ async function llmCrossEncode(query, documents) {
85
+ const { isAvailable, callClaude, MODELS } = require('./llm-client');
86
+ if (!isAvailable()) return null;
87
+
88
+ const docList = documents
89
+ .map((d, i) => `[${i}] ${(d.title || '').slice(0, 100)} | ${(d.content || '').slice(0, 200)}`)
90
+ .join('\n');
91
+
92
+ const prompt = `You are a relevance scoring engine. Given a query and a list of documents, score each document's relevance to the query from 0.0 (irrelevant) to 1.0 (highly relevant).
93
+
94
+ Query: "${query.slice(0, 300)}"
95
+
96
+ Documents:
97
+ ${docList}
98
+
99
+ Return ONLY a JSON array of scores, one per document. Example: [0.9, 0.2, 0.7, 0.1, 0.5]
100
+ No other text.`;
101
+
102
+ try {
103
+ const raw = await callClaude({
104
+ systemPrompt: 'You are a relevance scoring engine. Return only JSON arrays of numbers.',
105
+ userPrompt: prompt,
106
+ model: MODELS.FAST,
107
+ maxTokens: 256,
108
+ });
109
+ const scores = JSON.parse(raw);
110
+ if (Array.isArray(scores) && scores.length === documents.length) {
111
+ return scores.map((s) => Math.max(0, Math.min(1, Number(s) || 0)));
112
+ }
113
+ } catch { /* fall back to heuristic */ }
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Two-stage retrieval with cross-encoder reranking.
119
+ *
120
+ * Stage 1: Retrieve top N candidates using existing keyword + bigram matching
121
+ * Stage 2: Rerank candidates using cross-encoder (LLM or heuristic)
122
+ * Return top K results by cross-encoder score
123
+ */
124
+ async function retrieveWithReranking(toolName, actionContext, options = {}) {
125
+ const {
126
+ candidateCount = 20,
127
+ maxResults = 5,
128
+ useLLM = false,
129
+ feedbackDir,
130
+ } = options;
131
+
132
+ // Stage 1: Fast candidate retrieval (existing system)
133
+ const candidates = retrieveRelevantLessons(toolName, actionContext, {
134
+ maxResults: candidateCount,
135
+ feedbackDir,
136
+ });
137
+
138
+ if (candidates.length === 0) return [];
139
+ if (candidates.length <= maxResults) return candidates;
140
+
141
+ const query = `${toolName || ''} ${actionContext || ''}`.trim();
142
+
143
+ // Stage 2: Cross-encoder reranking
144
+ let rerankedScores;
145
+
146
+ if (useLLM) {
147
+ rerankedScores = await llmCrossEncode(query, candidates);
148
+ }
149
+
150
+ // Fall back to heuristic cross-encoder if LLM unavailable or failed
151
+ if (!rerankedScores) {
152
+ rerankedScores = candidates.map((c) => {
153
+ const docText = `${c.title || ''} ${c.content || ''}`;
154
+ return heuristicCrossEncode(query, docText);
155
+ });
156
+ }
157
+
158
+ // Combine original relevance score with cross-encoder score
159
+ // Weight: 40% original, 60% cross-encoder (cross-encoder is more precise)
160
+ const reranked = candidates.map((c, i) => ({
161
+ ...c,
162
+ crossEncoderScore: rerankedScores[i],
163
+ combinedScore: c.relevanceScore * 0.4 + rerankedScores[i] * 0.6,
164
+ }));
165
+
166
+ return reranked
167
+ .sort((a, b) => b.combinedScore - a.combinedScore)
168
+ .slice(0, maxResults);
169
+ }
170
+
171
+ /**
172
+ * Synchronous version for use in PreToolUse hooks (cannot be async).
173
+ */
174
+ function retrieveWithRerankingSync(toolName, actionContext, options = {}) {
175
+ const {
176
+ candidateCount = 20,
177
+ maxResults = 5,
178
+ feedbackDir,
179
+ } = options;
180
+
181
+ const candidates = retrieveRelevantLessons(toolName, actionContext, {
182
+ maxResults: candidateCount,
183
+ feedbackDir,
184
+ });
185
+
186
+ if (candidates.length === 0) return [];
187
+ if (candidates.length <= maxResults) return candidates;
188
+
189
+ const query = `${toolName || ''} ${actionContext || ''}`.trim();
190
+
191
+ const rerankedScores = candidates.map((c) => {
192
+ const docText = `${c.title || ''} ${c.content || ''}`;
193
+ return heuristicCrossEncode(query, docText);
194
+ });
195
+
196
+ const reranked = candidates.map((c, i) => ({
197
+ ...c,
198
+ crossEncoderScore: rerankedScores[i],
199
+ combinedScore: c.relevanceScore * 0.4 + rerankedScores[i] * 0.6,
200
+ }));
201
+
202
+ return reranked
203
+ .sort((a, b) => b.combinedScore - a.combinedScore)
204
+ .slice(0, maxResults);
205
+ }
206
+
207
+ // --- Utility functions ---
208
+
209
+ function extractPhrases(text) {
210
+ const words = text.split(/\s+/).filter((w) => w.length > 2);
211
+ const phrases = [];
212
+ for (let i = 0; i < words.length - 1; i++) {
213
+ phrases.push(`${words[i]} ${words[i + 1]}`);
214
+ }
215
+ return phrases;
216
+ }
217
+
218
+ function extractVerbs(text) {
219
+ const verbPatterns = [
220
+ 'push', 'pull', 'merge', 'delete', 'create', 'edit', 'write', 'read',
221
+ 'deploy', 'install', 'remove', 'run', 'execute', 'build', 'test',
222
+ 'commit', 'rebase', 'reset', 'drop', 'truncate', 'migrate', 'publish',
223
+ 'block', 'allow', 'approve', 'deny', 'warn', 'log',
224
+ ];
225
+ return verbPatterns.filter((v) => text.includes(v));
226
+ }
227
+
228
+ module.exports = {
229
+ heuristicCrossEncode,
230
+ llmCrossEncode,
231
+ retrieveWithReranking,
232
+ retrieveWithRerankingSync,
233
+ extractPhrases,
234
+ extractVerbs,
235
+ };