thumbgate 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (369) hide show
  1. package/.claude-plugin/README.md +134 -0
  2. package/.claude-plugin/bundle/icon.png +0 -0
  3. package/.claude-plugin/bundle/icon.svg +18 -0
  4. package/.claude-plugin/bundle/server/index.js +24 -0
  5. package/.claude-plugin/marketplace.json +36 -0
  6. package/.claude-plugin/plugin.json +21 -0
  7. package/.well-known/mcp/server-card.json +231 -0
  8. package/LICENSE +21 -0
  9. package/README.md +375 -0
  10. package/adapters/README.md +9 -0
  11. package/adapters/amp/skills/rlhf-feedback/SKILL.md +22 -0
  12. package/adapters/chatgpt/INSTALL.md +83 -0
  13. package/adapters/chatgpt/openapi.yaml +1281 -0
  14. package/adapters/claude/.mcp.json +14 -0
  15. package/adapters/codex/config.toml +9 -0
  16. package/adapters/gemini/function-declarations.json +224 -0
  17. package/adapters/mcp/server-stdio.js +788 -0
  18. package/adapters/opencode/opencode.json +15 -0
  19. package/bin/cli.js +1483 -0
  20. package/bin/memory.sh +64 -0
  21. package/bin/obsidian-sync.sh +20 -0
  22. package/bin/postinstall.js +37 -0
  23. package/config/build-metadata.json +4 -0
  24. package/config/e2e-critical-flows.json +45 -0
  25. package/config/gate-templates.json +77 -0
  26. package/config/gates/claim-verification.json +29 -0
  27. package/config/gates/computer-use.json +39 -0
  28. package/config/gates/default.json +117 -0
  29. package/config/github-about.json +25 -0
  30. package/config/mcp-allowlists.json +135 -0
  31. package/config/model-tiers.json +33 -0
  32. package/config/partner-routing.json +132 -0
  33. package/config/policy-bundles/constrained-v1.json +64 -0
  34. package/config/policy-bundles/default-v1.json +91 -0
  35. package/config/rubrics/default-v1.json +52 -0
  36. package/config/skill-packs/react-testing.json +23 -0
  37. package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
  38. package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
  39. package/config/skill-specs/pr-reviewer.json +9 -0
  40. package/config/skill-specs/release-status.json +9 -0
  41. package/config/skill-specs/ticket-triage.json +9 -0
  42. package/config/subagent-profiles.json +32 -0
  43. package/config/tessl-tiles.json +29 -0
  44. package/config/thumbgate-settings.managed.json +12 -0
  45. package/openapi/openapi.yaml +1281 -0
  46. package/package.json +286 -0
  47. package/plugins/amp-skill/INSTALL.md +52 -0
  48. package/plugins/amp-skill/SKILL.md +64 -0
  49. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
  50. package/plugins/claude-codex-bridge/.mcp.json +12 -0
  51. package/plugins/claude-codex-bridge/INSTALL.md +43 -0
  52. package/plugins/claude-codex-bridge/README.md +46 -0
  53. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
  54. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
  55. package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
  56. package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
  57. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
  58. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
  59. package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
  60. package/plugins/claude-skill/INSTALL.md +55 -0
  61. package/plugins/claude-skill/SKILL.md +46 -0
  62. package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
  63. package/plugins/codex-profile/.mcp.json +12 -0
  64. package/plugins/codex-profile/AGENTS.md +20 -0
  65. package/plugins/codex-profile/INSTALL.md +66 -0
  66. package/plugins/codex-profile/README.md +37 -0
  67. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
  68. package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
  69. package/plugins/cursor-marketplace/LICENSE +21 -0
  70. package/plugins/cursor-marketplace/README.md +124 -0
  71. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
  72. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  73. package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
  74. package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
  75. package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
  76. package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
  77. package/plugins/cursor-marketplace/mcp.json +12 -0
  78. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
  79. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
  80. package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
  81. package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
  82. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
  83. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
  84. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
  85. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
  86. package/plugins/gemini-extension/INSTALL.md +92 -0
  87. package/plugins/gemini-extension/gemini_prompt.txt +14 -0
  88. package/plugins/gemini-extension/tool_contract.json +45 -0
  89. package/plugins/opencode-profile/INSTALL.md +57 -0
  90. package/public/assets/instagram-card.png +0 -0
  91. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  92. package/public/blog.html +400 -0
  93. package/public/dashboard.html +1093 -0
  94. package/public/guide.html +317 -0
  95. package/public/index.html +1195 -0
  96. package/public/learn/agent-harness-pattern.html +180 -0
  97. package/public/learn/ai-agent-persistent-memory.html +202 -0
  98. package/public/learn/learn.css +45 -0
  99. package/public/learn/mcp-pre-action-gates-explained.html +172 -0
  100. package/public/learn/stop-ai-agent-force-push.html +134 -0
  101. package/public/learn/vibe-coding-safety-net.html +142 -0
  102. package/public/learn.html +213 -0
  103. package/public/lessons.html +650 -0
  104. package/public/vercel.json +8 -0
  105. package/scripts/__pycache__/train_from_feedback.cpython-314.pyc +0 -0
  106. package/scripts/a2ui-engine.js +73 -0
  107. package/scripts/access-anomaly-detector.js +12 -0
  108. package/scripts/adk-consolidator.js +266 -0
  109. package/scripts/agent-readiness.js +220 -0
  110. package/scripts/agent-security-hardening.js +227 -0
  111. package/scripts/agentic-data-pipeline.js +847 -0
  112. package/scripts/analytics-report.js +328 -0
  113. package/scripts/analytics-window.js +158 -0
  114. package/scripts/async-job-runner.js +1001 -0
  115. package/scripts/audit-trail.js +398 -0
  116. package/scripts/auto-promote-gates.js +293 -0
  117. package/scripts/auto-wire-hooks.js +316 -0
  118. package/scripts/autonomous-sales-agent.js +39 -0
  119. package/scripts/autoresearch-runner.js +216 -0
  120. package/scripts/background-agent-governance.js +237 -0
  121. package/scripts/behavioral-extraction.js +93 -0
  122. package/scripts/belief-update.js +84 -0
  123. package/scripts/billing.js +2438 -0
  124. package/scripts/bot-detector.js +50 -0
  125. package/scripts/budget-guard.js +173 -0
  126. package/scripts/build-claude-mcpb.js +189 -0
  127. package/scripts/build-metadata.js +97 -0
  128. package/scripts/check-congruence.js +322 -0
  129. package/scripts/cli-feedback.js +135 -0
  130. package/scripts/cli-telemetry.js +87 -0
  131. package/scripts/cloudflare-dynamic-sandbox.js +315 -0
  132. package/scripts/code-reasoning.js +350 -0
  133. package/scripts/codegraph-context.js +466 -0
  134. package/scripts/commercial-offer.js +56 -0
  135. package/scripts/computer-use-firewall.js +250 -0
  136. package/scripts/context-engine.js +694 -0
  137. package/scripts/contextfs.js +1287 -0
  138. package/scripts/conversation-context.js +119 -0
  139. package/scripts/creator-campaigns.js +239 -0
  140. package/scripts/daemon-manager.js +108 -0
  141. package/scripts/daily-digest.js +11 -0
  142. package/scripts/dashboard-render-spec.js +395 -0
  143. package/scripts/dashboard.js +1058 -0
  144. package/scripts/data-governance.js +173 -0
  145. package/scripts/delegation-runtime.js +900 -0
  146. package/scripts/deploy-gcp.sh +44 -0
  147. package/scripts/deploy-policy.js +231 -0
  148. package/scripts/disagreement-mining.js +315 -0
  149. package/scripts/dispatch-brief.js +159 -0
  150. package/scripts/distribution-surfaces.js +44 -0
  151. package/scripts/dpo-optimizer.js +206 -0
  152. package/scripts/ensure-repo-bootstrap.js +129 -0
  153. package/scripts/ephemeral-agent-store.js +219 -0
  154. package/scripts/eval-harness.js +56 -0
  155. package/scripts/evolution-state.js +241 -0
  156. package/scripts/experiment-tracker.js +267 -0
  157. package/scripts/export-databricks-bundle.js +242 -0
  158. package/scripts/export-dpo-pairs.js +344 -0
  159. package/scripts/export-kto-pairs.js +309 -0
  160. package/scripts/export-training.js +450 -0
  161. package/scripts/failure-diagnostics.js +558 -0
  162. package/scripts/feedback-attribution.js +313 -0
  163. package/scripts/feedback-fallback.js +110 -0
  164. package/scripts/feedback-history-distiller.js +391 -0
  165. package/scripts/feedback-inbox-read.js +162 -0
  166. package/scripts/feedback-loop.js +1887 -0
  167. package/scripts/feedback-paths.js +145 -0
  168. package/scripts/feedback-quality.js +139 -0
  169. package/scripts/feedback-root-consolidator.js +238 -0
  170. package/scripts/feedback-schema.js +426 -0
  171. package/scripts/feedback-session.js +286 -0
  172. package/scripts/feedback-to-memory.js +185 -0
  173. package/scripts/feedback-to-rules.js +164 -0
  174. package/scripts/filesystem-search.js +405 -0
  175. package/scripts/funnel-analytics.js +35 -0
  176. package/scripts/gate-satisfy.js +42 -0
  177. package/scripts/gate-stats.js +116 -0
  178. package/scripts/gate-templates.js +70 -0
  179. package/scripts/gates-engine.js +816 -0
  180. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  181. package/scripts/generate-pretool-hook.sh +40 -0
  182. package/scripts/github-about.js +350 -0
  183. package/scripts/github-outreach.js +65 -0
  184. package/scripts/gtm-revenue-loop.js +520 -0
  185. package/scripts/hallucination-detector.js +226 -0
  186. package/scripts/hf-papers.js +317 -0
  187. package/scripts/history-distiller.js +200 -0
  188. package/scripts/hook-auto-capture.sh +100 -0
  189. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  190. package/scripts/hook-stop-self-score.sh +51 -0
  191. package/scripts/hook-stop-verify-deploy.sh +31 -0
  192. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  193. package/scripts/hook-verify-before-done.sh +20 -0
  194. package/scripts/hosted-config.js +156 -0
  195. package/scripts/hybrid-feedback-context.js +675 -0
  196. package/scripts/install-mcp.js +159 -0
  197. package/scripts/intent-router.js +392 -0
  198. package/scripts/internal-agent-bootstrap.js +490 -0
  199. package/scripts/jsonl-watcher.js +155 -0
  200. package/scripts/lesson-db.js +613 -0
  201. package/scripts/lesson-inference.js +310 -0
  202. package/scripts/lesson-retrieval.js +95 -0
  203. package/scripts/lesson-rotation.js +137 -0
  204. package/scripts/lesson-search.js +644 -0
  205. package/scripts/lesson-synthesis.js +196 -0
  206. package/scripts/license.js +50 -0
  207. package/scripts/local-model-profile.js +384 -0
  208. package/scripts/markdown-escape.js +12 -0
  209. package/scripts/marketing-experiment.js +671 -0
  210. package/scripts/mcp-config.js +149 -0
  211. package/scripts/mcp-policy.js +99 -0
  212. package/scripts/memalign-recall.js +111 -0
  213. package/scripts/memory-firewall.js +222 -0
  214. package/scripts/memory-migration.js +296 -0
  215. package/scripts/meta-policy.js +190 -0
  216. package/scripts/metered-billing.js +16 -0
  217. package/scripts/model-tier-router.js +301 -0
  218. package/scripts/money-watcher.js +71 -0
  219. package/scripts/multi-hop-recall.js +240 -0
  220. package/scripts/natural-language-harness.js +330 -0
  221. package/scripts/obsidian-export.js +713 -0
  222. package/scripts/operational-dashboard.js +103 -0
  223. package/scripts/operational-summary.js +93 -0
  224. package/scripts/optimize-context.js +17 -0
  225. package/scripts/org-dashboard.js +201 -0
  226. package/scripts/partner-orchestration.js +146 -0
  227. package/scripts/per-step-scoring.js +165 -0
  228. package/scripts/perplexity-marketing.js +466 -0
  229. package/scripts/pii-scanner.js +153 -0
  230. package/scripts/plan-gate.js +154 -0
  231. package/scripts/post-everywhere.js +308 -0
  232. package/scripts/post-to-x-retry.sh +22 -0
  233. package/scripts/post-to-x.js +369 -0
  234. package/scripts/pr-manager.js +236 -0
  235. package/scripts/predictive-insights.js +356 -0
  236. package/scripts/principle-extractor.js +162 -0
  237. package/scripts/pro-features.js +40 -0
  238. package/scripts/pro-local-dashboard.js +174 -0
  239. package/scripts/problem-detail.js +53 -0
  240. package/scripts/product-feedback.js +134 -0
  241. package/scripts/profile-router.js +245 -0
  242. package/scripts/prompt-dlp.js +221 -0
  243. package/scripts/prompt-guard.js +83 -0
  244. package/scripts/prove-adapters.js +863 -0
  245. package/scripts/prove-attribution.js +365 -0
  246. package/scripts/prove-automation.js +653 -0
  247. package/scripts/prove-autoresearch.js +304 -0
  248. package/scripts/prove-claim-verification.js +277 -0
  249. package/scripts/prove-cloudflare-sandbox.js +163 -0
  250. package/scripts/prove-data-pipeline.js +410 -0
  251. package/scripts/prove-data-quality.js +227 -0
  252. package/scripts/prove-evolution.js +352 -0
  253. package/scripts/prove-harnesses.js +287 -0
  254. package/scripts/prove-intelligence.js +259 -0
  255. package/scripts/prove-lancedb.js +371 -0
  256. package/scripts/prove-local-intelligence.js +342 -0
  257. package/scripts/prove-loop-closure.js +263 -0
  258. package/scripts/prove-predictive-insights.js +357 -0
  259. package/scripts/prove-runtime.js +350 -0
  260. package/scripts/prove-seo-gsd.js +234 -0
  261. package/scripts/prove-settings.js +279 -0
  262. package/scripts/prove-subway-upgrades.js +277 -0
  263. package/scripts/prove-tessl.js +229 -0
  264. package/scripts/prove-training-export.js +327 -0
  265. package/scripts/prove-workflow-contract.js +116 -0
  266. package/scripts/prove-xmemory.js +332 -0
  267. package/scripts/publish-decision.js +133 -0
  268. package/scripts/pulse.js +80 -0
  269. package/scripts/rate-limiter.js +125 -0
  270. package/scripts/reddit-dm-outreach.js +182 -0
  271. package/scripts/reddit-monitor-cron.sh +26 -0
  272. package/scripts/reflector-agent.js +221 -0
  273. package/scripts/reminder-engine.js +132 -0
  274. package/scripts/revenue-status.js +472 -0
  275. package/scripts/risk-scorer.js +459 -0
  276. package/scripts/rlaif-self-audit.js +129 -0
  277. package/scripts/rlhf_session_start.sh +32 -0
  278. package/scripts/rubric-engine.js +230 -0
  279. package/scripts/schedule-manager.js +251 -0
  280. package/scripts/secret-scanner.js +414 -0
  281. package/scripts/self-heal.js +147 -0
  282. package/scripts/self-healing-check.js +188 -0
  283. package/scripts/semantic-layer.js +98 -0
  284. package/scripts/seo-gsd.js +1153 -0
  285. package/scripts/settings-hierarchy.js +214 -0
  286. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  287. package/scripts/skill-exporter.js +262 -0
  288. package/scripts/skill-generator.js +446 -0
  289. package/scripts/skill-materializer.js +134 -0
  290. package/scripts/skill-packs.js +136 -0
  291. package/scripts/skill-proposer.js +99 -0
  292. package/scripts/skill-quality-tracker.js +282 -0
  293. package/scripts/slo-alert-engine.js +14 -0
  294. package/scripts/slow-loop.js +72 -0
  295. package/scripts/social-analytics/db/schema.sql +32 -0
  296. package/scripts/social-analytics/db/social-analytics.db +0 -0
  297. package/scripts/social-analytics/digest.js +256 -0
  298. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  299. package/scripts/social-analytics/instagram-thumbgate-post.js +107 -0
  300. package/scripts/social-analytics/load-env.js +46 -0
  301. package/scripts/social-analytics/mcp-server.js +289 -0
  302. package/scripts/social-analytics/normalizer.js +580 -0
  303. package/scripts/social-analytics/notify.js +162 -0
  304. package/scripts/social-analytics/poll-all.js +92 -0
  305. package/scripts/social-analytics/pollers/github.js +195 -0
  306. package/scripts/social-analytics/pollers/instagram.js +253 -0
  307. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  308. package/scripts/social-analytics/pollers/plausible.js +247 -0
  309. package/scripts/social-analytics/pollers/reddit.js +306 -0
  310. package/scripts/social-analytics/pollers/threads.js +233 -0
  311. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  312. package/scripts/social-analytics/pollers/x.js +227 -0
  313. package/scripts/social-analytics/pollers/youtube.js +304 -0
  314. package/scripts/social-analytics/pollers/zernio.js +183 -0
  315. package/scripts/social-analytics/publish-instagram-thumbgate.js +98 -0
  316. package/scripts/social-analytics/publish-thumbgate-launch.js +316 -0
  317. package/scripts/social-analytics/publishers/devto.js +122 -0
  318. package/scripts/social-analytics/publishers/instagram.js +317 -0
  319. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  320. package/scripts/social-analytics/publishers/reddit.js +390 -0
  321. package/scripts/social-analytics/publishers/threads.js +275 -0
  322. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  323. package/scripts/social-analytics/publishers/x.js +259 -0
  324. package/scripts/social-analytics/publishers/youtube.js +223 -0
  325. package/scripts/social-analytics/publishers/zernio.js +378 -0
  326. package/scripts/social-analytics/run-digest.js +34 -0
  327. package/scripts/social-analytics/store.js +257 -0
  328. package/scripts/social-analytics/utm.js +143 -0
  329. package/scripts/social-pipeline.js +2628 -0
  330. package/scripts/social-quality-gate.js +18 -0
  331. package/scripts/social-reply-monitor.js +445 -0
  332. package/scripts/status-dashboard.js +155 -0
  333. package/scripts/statusline-lesson.js +16 -0
  334. package/scripts/statusline-tower.js +8 -0
  335. package/scripts/statusline.sh +116 -0
  336. package/scripts/stripe-live-status.js +115 -0
  337. package/scripts/subagent-profiles.js +79 -0
  338. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  339. package/scripts/sync-github-about.js +52 -0
  340. package/scripts/sync-version.js +447 -0
  341. package/scripts/synthetic-dpo.js +234 -0
  342. package/scripts/telemetry-analytics.js +821 -0
  343. package/scripts/tessl-export.js +371 -0
  344. package/scripts/test-coverage.js +120 -0
  345. package/scripts/thompson-sampling.js +417 -0
  346. package/scripts/thumbgate-search.js +189 -0
  347. package/scripts/tool-kpi-tracker.js +12 -0
  348. package/scripts/tool-registry.js +811 -0
  349. package/scripts/train_from_feedback.py +933 -0
  350. package/scripts/user-profile.js +78 -0
  351. package/scripts/validate-feedback.js +581 -0
  352. package/scripts/validate-workflow-contract.js +287 -0
  353. package/scripts/vector-store.js +197 -0
  354. package/scripts/verification-loop.js +291 -0
  355. package/scripts/verify-obsidian-setup.sh +269 -0
  356. package/scripts/verify-run.js +269 -0
  357. package/scripts/webhook-delivery.js +62 -0
  358. package/scripts/weekly-auto-post.js +124 -0
  359. package/scripts/workflow-runs.js +154 -0
  360. package/scripts/workflow-sprint-intake.js +475 -0
  361. package/scripts/workspace-evolver.js +374 -0
  362. package/scripts/x-autonomous-marketing.js +139 -0
  363. package/scripts/xmemory-lite.js +405 -0
  364. package/skills/agent-memory/SKILL.md +97 -0
  365. package/skills/rlhf-feedback/SKILL.md +49 -0
  366. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  367. package/skills/solve-architecture-autonomy/tool.js +33 -0
  368. package/skills/thumbgate/SKILL.md +114 -0
  369. package/src/api/server.js +4206 -0
