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
@@ -1,8 +0,0 @@
1
- {
2
- "version": 2,
3
- "public": true,
4
- "name": "thumbgate",
5
- "rewrites": [
6
- { "source": "/(.*)", "destination": "/index.html" }
7
- ]
8
- }
@@ -1,73 +0,0 @@
1
- /**
2
- * A2UI (Agent-to-User Interface) Component Definitions
3
- *
4
- * Standardized schema for dynamic UI components generated by the agent.
5
- * These are intended to be rendered in the Feedback Studio or as MCP Artifacts.
6
- */
7
-
8
- 'use strict';
9
-
10
- const fs = require('fs');
11
- const path = require('path');
12
-
13
- const COMPONENT_TYPES = {
14
- REASONING_TRACE: 'reasoning-trace', // Graph/List showing how dots were connected
15
- RULE_PROPOSAL: 'rule-proposal', // Interactive card to approve/refine a rule
16
- CONFLICT_VETO: 'conflict-veto', // UI to resolve contradicting memories
17
- METRIC_DYNAMIC: 'metric-dynamic' // Real-time custom metrics based on current task
18
- };
19
-
20
- /**
21
- * Generate a Reasoning Trace component (A2UI)
22
- * @param {string} summary - High-level synthesis
23
- * @param {Array} sources - List of source logs/memories
24
- * @param {Array} connections - Semantic links found
25
- */
26
- function createReasoningTrace(summary, sources, connections) {
27
- return {
28
- type: COMPONENT_TYPES.REASONING_TRACE,
29
- version: '1.0.0',
30
- data: {
31
- summary,
32
- sources: sources.map(s => ({
33
- id: s.id,
34
- text: s.context || s.content,
35
- signal: s.signal || 'neutral'
36
- })),
37
- graph: connections.map(c => ({
38
- from: c.sourceId,
39
- to: c.targetId,
40
- label: c.relation
41
- }))
42
- },
43
- actions: [
44
- { id: 'view-logs', label: 'View Raw Logs', type: 'primary' }
45
- ]
46
- };
47
- }
48
-
49
- /**
50
- * Generate a Rule Proposal component (A2UI)
51
- */
52
- function createRuleProposal(pattern, suggestedRule, severity) {
53
- return {
54
- type: COMPONENT_TYPES.RULE_PROPOSAL,
55
- version: '1.0.0',
56
- data: {
57
- pattern,
58
- suggestedRule,
59
- severity
60
- },
61
- actions: [
62
- { id: 'approve', label: 'Approve ALWAYS/NEVER', type: 'success' },
63
- { id: 'refine', label: 'Tweak Wording', type: 'secondary' },
64
- { id: 'veto', label: 'Veto Rule', type: 'danger' }
65
- ]
66
- };
67
- }
68
-
69
- module.exports = {
70
- COMPONENT_TYPES,
71
- createReasoningTrace,
72
- createRuleProposal
73
- };
@@ -1,274 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Agent Development Kit (ADK) Memory Consolidator
4
- *
5
- * 'Always-On' background service that reads disparate feedback logs and uses
6
- * Gemini (Flash-Lite/Flash) to actively consolidate, compress, and dream up
7
- * generalized prevention rules. This moves the system from 'passive logging'
8
- * to 'active semantic memory consolidation'.
9
- */
10
-
11
- 'use strict';
12
-
13
- const fs = require('fs');
14
- const path = require('path');
15
-
16
- const PROJECT_ROOT = path.join(__dirname, '..');
17
- const { getFeedbackPaths, readJSONL } = require('./feedback-loop');
18
- const { compactContext } = require('./context-engine');
19
- const { resolveModelRole } = require('./local-model-profile');
20
- const { trackEvent, shouldInjectReminder, injectReminder } = require('./reminder-engine');
21
- const { validateApiKey } = require('./billing');
22
-
23
- // Keep track of the last processed ID to avoid re-consolidating the exact same logs
24
- const STATE_FILE = process.env.ADK_STATE_FILE || path.join(PROJECT_ROOT, '.thumbgate', 'adk-state.json');
25
-
26
-
27
- function loadState() {
28
- if (fs.existsSync(STATE_FILE)) {
29
- try {
30
- return JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'));
31
- } catch {
32
- return { lastProcessedFeedbackId: null };
33
- }
34
- }
35
- return { lastProcessedFeedbackId: null };
36
- }
37
-
38
- function saveState(state) {
39
- ensureDir(path.dirname(STATE_FILE));
40
- fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
41
- }
42
-
43
- const { createRuleProposal, createReasoningTrace } = require('./a2ui-engine');
44
- const { ensureDir } = require('./fs-utils');
45
-
46
- function buildFakeConsolidation(anchorLogs, newLogs) {
47
- const combined = [...anchorLogs, ...newLogs].filter(Boolean);
48
- const connectedLogIds = combined.slice(0, 3).map((log) => log.id).filter(Boolean);
49
- const issueHints = combined
50
- .map((log) => log.whatWentWrong || log.context || '')
51
- .map((text) => String(text).trim())
52
- .filter(Boolean);
53
-
54
- const primaryHint = issueHints[0] || 'Environment and rollout checks were skipped';
55
- return {
56
- consolidatedInsights: [
57
- {
58
- pattern: primaryHint,
59
- rule: 'ALWAYS verify environment, approvals, and rollout prerequisites before executing workflow changes',
60
- severity: 'high',
61
- connectedLogIds,
62
- },
63
- ],
64
- a2uiPayload: {
65
- reasoningGraph: {
66
- summary: 'Synthetic consolidation used for hermetic test mode.',
67
- connections: connectedLogIds.slice(1).map((id) => ({
68
- from: connectedLogIds[0],
69
- to: id,
70
- label: 'Shared failure pattern',
71
- })),
72
- },
73
- },
74
- };
75
- }
76
-
77
- async function consolidateMemory() {
78
- const requestedFakeConsolidation = process.env.ADK_FAKE_CONSOLIDATION === 'true';
79
- const useFakeConsolidation = requestedFakeConsolidation && process.env.NODE_ENV === 'test';
80
- const apiKey = process.env.GEMINI_API_KEY;
81
- if (requestedFakeConsolidation && !useFakeConsolidation) {
82
- console.warn('[ADK Consolidator] Ignoring ADK_FAKE_CONSOLIDATION outside test mode.');
83
- }
84
- if (!useFakeConsolidation && !apiKey) {
85
- console.warn('[ADK Consolidator] GEMINI_API_KEY is not set. Skipping active consolidation.');
86
- return;
87
- }
88
-
89
- let ai = null;
90
- if (!useFakeConsolidation) {
91
- let GoogleGenAI;
92
- try {
93
- ({ GoogleGenAI } = require('@google/genai'));
94
- } catch (error) {
95
- if (error && error.code === 'MODULE_NOT_FOUND') {
96
- console.warn('[ADK Consolidator] @google/genai is not installed. Skipping active consolidation.');
97
- return;
98
- }
99
- throw error;
100
- }
101
- ai = new GoogleGenAI({ apiKey });
102
- }
103
- const paths = getFeedbackPaths();
104
- const state = loadState();
105
-
106
- const allLogs = readJSONL(paths.FEEDBACK_LOG_PATH);
107
-
108
- if (allLogs.length === 0) {
109
- console.log('[ADK Consolidator] No logs to consolidate.');
110
- return;
111
- }
112
-
113
- // 1. Anchor-Memories: Always include the first 5 "foundational" logs of the session.
114
- // These act as 'attention sinks' that provide global context and numerical anchors
115
- // for the model's reasoning stability.
116
- const anchorLogs = allLogs.slice(0, 5);
117
-
118
- // 2. Incremental Window: Find where we left off
119
- const hasPriorState = Boolean(state.lastProcessedFeedbackId);
120
- let newLogs = [];
121
- if (hasPriorState) {
122
- const lastIdx = allLogs.findIndex(l => l.id === state.lastProcessedFeedbackId);
123
- if (lastIdx !== -1) {
124
- newLogs = allLogs.slice(lastIdx + 1);
125
- } else {
126
- newLogs = allLogs.slice(-50);
127
- }
128
- } else {
129
- newLogs = allLogs.slice(-50);
130
- }
131
-
132
- // Filter anchors out of newLogs if they overlap to save tokens
133
- const rawNewLogs = newLogs.filter(nl => !anchorLogs.some(al => al.id === nl.id));
134
-
135
- if (rawNewLogs.length === 0 && anchorLogs.length > 0 && hasPriorState) {
136
- console.log('[ADK Consolidator] No new logs since last consolidation cycle.');
137
- return;
138
- }
139
-
140
- // Adaptive context compaction: reduce prompt size before sending to Gemini
141
- const compactionResult = compactContext(rawNewLogs, anchorLogs, { windowSize: 30, perEntryMaxChars: 512 });
142
- const filteredNewLogs = compactionResult.entries.filter(e => !anchorLogs.some(a => a.id === e.id));
143
- if (compactionResult.compacted) {
144
- console.log(`[ADK Consolidator] Context compacted: removed ${compactionResult.removedCount} entries (stage ${compactionResult.stage}).`);
145
- }
146
-
147
- // Resolve model via role router instead of hardcoding
148
- const modelConfig = resolveModelRole('normal');
149
- const activationLabel = useFakeConsolidation ? `Gemini test stub (${modelConfig.model})` : `Gemini (${modelConfig.model})`;
150
- console.log(`[ADK Consolidator] Activating ${activationLabel} with ${anchorLogs.length} anchors and ${filteredNewLogs.length} new events...`);
151
-
152
- const prompt = `
153
- You are the Agent Development Kit (ADK) 'Always-On' Memory Consolidator.
154
- Synthesize the latest feedback into generalized prevention rules AND dynamic A2UI components.
155
-
156
- Foundational Anchors (Numerical Sinks):
157
- ${JSON.stringify(anchorLogs.map(l => ({ id: l.id, signal: l.signal, context: l.context, whatWentWrong: l.whatWentWrong })), null, 2)}
158
-
159
- Latest Feedback Events (Spikes):
160
- ${JSON.stringify(filteredNewLogs.map(l => ({ id: l.id, signal: l.signal, context: l.context, whatWentWrong: l.whatWentWrong })), null, 2)}
161
-
162
- Output ONLY valid JSON:
163
- {
164
- "consolidatedInsights": [
165
- {
166
- "pattern": "Underlying flaw",
167
- "rule": "ALWAYS/NEVER directive",
168
- "severity": "critical|high|medium|low",
169
- "connectedLogIds": ["fb_1", "fb_2"]
170
- }
171
- ],
172
- "a2uiPayload": {
173
- "reasoningGraph": {
174
- "summary": "Synthesis summary",
175
- "connections": [{"from": "fb_1", "to": "fb_2", "label": "Same environment issue"}]
176
- }
177
- }
178
- }
179
- `;
180
-
181
- try {
182
- const result = useFakeConsolidation
183
- ? buildFakeConsolidation(anchorLogs, filteredNewLogs)
184
- : JSON.parse((await ai.models.generateContent({
185
- model: modelConfig.model,
186
- contents: prompt,
187
- config: { responseMimeType: 'application/json' }
188
- })).text);
189
- console.log('[ADK Consolidator] Consolidation complete.');
190
-
191
- if (result.consolidatedInsights) {
192
- // Append to markdown (legacy fallback)
193
- appendRules(result.consolidatedInsights, paths.PREVENTION_RULES_PATH);
194
-
195
- // Track guardrail spikes and emit reminders when threshold is met
196
- const criticalInsights = result.consolidatedInsights.filter(
197
- i => i.severity === 'critical' || i.severity === 'high',
198
- );
199
- if (criticalInsights.length > 0) {
200
- trackEvent('guardrail_spike');
201
- if (shouldInjectReminder('guardrail_spike')) {
202
- const topRule = criticalInsights[0].rule;
203
- const reminderTurns = injectReminder([], 'guardrail_spike', { rule: topRule });
204
- const reminderPath = path.join(PROJECT_ROOT, '.thumbgate', `reminder_${Date.now()}.json`);
205
- fs.writeFileSync(reminderPath, JSON.stringify(reminderTurns[0], null, 2));
206
- console.log(`[ADK Consolidator] Emitted system reminder: ${reminderPath}`);
207
- }
208
- }
209
-
210
- // Emit A2UI components (New Model)
211
- result.consolidatedInsights.forEach(insight => {
212
- const proposal = createRuleProposal(insight.pattern, insight.rule, insight.severity);
213
- const a2uiPath = path.join(PROJECT_ROOT, '.thumbgate', `a2ui_proposal_${Date.now()}.json`);
214
- fs.writeFileSync(a2uiPath, JSON.stringify(proposal, null, 2));
215
- console.log(`[ADK Consolidator] Emitted A2UI Proposal: ${a2uiPath}`);
216
- });
217
- }
218
-
219
- state.lastProcessedFeedbackId = newLogs[newLogs.length - 1].id;
220
- saveState(state);
221
-
222
- // Hosted consolidation can run with a valid cloud key, but it is not metered usage billing.
223
- const cloudKey = process.env.THUMBGATE_API_KEY;
224
- if (cloudKey) {
225
- const validation = validateApiKey(cloudKey);
226
- if (validation.valid) {
227
- console.log(`[ADK Consolidator] Hosted key validated for customer: ${validation.customerId}`);
228
- }
229
- }
230
-
231
- } catch (err) {
232
- console.error('[ADK Consolidator] Consolidation failed:', err.message);
233
- }
234
- }
235
-
236
- function appendRules(insights, rulesPath) {
237
- let existingContent = '';
238
- if (fs.existsSync(rulesPath)) {
239
- existingContent = fs.readFileSync(rulesPath, 'utf-8');
240
- } else {
241
- existingContent = '# Prevention Rules\n\nGenerated from active semantic memory consolidation.\n\n';
242
- }
243
-
244
- let newRulesBlock = '\n## ADK Semantic Consolidations\n';
245
- const timestamp = new Date().toISOString();
246
- insights.forEach(insight => {
247
- newRulesBlock += `- [${insight.severity.toUpperCase()}] **${insight.pattern}**\n - Rule: ${insight.rule} *(Consolidated at ${timestamp})*\n`;
248
- });
249
-
250
- const updatedContent = existingContent + newRulesBlock;
251
- ensureDir(path.dirname(rulesPath));
252
- fs.writeFileSync(rulesPath, updatedContent);
253
- console.log(`[ADK Consolidator] Appended ${insights.length} new consolidated rules to ${rulesPath}`);
254
- }
255
-
256
- if (require.main === module) {
257
- const args = process.argv.slice(2);
258
- const isWatchMode = args.includes('--watch');
259
-
260
- if (isWatchMode) {
261
- console.log('[ADK Consolidator] Started in Always-On Watch Mode (interval: 5 minutes)');
262
- consolidateMemory(); // Run once immediately
263
- setInterval(() => {
264
- consolidateMemory();
265
- }, 5 * 60 * 1000); // Check every 5 minutes
266
- } else {
267
- consolidateMemory().then(() => {
268
- console.log('[ADK Consolidator] Cycle finished.');
269
- process.exit(0);
270
- });
271
- }
272
- }
273
-
274
- module.exports = { consolidateMemory };
@@ -1,225 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * Agent Security Hardening — credential tracking, privilege escalation detection,
6
- * dependency attestation gate.
7
- *
8
- * Closes the gaps from the agentic security video:
9
- * 1. Session-scoped credential attestation — track what creds each agent uses
10
- * 2. Privilege escalation detection — flag agents invoking tools outside their MCP profile
11
- * 3. Dependency attestation gate — block agents from installing unvetted packages
12
- */
13
-
14
- const fs = require('fs');
15
- const path = require('path');
16
- const { resolveFeedbackDir } = require('./feedback-paths');
17
- const { ensureParentDir, readJsonl } = require('./fs-utils');
18
-
19
- function getFeedbackDir() { return resolveFeedbackDir(); }
20
- const CRED_LOG = 'credential-attestations.jsonl';
21
- const ESCALATION_LOG = 'escalation-events.jsonl';
22
- const DEP_LOG = 'dependency-attestations.jsonl';
23
-
24
- function getCredLogPath() { return path.join(getFeedbackDir(), CRED_LOG); }
25
- function getEscalationLogPath() { return path.join(getFeedbackDir(), ESCALATION_LOG); }
26
- function getDepLogPath() { return path.join(getFeedbackDir(), DEP_LOG); }
27
-
28
- // ---------------------------------------------------------------------------
29
- // 1. Session-Scoped Credential Attestation
30
- // ---------------------------------------------------------------------------
31
-
32
- /**
33
- * Record what credential an agent used for a tool call.
34
- * Creates an audit trail: agent → credential → tool → timestamp.
35
- */
36
- function attestCredential({ agentId, credentialType, credentialId, toolName, scope, sessionId } = {}) {
37
- const entry = {
38
- id: `cred_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
39
- timestamp: new Date().toISOString(),
40
- agentId: agentId || 'unknown',
41
- credentialType: credentialType || 'unknown', // 'api_key', 'oauth_token', 'session_token', 'mcp_auth'
42
- credentialId: credentialId ? credentialId.slice(0, 8) + '***' : 'unknown', // truncated for safety
43
- toolName: toolName || 'unknown',
44
- scope: scope || 'default',
45
- sessionId: sessionId || null,
46
- };
47
- const logPath = getCredLogPath();
48
- ensureParentDir(logPath);
49
- fs.appendFileSync(logPath, JSON.stringify(entry) + '\n');
50
- return entry;
51
- }
52
-
53
- /**
54
- * Get credential usage summary for audit.
55
- */
56
- function getCredentialAudit({ periodHours = 24 } = {}) {
57
- const entries = readJsonl(getCredLogPath());
58
- const cutoff = Date.now() - periodHours * 60 * 60 * 1000;
59
- const recent = entries.filter((e) => new Date(e.timestamp).getTime() > cutoff);
60
-
61
- const byAgent = {};
62
- const byCredType = {};
63
- for (const e of recent) {
64
- if (!byAgent[e.agentId]) byAgent[e.agentId] = { tools: new Set(), credTypes: new Set(), count: 0 };
65
- byAgent[e.agentId].tools.add(e.toolName);
66
- byAgent[e.agentId].credTypes.add(e.credentialType);
67
- byAgent[e.agentId].count++;
68
- byCredType[e.credentialType] = (byCredType[e.credentialType] || 0) + 1;
69
- }
70
-
71
- // Serialize Sets
72
- const agents = Object.entries(byAgent).map(([id, data]) => ({
73
- agentId: id, tools: [...data.tools], credTypes: [...data.credTypes], callCount: data.count,
74
- }));
75
-
76
- return { periodHours, total: recent.length, agents, byCredType };
77
- }
78
-
79
- // ---------------------------------------------------------------------------
80
- // 2. Privilege Escalation Detection
81
- // ---------------------------------------------------------------------------
82
-
83
- // MCP profile tool allowlists (loaded from config or defaults)
84
- const PROFILE_ALLOWLISTS = {
85
- essential: new Set(['capture_feedback', 'recall', 'search_lessons', 'search_thumbgate', 'prevention_rules', 'enforcement_matrix', 'feedback_stats', 'estimate_uncertainty', 'org_dashboard', 'set_task_scope', 'get_scope_state', 'set_branch_governance', 'get_branch_governance', 'approve_protected_action', 'check_operational_integrity', 'workflow_sentinel']),
86
- readonly: new Set(['recall', 'feedback_summary', 'search_lessons', 'verify_claim', 'gate_stats', 'search_thumbgate', 'feedback_stats', 'estimate_uncertainty', 'org_dashboard', 'get_scope_state', 'get_branch_governance', 'check_operational_integrity', 'workflow_sentinel']),
87
- locked: new Set(['feedback_summary', 'search_lessons', 'diagnose_failure', 'list_intents', 'plan_intent', 'list_harnesses', 'verify_claim', 'get_scope_state', 'get_branch_governance', 'check_operational_integrity', 'workflow_sentinel']),
88
- commerce: new Set(['capture_feedback', 'recall', 'search_thumbgate', 'commerce_recall', 'track_action', 'verify_claim', 'feedback_stats', 'set_task_scope', 'get_scope_state', 'set_branch_governance', 'get_branch_governance', 'approve_protected_action', 'check_operational_integrity', 'workflow_sentinel']),
89
- };
90
-
91
- /**
92
- * Check if a tool call is within the agent's MCP profile scope.
93
- * Detects privilege escalation when agent tries to use tools outside its profile.
94
- */
95
- function detectPrivilegeEscalation({ agentId, toolName, mcpProfile } = {}) {
96
- const profile = mcpProfile || 'essential';
97
- const allowlist = PROFILE_ALLOWLISTS[profile];
98
-
99
- // If profile unknown or no allowlist, can't detect escalation
100
- if (!allowlist) return { escalation: false, reason: 'unknown profile' };
101
-
102
- const isAllowed = allowlist.has(toolName);
103
-
104
- if (!isAllowed) {
105
- const event = {
106
- id: `esc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
107
- timestamp: new Date().toISOString(),
108
- agentId: agentId || 'unknown',
109
- toolName: toolName || 'unknown',
110
- mcpProfile: profile,
111
- severity: 'warning',
112
- message: `Agent "${agentId}" attempted to use "${toolName}" which is outside "${profile}" profile scope`,
113
- };
114
- const logPath = getEscalationLogPath();
115
- ensureParentDir(logPath);
116
- fs.appendFileSync(logPath, JSON.stringify(event) + '\n');
117
- return { escalation: true, event };
118
- }
119
-
120
- return { escalation: false };
121
- }
122
-
123
- /**
124
- * Get escalation event stats.
125
- */
126
- function getEscalationStats({ periodHours = 24 } = {}) {
127
- const entries = readJsonl(getEscalationLogPath());
128
- const cutoff = Date.now() - periodHours * 60 * 60 * 1000;
129
- const recent = entries.filter((e) => new Date(e.timestamp).getTime() > cutoff);
130
-
131
- const byAgent = {};
132
- const byTool = {};
133
- for (const e of recent) {
134
- byAgent[e.agentId] = (byAgent[e.agentId] || 0) + 1;
135
- byTool[e.toolName] = (byTool[e.toolName] || 0) + 1;
136
- }
137
-
138
- return { total: recent.length, byAgent, byTool, periodHours };
139
- }
140
-
141
- // ---------------------------------------------------------------------------
142
- // 3. Dependency Attestation Gate
143
- // ---------------------------------------------------------------------------
144
-
145
- const BLOCKED_PACKAGES = new Set([
146
- 'event-stream', // known supply chain attack
147
- 'ua-parser-js', // compromised in 2021
148
- 'coa', // compromised in 2021
149
- 'rc', // compromised in 2021
150
- ]);
151
-
152
- const TRUSTED_SCOPES = new Set(['@anthropic-ai', '@types', '@babel', '@eslint']);
153
-
154
- /**
155
- * Check if a dependency install should be allowed.
156
- * Blocks known-compromised packages and unscoped packages without attestation.
157
- */
158
- function attestDependency({ packageName, version, agentId, action } = {}) {
159
- const pkg = packageName || '';
160
- const act = action || 'install'; // 'install', 'update', 'remove'
161
-
162
- const findings = [];
163
- let allowed = true;
164
-
165
- // Check blocked list
166
- if (BLOCKED_PACKAGES.has(pkg)) {
167
- findings.push({ rule: 'blocked_package', message: `"${pkg}" is a known-compromised package`, severity: 'critical' });
168
- allowed = false;
169
- }
170
-
171
- // Check for suspicious patterns
172
- if (pkg.includes('..') || pkg.includes('/') && !pkg.startsWith('@')) {
173
- findings.push({ rule: 'suspicious_path', message: `"${pkg}" has suspicious path characters`, severity: 'warning' });
174
- allowed = false;
175
- }
176
-
177
- // Check version pinning
178
- if (version && /^[>~^]/.test(version)) {
179
- findings.push({ rule: 'unpinned_version', message: `Version "${version}" is not pinned — use exact version`, severity: 'warning' });
180
- }
181
-
182
- // Trusted scope bonus
183
- const isTrustedScope = TRUSTED_SCOPES.has(pkg.split('/')[0]);
184
-
185
- const event = {
186
- id: `dep_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
187
- timestamp: new Date().toISOString(),
188
- packageName: pkg,
189
- version: version || 'latest',
190
- agentId: agentId || 'unknown',
191
- action: act,
192
- allowed,
193
- isTrustedScope,
194
- findings,
195
- };
196
-
197
- const logPath = getDepLogPath();
198
- ensureParentDir(logPath);
199
- fs.appendFileSync(logPath, JSON.stringify(event) + '\n');
200
-
201
- return { allowed, findings, isTrustedScope, event };
202
- }
203
-
204
- /**
205
- * Get dependency attestation stats.
206
- */
207
- function getDepAttestationStats({ periodHours = 24 } = {}) {
208
- const entries = readJsonl(getDepLogPath());
209
- const cutoff = Date.now() - periodHours * 60 * 60 * 1000;
210
- const recent = entries.filter((e) => new Date(e.timestamp).getTime() > cutoff);
211
-
212
- return {
213
- total: recent.length,
214
- allowed: recent.filter((e) => e.allowed).length,
215
- blocked: recent.filter((e) => !e.allowed).length,
216
- findings: recent.reduce((sum, e) => sum + (e.findings || []).length, 0),
217
- periodHours,
218
- };
219
- }
220
-
221
- module.exports = {
222
- attestCredential, getCredentialAudit, getCredLogPath,
223
- detectPrivilegeEscalation, getEscalationStats, getEscalationLogPath, PROFILE_ALLOWLISTS,
224
- attestDependency, getDepAttestationStats, getDepLogPath, BLOCKED_PACKAGES, TRUSTED_SCOPES,
225
- };