@@ -0,0 +1,313 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { resolveFeedbackDir } = require('./feedback-paths');
7
+
8
+ const FEEDBACK_DIR = resolveFeedbackDir();
9
+ const PATHS = {
10
+ actionLog: path.join(FEEDBACK_DIR, 'action-log.jsonl'),
11
+ attributions: path.join(FEEDBACK_DIR, 'feedback-attributions.jsonl'),
12
+ attributedFeedback: path.join(FEEDBACK_DIR, 'attributed-feedback.jsonl'),
13
+ };
14
+
15
+ const STOPWORDS = new Set([
16
+ 'about', 'after', 'again', 'allow', 'already', 'always', 'because', 'before', 'being', 'between',
17
+ 'could', 'does', 'done', 'each', 'ensure', 'every', 'from', 'have', 'into', 'just', 'make', 'more',
18
+ 'most', 'must', 'never', 'only', 'other', 'over', 'repeat', 'same', 'should', 'since', 'that',
19
+ 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'under', 'until', 'very', 'what', 'when',
20
+ 'where', 'which', 'while', 'with', 'without', 'would', 'thumbs', 'down', 'up', 'please', 'avoid',
21
+ ]);
22
+
23
+ function readJsonl(filePath, maxLines = 500) {
24
+ if (!filePath || !fs.existsSync(filePath)) return [];
25
+ const lines = fs.readFileSync(filePath, 'utf8').split('\n');
26
+ const out = [];
27
+ for (let i = lines.length - 1; i >= 0 && out.length < maxLines; i -= 1) {
28
+ const line = lines[i].trim();
29
+ if (!line) continue;
30
+ try {
31
+ out.push(JSON.parse(line));
32
+ } catch {
33
+ // ignore malformed jsonl lines
34
+ }
35
+ }
36
+ return out.reverse();
37
+ }
38
+
39
+ function appendJsonl(filePath, obj) {
40
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
41
+ fs.appendFileSync(filePath, `${JSON.stringify(obj)}\n`);
42
+ }
43
+
44
+ function normalize(text) {
45
+ return String(text || '')
46
+ .replace(/\/Users\/[^\s/]+/g, '~')
47
+ .replace(/:[0-9]+/g, '')
48
+ .replace(/\s+/g, ' ')
49
+ .trim()
50
+ .toLowerCase();
51
+ }
52
+
53
+ function stripFeedbackPrefix(text) {
54
+ return String(text || '')
55
+ .replace(/^\s*thumbs?[ -]?down\s*[:\-]?\s*/i, '')
56
+ .replace(/^\s*thumbs?[ -]?up\s*[:\-]?\s*/i, '')
57
+ .replace(/^\s*(negative|positive)\s+feedback\s*[:\-]?\s*/i, '')
58
+ .trim();
59
+ }
60
+
61
+ function tokenize(text) {
62
+ return [...new Set(
63
+ normalize(text)
64
+ .split(/[^a-z0-9]+/)
65
+ .filter(Boolean)
66
+ .filter(w => w.length >= 3 && !STOPWORDS.has(w))
67
+ )].slice(0, 24);
68
+ }
69
+
70
+ function nowIso() {
71
+ return new Date().toISOString();
72
+ }
73
+
74
+ function hashText(text) {
75
+ let h = 2166136261;
76
+ const str = String(text || '');
77
+ for (let i = 0; i < str.length; i += 1) {
78
+ h ^= str.charCodeAt(i);
79
+ h = Math.imul(h, 16777619);
80
+ }
81
+ return (h >>> 0).toString(16).padStart(8, '0');
82
+ }
83
+
84
+ function summarizeToolInput(toolName, toolInput) {
85
+ const tool = String(toolName || 'unknown');
86
+ const input = (typeof toolInput === 'string') ? toolInput : JSON.stringify(toolInput || {});
87
+ if (tool === 'Bash') {
88
+ try {
89
+ const parsed = typeof toolInput === 'string' ? JSON.parse(toolInput) : toolInput;
90
+ if (parsed && typeof parsed.command === 'string') {
91
+ return parsed.command;
92
+ }
93
+ } catch {}
94
+ return input;
95
+ }
96
+ if (tool === 'Edit' || tool === 'Write') {
97
+ try {
98
+ const parsed = typeof toolInput === 'string' ? JSON.parse(toolInput) : toolInput;
99
+ const p = parsed?.file_path || parsed?.path || parsed?.filePath || '';
100
+ if (p) return `${tool} ${p}`;
101
+ } catch {}
102
+ }
103
+ return input;
104
+ }
105
+
106
+ function inferIntent(toolName, text) {
107
+ const t = normalize(text);
108
+ if (/git\s+push|--force|git\s+reset|git\s+checkout/.test(t)) return 'git-risk';
109
+ if (/rm\s+-rf|sudo|chmod\s+777|chown\s+-r/.test(t)) return 'destructive-shell';
110
+ if (/\.env|secret|token|credential/.test(t)) return 'sensitive-data';
111
+ if (toolName === 'Edit' || toolName === 'Write') return 'file-change';
112
+ if (toolName === 'Bash') return 'shell-command';
113
+ return 'general';
114
+ }
115
+
116
+ function riskScore(toolName, text) {
117
+ const t = normalize(text);
118
+ let score = 2;
119
+ if (toolName === 'Bash') score += 2;
120
+ if (toolName === 'Edit' || toolName === 'Write') score += 1;
121
+ if (/--force|rm\s+-rf|reset\s+--hard|chmod\s+777|sudo/.test(t)) score += 4;
122
+ if (/\.env|secret|token|credential/.test(t)) score += 3;
123
+ return Math.max(1, Math.min(10, score));
124
+ }
125
+
126
+ function overlapScore(tokensA, tokensB) {
127
+ const a = new Set(tokensA || []);
128
+ const b = new Set(tokensB || []);
129
+ if (a.size === 0 || b.size === 0) return 0;
130
+ let inter = 0;
131
+ for (const w of a) {
132
+ if (b.has(w)) inter += 1;
133
+ }
134
+ const union = a.size + b.size - inter;
135
+ return union > 0 ? inter / union : 0;
136
+ }
137
+
138
+ function scoreCandidate(action, feedbackNormalized, feedbackTokens, nowMs) {
139
+ const ts = Date.parse(action.timestamp || '') || nowMs;
140
+ const ageMs = Math.max(0, nowMs - ts);
141
+ const recency = Math.exp(-ageMs / (6 * 60 * 1000));
142
+ const actionTokens = Array.isArray(action.keywords) && action.keywords.length > 0
143
+ ? action.keywords
144
+ : tokenize(action.normalized_input || action.input || '');
145
+ const lexical = overlapScore(feedbackTokens, actionTokens);
146
+ const containment = feedbackNormalized && normalize(action.normalized_input || '').includes(feedbackNormalized) ? 1 : 0;
147
+ const risk = Number(action.risk_score || 0) / 10;
148
+ let score = 0.45 * lexical + 0.30 * recency + 0.20 * risk + 0.05 * containment;
149
+
150
+ const f = feedbackNormalized;
151
+ if (/\bgit\b|\bpush\b|\bforce\b/.test(f) && action.tool_name === 'Bash') score += 0.1;
152
+ if (/\bedit\b|\bwrite\b|\bfile\b/.test(f) && (action.tool_name === 'Edit' || action.tool_name === 'Write')) score += 0.1;
153
+
154
+ return Math.max(0, Math.min(1, score));
155
+ }
156
+
157
+ function recordAction(toolName, toolInput, opts = {}) {
158
+ const actionLogPath = opts.actionLogPath || process.env.THUMBGATE_ACTION_LOG || PATHS.actionLog;
159
+ const tool = String(toolName || 'unknown');
160
+ const inputSummary = summarizeToolInput(tool, toolInput);
161
+ const normalized = normalize(inputSummary);
162
+ const row = {
163
+ action_id: `act_${Date.now()}_${hashText(`${tool}|${normalized}`)}`,
164
+ timestamp: nowIso(),
165
+ tool_name: tool,
166
+ input: inputSummary,
167
+ normalized_input: normalized,
168
+ intent: inferIntent(tool, inputSummary),
169
+ keywords: tokenize(inputSummary),
170
+ risk_score: riskScore(tool, inputSummary),
171
+ };
172
+ appendJsonl(actionLogPath, row);
173
+ return { ok: true, action: row, actionLogPath };
174
+ }
175
+
176
+ function attributeFeedback(signal, feedbackContext, opts = {}) {
177
+ const sig = String(signal || '').toLowerCase().trim();
178
+ const actionLogPath = opts.actionLogPath || process.env.THUMBGATE_ACTION_LOG || PATHS.actionLog;
179
+ const attributionsPath = opts.attributionsPath || process.env.THUMBGATE_FEEDBACK_ATTRIBUTIONS || PATHS.attributions;
180
+ const attributedFeedbackPath = opts.attributedFeedbackPath || process.env.THUMBGATE_ATTRIBUTED_FEEDBACK || PATHS.attributedFeedback;
181
+
182
+ if (sig !== 'negative' && sig !== 'positive') {
183
+ return { ok: true, skipped: true, reason: 'signal_not_supported' };
184
+ }
185
+
186
+ const nowMs = Date.now();
187
+ const feedbackText = stripFeedbackPrefix(feedbackContext);
188
+ const feedbackNormalized = normalize(feedbackText);
189
+ const feedbackTokens = tokenize(feedbackText);
190
+ const windowMs = Number(opts.windowMs || process.env.THUMBGATE_ATTRIBUTION_WINDOW_MS || (20 * 60 * 1000));
191
+ const maxActions = Number(opts.maxActions || 80);
192
+ const topK = Number(opts.topK || 3);
193
+ const threshold = Number(opts.threshold || (sig === 'negative' ? 0.33 : 0.38));
194
+
195
+ const actions = readJsonl(actionLogPath, maxActions)
196
+ .filter(a => {
197
+ const ts = Date.parse(a.timestamp || '') || nowMs;
198
+ return (nowMs - ts) <= windowMs;
199
+ })
200
+ .reverse();
201
+
202
+ const scored = actions.map(action => {
203
+ const confidence = scoreCandidate(action, feedbackNormalized, feedbackTokens, nowMs);
204
+ return { action, confidence };
205
+ }).sort((a, b) => b.confidence - a.confidence);
206
+
207
+ const selected = scored.filter(s => s.confidence >= threshold).slice(0, topK);
208
+
209
+ const attribution = {
210
+ attribution_id: `att_${Date.now()}_${hashText(`${sig}|${feedbackNormalized}`)}`,
211
+ timestamp: nowIso(),
212
+ signal: sig,
213
+ feedback_context: feedbackContext,
214
+ feedback_normalized: feedbackNormalized,
215
+ threshold,
216
+ candidates_considered: scored.length,
217
+ attributed_actions: selected.map(s => ({
218
+ action_id: s.action.action_id,
219
+ tool_name: s.action.tool_name,
220
+ input: s.action.input,
221
+ normalized_input: s.action.normalized_input,
222
+ intent: s.action.intent,
223
+ confidence: Number(s.confidence.toFixed(4)),
224
+ risk_score: s.action.risk_score,
225
+ })),
226
+ };
227
+
228
+ appendJsonl(attributionsPath, attribution);
229
+
230
+ if (sig === 'negative') {
231
+ for (const s of selected) {
232
+ appendJsonl(attributedFeedbackPath, {
233
+ timestamp: attribution.timestamp,
234
+ signal: sig,
235
+ feedback: sig,
236
+ source: 'attributed',
237
+ source_detail: 'feedback-attribution-engine',
238
+ context: s.action.input,
239
+ tool_name: s.action.tool_name,
240
+ attributed_action_id: s.action.action_id,
241
+ attribution_id: attribution.attribution_id,
242
+ confidence: Number(s.confidence.toFixed(4)),
243
+ intent: s.action.intent,
244
+ });
245
+ }
246
+ }
247
+
248
+ return {
249
+ ok: true,
250
+ signal: sig,
251
+ attributedCount: selected.length,
252
+ topConfidence: selected.length ? Number(selected[0].confidence.toFixed(4)) : 0,
253
+ attributionId: attribution.attribution_id,
254
+ actionLogPath,
255
+ attributionsPath,
256
+ attributedFeedbackPath,
257
+ };
258
+ }
259
+
260
+ function main() {
261
+ const args = process.argv.slice(2);
262
+ const recordIdx = args.indexOf('--record-action');
263
+ const attrIdx = args.indexOf('--attribute');
264
+
265
+ if (recordIdx >= 0) {
266
+ const toolName = args[recordIdx + 1] || 'unknown';
267
+ const toolInput = args[recordIdx + 2] || '{}';
268
+ const result = recordAction(toolName, toolInput);
269
+ process.stdout.write(JSON.stringify(result, null, 2));
270
+ return;
271
+ }
272
+
273
+ if (attrIdx >= 0) {
274
+ const signal = args[attrIdx + 1] || '';
275
+ const context = args[attrIdx + 2] || '';
276
+ const result = attributeFeedback(signal, context);
277
+ process.stdout.write(JSON.stringify(result, null, 2));
278
+ return;
279
+ }
280
+
281
+ process.stdout.write(JSON.stringify({
282
+ ok: true,
283
+ usage: [
284
+ '--record-action <toolName> <toolInputJson>',
285
+ '--attribute <signal> <feedbackContext>',
286
+ ],
287
+ }, null, 2));
288
+ }
289
+
290
+ if (require.main === module) {
291
+ try {
292
+ main();
293
+ } catch (error) {
294
+ console.error(`[ATTRIBUTION WARNING] ${error.message}`);
295
+ process.exit(0);
296
+ }
297
+ }
298
+
299
+ module.exports = {
300
+ PATHS,
301
+ readJsonl,
302
+ appendJsonl,
303
+ normalize,
304
+ stripFeedbackPrefix,
305
+ tokenize,
306
+ inferIntent,
307
+ riskScore,
308
+ summarizeToolInput,
309
+ overlapScore,
310
+ scoreCandidate,
311
+ recordAction,
312
+ attributeFeedback,
313
+ };
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Feedback capture fallback — captures feedback via REST API when MCP tools are unavailable.
4
+ *
5
+ * Usage (from hooks or scripts):
6
+ * echo '{"signal":"down","context":"..."}' | node scripts/feedback-fallback.js
7
+ * node scripts/feedback-fallback.js --signal=up --context="Great work"
8
+ *
9
+ * Tries localhost Pro dashboard first, then production API.
10
+ * Returns JSON result on stdout, errors on stderr.
11
+ */
12
+ 'use strict';
13
+
14
+ const http = require('http');
15
+ const https = require('https');
16
+
17
+ const ENDPOINTS = [
18
+ { url: 'http://localhost:9876/v1/feedback/capture', key: 'tg_creator_dev_enterprise', label: 'local' },
19
+ { url: 'http://localhost:3456/v1/feedback/capture', key: 'tg_creator_dev_enterprise', label: 'local-alt' },
20
+ ];
21
+
22
+ function parseArgs() {
23
+ const args = process.argv.slice(2);
24
+ const result = {};
25
+ for (const arg of args) {
26
+ const match = arg.match(/^--(\w+)=(.+)$/);
27
+ if (match) result[match[1]] = match[2];
28
+ }
29
+ return result;
30
+ }
31
+
32
+ function postJSON(endpoint, body, timeoutMs = 5000) {
33
+ return new Promise((resolve, reject) => {
34
+ const parsed = new URL(endpoint.url);
35
+ const mod = parsed.protocol === 'https:' ? https : http;
36
+ const payload = JSON.stringify(body);
37
+ const req = mod.request({
38
+ hostname: parsed.hostname,
39
+ port: parsed.port,
40
+ path: parsed.pathname,
41
+ method: 'POST',
42
+ headers: {
43
+ 'Content-Type': 'application/json',
44
+ 'Authorization': `Bearer ${endpoint.key}`,
45
+ 'Content-Length': Buffer.byteLength(payload),
46
+ },
47
+ timeout: timeoutMs,
48
+ }, (res) => {
49
+ let data = '';
50
+ res.on('data', chunk => { data += chunk; });
51
+ res.on('end', () => {
52
+ try {
53
+ const json = JSON.parse(data);
54
+ resolve({ ...json, _endpoint: endpoint.label });
55
+ } catch {
56
+ reject(new Error(`Invalid JSON from ${endpoint.label}: ${data.slice(0, 100)}`));
57
+ }
58
+ });
59
+ });
60
+ req.on('error', reject);
61
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
62
+ req.write(payload);
63
+ req.end();
64
+ });
65
+ }
66
+
67
+ async function main() {
68
+ let body;
69
+ const cliArgs = parseArgs();
70
+
71
+ if (cliArgs.signal) {
72
+ body = {
73
+ signal: cliArgs.signal,
74
+ context: cliArgs.context || 'Captured via REST fallback',
75
+ whatWentWrong: cliArgs.whatWentWrong || undefined,
76
+ whatWorked: cliArgs.whatWorked || undefined,
77
+ tags: cliArgs.tags ? cliArgs.tags.split(',') : ['rest-fallback'],
78
+ };
79
+ } else {
80
+ // Read from stdin
81
+ const chunks = [];
82
+ for await (const chunk of process.stdin) chunks.push(chunk);
83
+ const input = Buffer.concat(chunks).toString('utf8').trim();
84
+ if (!input) {
85
+ process.stderr.write('No input. Pass --signal=up/down or pipe JSON to stdin.\n');
86
+ process.exit(1);
87
+ }
88
+ body = JSON.parse(input);
89
+ if (!body.tags) body.tags = [];
90
+ if (!body.tags.includes('rest-fallback')) body.tags.push('rest-fallback');
91
+ }
92
+
93
+ for (const endpoint of ENDPOINTS) {
94
+ try {
95
+ const result = await postJSON(endpoint, body);
96
+ process.stdout.write(JSON.stringify(result) + '\n');
97
+ return;
98
+ } catch (err) {
99
+ process.stderr.write(`[fallback] ${endpoint.label} failed: ${err.message}\n`);
100
+ }
101
+ }
102
+
103
+ process.stderr.write('[fallback] All endpoints failed. Feedback NOT captured.\n');
104
+ process.exit(1);
105
+ }
106
+
107
+ main().catch(err => {
108
+ process.stderr.write(`[fallback] ${err.message}\n`);
109
+ process.exit(1);
110
+ });