thumbgate 1.39.1 → 1.40.2

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 (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -73,8 +73,9 @@ function extractFeedbackCorrectiveAction(record) {
73
73
 
74
74
  function mapFeedbackResult(record) {
75
75
  return {
76
+ ...require('./project-identity').projectForRecord(record),
76
77
  id: record.id || null,
77
- source: 'feedback',
78
+ source: record._kind || 'feedback',
78
79
  score: clampScore(record._score),
79
80
  signal: normalizeRecordSignal(record.signal),
80
81
  tags: safeArray(record.tags),
@@ -178,7 +179,8 @@ function deduplicateResults(results) {
178
179
  const bestByFeedbackId = new Map();
179
180
 
180
181
  for (const r of results) {
181
- const feedId = extractFeedbackId(r.id || r.title || r.file || '');
182
+ const rawFeedId = extractFeedbackId(r.id || r.title || r.file || '');
183
+ const feedId = rawFeedId ? (r.projectKey || 'unassigned') + ':' + rawFeedId : null;
182
184
  if (feedId) {
183
185
  const existing = bestByFeedbackId.get(feedId);
184
186
  if (!existing) {
@@ -201,24 +203,25 @@ function deduplicateResults(results) {
201
203
  const seenIds = new Set();
202
204
 
203
205
  for (const r of results) {
204
- const feedId = extractFeedbackId(r.id || r.title || r.file || '');
206
+ const rawFeedId = extractFeedbackId(r.id || r.title || r.file || '');
207
+ const feedId = rawFeedId ? (r.projectKey || 'unassigned') + ':' + rawFeedId : null;
205
208
  let recordToUse = r;
206
209
  if (feedId) {
207
210
  recordToUse = bestByFeedbackId.get(feedId);
208
- if (seenIds.has(recordToUse.id)) continue;
211
+ if (seenIds.has((recordToUse.projectKey || 'unassigned') + ':' + recordToUse.id)) continue;
209
212
  } else {
210
213
  if (r.id && r.id !== 'null' && String(r.id).trim() !== '') {
211
- if (seenIds.has(r.id)) continue;
214
+ if (seenIds.has((r.projectKey || 'unassigned') + ':' + r.id)) continue;
212
215
  }
213
216
  }
214
217
 
215
218
  const normTitle = String(recordToUse.title || '').trim().toLowerCase();
216
219
  const normContext = String(recordToUse.context || '').trim().toLowerCase();
217
- const contentKey = `${normTitle}|${normContext}`;
220
+ const contentKey = `${recordToUse.projectKey || 'unassigned'}|${normTitle}|${normContext}`;
218
221
  if (seenContent.has(contentKey)) continue;
219
222
 
220
223
  if (recordToUse.id && recordToUse.id !== 'null' && String(recordToUse.id).trim() !== '') {
221
- seenIds.add(recordToUse.id);
224
+ seenIds.add((recordToUse.projectKey || 'unassigned') + ':' + recordToUse.id);
222
225
  }
223
226
  seenContent.add(contentKey);
224
227
  finalResults.push(recordToUse);
@@ -227,8 +230,8 @@ function deduplicateResults(results) {
227
230
  return finalResults;
228
231
  }
229
232
 
230
- function getFeedbackResults(query, limit, signal, feedbackDir) {
231
- const results = searchFeedbackLog(query, Math.max(limit * 3, limit), { feedbackDir });
233
+ function getFeedbackResults(query, limit, signal, feedbackDir, projectKey = null, includeMemories = false, localPathEvidence) {
234
+ const results = searchFeedbackLog(query, Math.max(limit * 3, limit), { feedbackDir, projectKey, signal, includeMemories, localPathEvidence });
232
235
  const normalizedSignal = normalizeSignal(signal);
233
236
  const filtered = normalizedSignal
234
237
  ? results.filter((record) => normalizeRecordSignal(record.signal) === normalizedSignal)
@@ -260,6 +263,8 @@ function searchThumbgate({
260
263
  signal = null,
261
264
  feedbackDir = null,
262
265
  accessContext = null,
266
+ projectKey = null,
267
+ localPathEvidence,
263
268
  } = {}) {
264
269
  const trimmedQuery = String(query || '').trim();
265
270
  if (!trimmedQuery) {
@@ -272,6 +277,12 @@ function searchThumbgate({
272
277
 
273
278
  const fetchLimit = Math.max(100, normalizedLimit * 5);
274
279
 
280
+ if (projectKey != null) {
281
+ const unavailableSources = normalizedSource === 'all' ? ['context', 'rules', 'documents'] : ['context', 'rules', 'documents'].filter((item) => item === normalizedSource);
282
+ const rows = ['all', 'feedback'].includes(normalizedSource) ? getFeedbackResults(trimmedQuery, fetchLimit, normalizedSignal, feedbackDir, projectKey, normalizedSource === 'all', localPathEvidence) : [];
283
+ const results = deduplicateResults(sortResults(rows)).slice(0, normalizedLimit);
284
+ return { query: trimmedQuery, source: normalizedSource, signal: normalizedSignal, limit: normalizedLimit, engine: 'filesystem-search', returned: results.length, total: results.length, results, unavailableSources };
285
+ }
275
286
  let results = [];
276
287
  if (normalizedSource === 'feedback') {
277
288
  const raw = getFeedbackResults(trimmedQuery, fetchLimit, normalizedSignal, feedbackDir);
@@ -318,7 +329,10 @@ async function searchThumbgateAsync({
318
329
  embedder,
319
330
  embedderId,
320
331
  accessContext = null,
332
+ projectKey = null,
333
+ localPathEvidence,
321
334
  } = {}) {
335
+ if (projectKey != null) return searchThumbgate({ query, source, limit, signal, feedbackDir, accessContext, projectKey, localPathEvidence });
322
336
  const trimmedQuery = String(query || '').trim();
323
337
  if (!trimmedQuery) throw new Error('query is required');
324
338
  const normalizedSource = normalizeSource(source);
@@ -61,6 +61,7 @@ function recordToolCall({
61
61
  writeRiskTier,
62
62
  metadata,
63
63
  feedbackDir,
64
+ projectKey, projectName, identitySource, cwd, hosted,
64
65
  } = {}) {
65
66
  const logPath = getKpiLogPath({ feedbackDir });
66
67
  fs.mkdirSync(path.dirname(logPath), { recursive: true });
@@ -71,6 +72,7 @@ function recordToolCall({
71
72
  metadata,
72
73
  });
73
74
  const entry = {
75
+ ...require('./project-identity').projectForCapture({ projectKey, projectName, identitySource, cwd }, { hosted: hosted === undefined ? Boolean(require('./feedback-scope').tenantDataScope()) : Boolean(hosted) }),
74
76
  id: `kpi_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`,
75
77
  timestamp: new Date().toISOString(),
76
78
  toolName: toolName || 'unknown',
@@ -115,8 +117,8 @@ function pickDominantTier(tierCounts = {}) {
115
117
  return best;
116
118
  }
117
119
 
118
- function computeToolKpis({ periodHours = 24, feedbackDir } = {}) {
119
- const entries = readJsonl(getKpiLogPath({ feedbackDir }));
120
+ function computeToolKpis({ periodHours = 24, feedbackDir, projectKey } = {}) {
121
+ const entries = require('./project-catalog').readProjectRows(path.dirname(getKpiLogPath({ feedbackDir })), path.basename(getKpiLogPath({ feedbackDir })), { projectKey });
120
122
  const cutoff = Date.now() - periodHours * 60 * 60 * 1000;
121
123
  const recent = entries.filter((entry) => new Date(entry.timestamp).getTime() > cutoff);
122
124
  const byTool = {};
@@ -210,6 +212,7 @@ function getAtRiskTools({
210
212
  p95Threshold = 500,
211
213
  periodHours = 24,
212
214
  feedbackDir,
215
+ projectKey, projectName, identitySource, cwd, hosted,
213
216
  } = {}) {
214
217
  const { tools } = computeToolKpis({ periodHours, feedbackDir });
215
218
  return tools.filter((tool) => tool.requestCount >= 3
@@ -468,6 +468,47 @@ const TOOLS = [
468
468
  },
469
469
  },
470
470
  }),
471
+ readOnlyTool({
472
+ name: 'graphrag_traverse',
473
+ description: 'Answer a multi-hop question over a Neo4j graph with a schema-first ReAct loop. Only read-only Cypher runs (static guard plus READ session); stops after 3 failed attempts and names the missing link instead of guessing. Needs NEO4J_URI, neo4j-driver and model credentials; otherwise returns status "unavailable".',
474
+ inputSchema: {
475
+ type: 'object',
476
+ additionalProperties: false,
477
+ required: ['query'],
478
+ properties: {
479
+ query: { type: 'string', description: 'The multi-hop question to answer.' },
480
+ maxSteps: { type: 'integer', minimum: 1, maximum: 10, description: 'Upper bound on ReAct steps. Default: 10.' },
481
+ },
482
+ },
483
+ }),
484
+ readOnlyTool({
485
+ name: 'route_workload',
486
+ description: 'Decide whether a workload goes to Claude (code, tool use, strict JSON) or Gemini (huge payloads, raw logs), or splits into ordered sub-tasks. Deterministic rules first; an LLM router is used for ambiguous work only when useModel is true. Returns a validated routing decision; does not run the workload.',
487
+ inputSchema: {
488
+ type: 'object',
489
+ additionalProperties: false,
490
+ required: ['workload'],
491
+ properties: {
492
+ workload: { type: 'string', description: 'The task text or payload to route.' },
493
+ useModel: { type: 'boolean', description: 'Allow an LLM router call for ambiguous workloads. Default: false.' },
494
+ },
495
+ },
496
+ }),
497
+ readOnlyTool({
498
+ name: 'trim_context',
499
+ description: 'Compact retrieved context for one target operation before inference: drops metadata and boilerplate, collapses repeats, and keeps error lines, stack frames, trace ids and matching declarations verbatim. Deterministic unless useModel is true and the result is still over tokenBudget.',
500
+ inputSchema: {
501
+ type: 'object',
502
+ additionalProperties: false,
503
+ required: ['rawContext', 'targetOperation'],
504
+ properties: {
505
+ rawContext: { type: 'string', description: 'Raw retrieved text to compact.' },
506
+ targetOperation: { type: 'string', description: 'What the downstream model must do with the context.' },
507
+ tokenBudget: { type: 'integer', minimum: 1, description: 'Target size in estimated tokens. Default: 2000.' },
508
+ useModel: { type: 'boolean', description: 'Allow an LLM compaction pass when over budget. Default: false.' },
509
+ },
510
+ },
511
+ }),
471
512
  readOnlyTool({
472
513
  name: 'plan_agent_design_governance',
473
514
  description: 'Evaluate an agent workflow before adding tools, autonomy, or subagents. Recommends single-agent vs manager/decentralized patterns, baseline evals, instruction fixes, and tool safeguards.',
@@ -552,7 +593,7 @@ const TOOLS = [
552
593
  inputSchema: {
553
594
  type: 'object',
554
595
  properties: {
555
- offer: { type: 'string', description: 'Offer to advertise, such as Pro or Workflow Hardening Sprint.' },
596
+ offer: { type: 'string', description: 'Offer to advertise, such as Pro or Setup Sprint.' },
556
597
  audience: { type: 'string', description: 'Audience segment to target.' },
557
598
  budget: { type: 'number', description: 'Initial test budget.' },
558
599
  keywords: { type: 'array', items: { type: 'string' }, description: 'High-intent conversational queries.' },
@@ -20,7 +20,7 @@ const {
20
20
  const PRICING_TIERS = Object.freeze({
21
21
  free: { name: 'Community', monthlyCost: 0, annualCost: 0 },
22
22
  pro: { name: 'Pro Firewall', monthlyCost: 19, annualCost: 149 },
23
- managed: { name: 'Managed Workflow Gate', monthlyCost: 499, annualCost: 499 },
23
+ managed: { name: 'Setup Sprint', monthlyCost: 499, annualCost: 499 },
24
24
  enterprise: { name: 'Enterprise Gateway', monthlyCost: 2500, annualCost: 27000 },
25
25
  });
26
26
 
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { tenantDataScope } = require('./feedback-scope');
4
+
3
5
  const fs = require('fs');
4
6
  const path = require('path');
5
7
  const { ensureDir } = require('./fs-utils');
@@ -88,6 +90,7 @@ function finalizeEmbedding(vector, options = {}) {
88
90
  let _explicitVectorStoreEngine = null;
89
91
 
90
92
  function resolveVectorBackend(env = process.env) {
93
+ if (tenantDataScope()) return 'lancedb';
91
94
  if (_explicitVectorStoreEngine) return _explicitVectorStoreEngine;
92
95
  const explicit = String(env.THUMBGATE_VECTOR_BACKEND || '').trim().toLowerCase();
93
96
  if (explicit === 'hotdata') return 'hotdata';
@@ -97,7 +100,7 @@ function resolveVectorBackend(env = process.env) {
97
100
  }
98
101
 
99
102
  function getVectorStoreEngine() {
100
- return _explicitVectorStoreEngine || resolveVectorBackend();
103
+ return tenantDataScope() ? 'lancedb' : (_explicitVectorStoreEngine || resolveVectorBackend());
101
104
  }
102
105
 
103
106
  function setVectorStoreEngine(engine) {
@@ -0,0 +1,270 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * verified-lessons.js — Core domain logic for verified lessons, voting,
5
+ * staleness, and exact-error lookup (brief 2026-11-05).
6
+ */
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const { getFeedbackPaths } = require('./feedback-paths');
11
+ const { readJSONL } = require('./feedback-loop');
12
+
13
+ // Built-in seeded lessons catalog (search before solving)
14
+ const SEEDED_LESSONS = [
15
+ {
16
+ id: 'lesson_seed_e2e_base_url',
17
+ title: 'MISTAKE: E2E_BASE_URL is not set during pre-push hook',
18
+ errorPattern: 'E2E_BASE_URL is not set',
19
+ fix: 'set E2E_BASE_URL to the STAGE URL and run the push under with-secrets; never E2E_HOOK_SKIP',
20
+ content: [
21
+ 'What went wrong: Azure DevOps pre-push hook failed: E2E_BASE_URL is not set in a fresh worktree.',
22
+ 'How to avoid: set E2E_BASE_URL to the STAGE URL and run the push under with-secrets; never E2E_HOOK_SKIP',
23
+ 'Action needed: Set E2E_BASE_URL to the STAGE URL and run the push under with-secrets; never E2E_HOOK_SKIP.',
24
+ ].join('\n'),
25
+ category: 'error',
26
+ importance: 'high',
27
+ tags: ['git', 'pre-push', 'azure-devops', 'e2e', 'verification'],
28
+ verificationStatus: 'verified',
29
+ verificationCount: 1,
30
+ lastVerifiedAt: '2026-11-05T00:00:00.000Z',
31
+ verifications: [
32
+ {
33
+ date: '2026-11-05',
34
+ check: 'git push with-secrets (E2E_BASE_URL set to STAGE)',
35
+ },
36
+ ],
37
+ upVotes: 1,
38
+ downVotes: 0,
39
+ netVotes: 1,
40
+ timestamp: '2026-11-05T00:00:00.000Z',
41
+ },
42
+ ];
43
+
44
+ function normalizeVerificationFields(lesson = {}) {
45
+ const verifications = Array.isArray(lesson.verifications) ? [...lesson.verifications] : [];
46
+ const verificationCount = Number.isInteger(lesson.verificationCount)
47
+ ? lesson.verificationCount
48
+ : verifications.length;
49
+ const lastVerifiedAt = lesson.lastVerifiedAt || (verifications.length > 0 ? verifications[verifications.length - 1].date : null);
50
+ const verificationStatus = lesson.verificationStatus || (verificationCount > 0 ? 'verified' : 'unverified');
51
+
52
+ const upVotes = Number.isInteger(lesson.upVotes) ? lesson.upVotes : 0;
53
+ const downVotes = Number.isInteger(lesson.downVotes) ? lesson.downVotes : 0;
54
+ const netVotes = upVotes - downVotes;
55
+
56
+ return {
57
+ ...lesson,
58
+ verificationStatus,
59
+ verifications,
60
+ verificationCount,
61
+ lastVerifiedAt,
62
+ upVotes,
63
+ downVotes,
64
+ netVotes,
65
+ };
66
+ }
67
+
68
+ function formatVerificationBadge(lesson) {
69
+ const count = Number(lesson.verificationCount || 0);
70
+ if (count <= 0 || !lesson.lastVerifiedAt) {
71
+ return 'unverified';
72
+ }
73
+ const dateStr = String(lesson.lastVerifiedAt).split('T')[0];
74
+ return `verified ${count}x, last ${dateStr}`;
75
+ }
76
+
77
+ function isLessonStale(lesson, now = new Date()) {
78
+ if (!lesson || !lesson.lastVerifiedAt) return false;
79
+ const last = new Date(lesson.lastVerifiedAt).getTime();
80
+ if (!Number.isFinite(last)) return false;
81
+ const nowDate = (now instanceof Date ? now : new Date(now)).getTime();
82
+ const diffDays = (nowDate - last) / (1000 * 60 * 60 * 24);
83
+ return diffDays > 30;
84
+ }
85
+
86
+ function isLessonDemoted(lesson) {
87
+ if (!lesson) return false;
88
+ const up = Number(lesson.upVotes || 0);
89
+ const down = Number(lesson.downVotes || 0);
90
+ return down > up;
91
+ }
92
+
93
+ /**
94
+ * Atomically updates a lesson in memory-log.jsonl
95
+ */
96
+ function updateMemoryRecord(memoryId, updater, options = {}) {
97
+ const paths = getFeedbackPaths(options);
98
+ const memoryLogPath = paths.MEMORY_LOG_PATH;
99
+ const dir = path.dirname(memoryLogPath);
100
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
101
+
102
+ let lines = [];
103
+ if (fs.existsSync(memoryLogPath)) {
104
+ const raw = fs.readFileSync(memoryLogPath, 'utf8');
105
+ lines = raw.split('\n').filter(Boolean);
106
+ }
107
+
108
+ let updatedRecord = null;
109
+ let found = false;
110
+ const newLines = lines.map((line) => {
111
+ try {
112
+ const record = JSON.parse(line);
113
+ if (record.id === memoryId || record.canonicalHash === memoryId || record.title === memoryId) {
114
+ found = true;
115
+ updatedRecord = updater(record);
116
+ return JSON.stringify(updatedRecord);
117
+ }
118
+ return line;
119
+ } catch {
120
+ return line;
121
+ }
122
+ });
123
+
124
+ if (!found) {
125
+ const baseRecord = options.initialLesson || {
126
+ id: memoryId,
127
+ title: options.title || memoryId,
128
+ content: options.content || memoryId,
129
+ timestamp: (options.now instanceof Date ? options.now : new Date(options.now || Date.now())).toISOString(),
130
+ signal: 'negative',
131
+ };
132
+ updatedRecord = updater(baseRecord);
133
+ newLines.push(JSON.stringify(updatedRecord));
134
+ }
135
+
136
+ if (updatedRecord) {
137
+ fs.writeFileSync(memoryLogPath, newLines.join('\n') + '\n', 'utf8');
138
+ }
139
+ return updatedRecord;
140
+ }
141
+
142
+ /**
143
+ * Record a verification on a lesson.
144
+ * Resets demoted status (if downVotes > upVotes, verification overrides/resets it).
145
+ */
146
+ function verifyLesson(lessonId, checkCommand = 'manual check', options = {}) {
147
+ const now = options.now instanceof Date ? options.now : new Date(options.now || Date.now());
148
+ const dateStr = now.toISOString().split('T')[0];
149
+
150
+ return updateMemoryRecord(lessonId, (record) => {
151
+ const norm = normalizeVerificationFields(record);
152
+ if (checkCommand === 'check-only') {
153
+ return {
154
+ ...record,
155
+ ...norm,
156
+ };
157
+ }
158
+ const verifications = [...norm.verifications, { date: dateStr, check: checkCommand }];
159
+ const verificationCount = norm.verificationCount + 1;
160
+ const lastVerifiedAt = now.toISOString();
161
+
162
+ // Re-verification overrides or offsets downvotes so it is no longer demoted
163
+ let upVotes = norm.upVotes;
164
+ let downVotes = norm.downVotes;
165
+ if (downVotes > upVotes) {
166
+ upVotes = downVotes; // reset netVotes to 0 so downVotes > upVotes is cleared
167
+ }
168
+
169
+ return {
170
+ ...record,
171
+ verificationStatus: 'verified',
172
+ verifications,
173
+ verificationCount,
174
+ lastVerifiedAt,
175
+ upVotes,
176
+ downVotes,
177
+ netVotes: upVotes - downVotes,
178
+ demoted: false,
179
+ };
180
+ }, options);
181
+ }
182
+
183
+ /**
184
+ * Vote up or down on a lesson.
185
+ */
186
+ function voteOnLesson(lessonId, signal, options = {}) {
187
+ const isUp = signal === 'up' || signal === 'positive';
188
+ const isDown = signal === 'down' || signal === 'negative';
189
+ if (!isUp && !isDown) return null;
190
+
191
+ return updateMemoryRecord(lessonId, (record) => {
192
+ const norm = normalizeVerificationFields(record);
193
+ const upVotes = norm.upVotes + (isUp ? 1 : 0);
194
+ const downVotes = norm.downVotes + (isDown ? 1 : 0);
195
+ const netVotes = upVotes - downVotes;
196
+ const demoted = downVotes > upVotes;
197
+
198
+ return {
199
+ ...record,
200
+ upVotes,
201
+ downVotes,
202
+ netVotes,
203
+ demoted,
204
+ };
205
+ }, options);
206
+ }
207
+
208
+ function matchesErrorMemory(norm, cleanQuery) {
209
+ const errPattern = (norm.errorPattern || '').toLowerCase();
210
+ if (errPattern && cleanQuery.includes(errPattern)) return true;
211
+ if (cleanQuery.length < 8) return false;
212
+ const content = (norm.content || '').toLowerCase();
213
+ const title = (norm.title || '').toLowerCase();
214
+ return content.includes(cleanQuery) || title.includes(cleanQuery);
215
+ }
216
+
217
+ function findMemoryErrorMatch(cleanQuery, options = {}) {
218
+ const paths = getFeedbackPaths(options);
219
+ if (!fs.existsSync(paths.MEMORY_LOG_PATH)) return null;
220
+ const rawMemories = readJSONL(paths.MEMORY_LOG_PATH, { maxLines: 500 });
221
+ for (const mem of rawMemories) {
222
+ const norm = normalizeVerificationFields(mem);
223
+ if (matchesErrorMemory(norm, cleanQuery)) {
224
+ return {
225
+ ...norm,
226
+ stale: isLessonStale(norm, options.now),
227
+ badge: formatVerificationBadge(norm),
228
+ };
229
+ }
230
+ }
231
+ return null;
232
+ }
233
+
234
+ /**
235
+ * Exact error text lookup across seeded catalog + memory-log.jsonl
236
+ */
237
+ function lookupLessonByError(errorText, options = {}) {
238
+ if (!errorText || typeof errorText !== 'string') return null;
239
+ const cleanQuery = errorText.trim().toLowerCase();
240
+ if (!cleanQuery) return null;
241
+
242
+ for (const seed of SEEDED_LESSONS) {
243
+ const pattern = (seed.errorPattern || '').toLowerCase();
244
+ if (pattern && (cleanQuery.includes(pattern) || pattern.includes(cleanQuery))) {
245
+ const norm = normalizeVerificationFields(seed);
246
+ return {
247
+ ...norm,
248
+ isSeeded: true,
249
+ stale: isLessonStale(norm, options.now),
250
+ badge: formatVerificationBadge(norm),
251
+ };
252
+ }
253
+ }
254
+
255
+ return findMemoryErrorMatch(cleanQuery, options);
256
+ }
257
+
258
+ module.exports = {
259
+ SEEDED_LESSONS,
260
+ normalizeVerificationFields,
261
+ formatVerificationBadge,
262
+ isLessonStale,
263
+ isLessonDemoted,
264
+ updateMemoryRecord,
265
+ verifyLesson,
266
+ voteOnLesson,
267
+ voteLesson: voteOnLesson,
268
+ lookupLessonByError,
269
+ DEFAULT_E2E_BASE_URL_LESSON: SEEDED_LESSONS[0],
270
+ };
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * Reads `config/post-deploy-marketing-pages.json` and curls every entry
9
9
  * against the live production URL (default
10
- * https://thumbgate-production.up.railway.app, overridable via
10
+ * https://thumbgate.ai, overridable via
11
11
  * THUMBGATE_PROD_URL env or --prod-url=…). Each response body must
12
12
  * contain the configured sentinel string and must not contain any configured
13
13
  * `mustNotContain` strings. Any mismatch fails the run and the route is
@@ -32,7 +32,7 @@
32
32
  const fs = require('node:fs');
33
33
  const path = require('node:path');
34
34
 
35
- const DEFAULT_PROD_URL = 'https://thumbgate-production.up.railway.app';
35
+ const DEFAULT_PROD_URL = 'https://thumbgate.ai';
36
36
  const DEFAULT_TIMEOUT_MS = 12000;
37
37
  const DEFAULT_MAX_ATTEMPTS = 2;
38
38
  const DEFAULT_RETRY_DELAY_MS = 500;
@@ -11,6 +11,7 @@ const {
11
11
  classifyCommand,
12
12
  evaluateOperationalIntegrity,
13
13
  findReleaseSensitiveFiles,
14
+ isDestructiveDeleteCommand,
14
15
  normalizePosix,
15
16
  resolveRepoRoot,
16
17
  } = require('./operational-integrity');
@@ -22,6 +23,7 @@ const {
22
23
  buildWorkflowControl,
23
24
  normalizeProviderAction,
24
25
  } = require('./provider-action-normalizer');
26
+ const { canonicalizeToolCall } = require('./harness-tool-names');
25
27
  const {
26
28
  detectEconomicAction,
27
29
  evaluateFinancialControl,
@@ -272,15 +274,22 @@ function collectAffectedFiles(toolName, toolInput = {}, repoRoot) {
272
274
  function isHighRiskAction(toolName, toolInput = {}, affectedFiles = []) {
273
275
  if (EDIT_LIKE_TOOLS.has(toolName) && affectedFiles.length > 0) return true;
274
276
  if (toolName !== 'Bash') return false;
275
- return HIGH_RISK_BASH_PATTERN.test(String(toolInput.command || ''));
277
+ const command = String(toolInput.command || '');
278
+ return HIGH_RISK_BASH_PATTERN.test(command) || isDestructiveDeleteCommand(command);
276
279
  }
277
280
 
278
- function classifyActionProfile(toolInput = {}) {
281
+ function classifyActionProfile(toolInput = {}, toolName = '', options = {}) {
279
282
  const command = String(toolInput.command || '');
280
283
  const metadata = toolInput && typeof toolInput.metadata === 'object' ? toolInput.metadata : {};
281
284
  const source = String(toolInput.source || metadata.source || '');
282
285
  const runType = String(toolInput.runType || metadata.runType || '');
283
286
  const combined = [command, source, runType, metadata.context || ''].filter(Boolean).join(' ');
287
+ const metadataContext = [source, runType, metadata.context || '']
288
+ .map((part) => String(part || '').replace(/[_-]+/g, ' '))
289
+ .filter(Boolean)
290
+ .join(' ');
291
+ const effectiveToolName = String(toolName || '').trim()
292
+ || (typeof toolInput.command === 'string' && !toolInput.action && !toolInput.url ? 'Bash' : '');
284
293
 
285
294
  const backgroundAgent = Boolean(
286
295
  toolInput.backgroundAgent === true
@@ -292,7 +301,10 @@ function classifyActionProfile(toolInput = {}) {
292
301
  const economicAction = Boolean(
293
302
  toolInput.economicAction === true
294
303
  || metadata.economicAction === true
295
- || detectEconomicAction('', { ...toolInput, metadata: { ...metadata, context: combined } })
304
+ || detectEconomicAction(effectiveToolName, {
305
+ ...toolInput,
306
+ metadata: { ...metadata, context: metadataContext },
307
+ }, options)
296
308
  );
297
309
  const customerSystemAction = Boolean(
298
310
  toolInput.customerSystemAction === true
@@ -658,7 +670,7 @@ function scoreRisk({
658
670
  if (/\bgh\s+pr\s+merge\b.*--admin\b/i.test(commandInfo.text)) {
659
671
  addDriver(drivers, 'admin_merge_bypass', 0.45, 'Admin merge bypass skips the protected merge path.');
660
672
  }
661
- if (/\brm\s+-rf\b/i.test(commandInfo.text)) {
673
+ if (/\brm\s+-rf\b/i.test(commandInfo.text) || commandInfo.isDestructiveDelete) {
662
674
  addDriver(drivers, 'destructive_delete', 0.28, 'Recursive delete is destructive and difficult to recover from.');
663
675
  }
664
676
  if (taskScopeViolation) {
@@ -1242,6 +1254,7 @@ function classifyReversibility({ command, blastRadius, integrity, protectedSurfa
1242
1254
  const destructiveCommand = /\bgit\s+push\b.*(?:--force|-f)\b/i.test(text)
1243
1255
  || /\bgh\s+pr\s+merge\b.*--admin\b/i.test(text)
1244
1256
  || /\brm\s+-rf\b/i.test(text)
1257
+ || isDestructiveDeleteCommand(text)
1245
1258
  || /\b(?:npm|yarn|pnpm)\s+publish\b/i.test(text)
1246
1259
  || /\bgh\s+release\s+create\b/i.test(text)
1247
1260
  || /\bgit\s+tag\b/i.test(text);
@@ -1541,12 +1554,14 @@ function evaluateWorkflowSentinel(toolName, toolInput = {}, options = {}) {
1541
1554
  tokenEstimate: options.tokenEstimate,
1542
1555
  costUsd: options.costUsd,
1543
1556
  });
1544
- const normalizedToolName = normalizedAction.toolName || toolName;
1545
- const normalizedToolInput = {
1557
+ const reportedToolName = normalizedAction.toolName || toolName;
1558
+ const canonicalCall = canonicalizeToolCall(reportedToolName, {
1546
1559
  ...toolInput,
1547
1560
  ...normalizedAction.toolInput,
1548
- };
1549
- if (normalizedAction.command && !normalizedToolInput.command) {
1561
+ });
1562
+ const normalizedToolName = canonicalCall.toolName;
1563
+ const normalizedToolInput = canonicalCall.toolInput;
1564
+ if (normalizedAction.command && (!normalizedToolInput.command || Array.isArray(normalizedToolInput.command))) {
1550
1565
  normalizedToolInput.command = normalizedAction.command;
1551
1566
  }
1552
1567
  if (normalizedAction.affectedFiles.length > 0 && !normalizedToolInput.changed_files && !normalizedToolInput.changedFiles) {
@@ -1585,7 +1600,7 @@ function evaluateWorkflowSentinel(toolName, toolInput = {}, options = {}) {
1585
1600
  .map((filePath) => toRepoRelativePath(filePath, repoRoot))
1586
1601
  .filter(Boolean)
1587
1602
  : collectAffectedFiles(normalizedToolName, normalizedToolInput, repoRoot));
1588
- let actionProfile = classifyActionProfile(normalizedToolInput);
1603
+ let actionProfile = classifyActionProfile(normalizedToolInput, normalizedToolName, options);
1589
1604
  const financialControl = evaluateFinancialControl({
1590
1605
  toolName: normalizedToolName,
1591
1606
  toolInput: normalizedToolInput,
@@ -1594,6 +1609,9 @@ function evaluateWorkflowSentinel(toolName, toolInput = {}, options = {}) {
1594
1609
  budget: options.budget || toolInput.budget || {},
1595
1610
  financialControl: options.financialControl || toolInput.financialControl,
1596
1611
  }, getFinancialControlRuntimeOptions({
1612
+ runtimeDir: options.runtimeDir,
1613
+ home: options.home,
1614
+ env: options.env,
1597
1615
  feedbackDir: options.feedbackDir
1598
1616
  || process.env.THUMBGATE_FEEDBACK_DIR
1599
1617
  || (repoRoot ? path.join(repoRoot, '.thumbgate') : null),
@@ -1764,7 +1782,7 @@ function evaluateWorkflowSentinel(toolName, toolInput = {}, options = {}) {
1764
1782
  : 'Predicted workflow failure before execution.';
1765
1783
  const report = {
1766
1784
  sentinelVersion: 'workflow-sentinel-v2',
1767
- toolName: normalizedToolName,
1785
+ toolName: reportedToolName,
1768
1786
  normalizedAction,
1769
1787
  costControl,
1770
1788
  financialControl,
@@ -1828,6 +1846,7 @@ module.exports = {
1828
1846
  collectAffectedFiles,
1829
1847
  evaluateWorkflowSentinel,
1830
1848
  isHighRiskAction,
1849
+ isDestructiveDeleteCommand,
1831
1850
  isVersionOrProbeCommand,
1832
1851
  loadGovernanceState,
1833
1852
  normalizeLearnedPolicyForSentinel,
package/server.json CHANGED
@@ -8,13 +8,13 @@
8
8
  "source": "github",
9
9
  "url": "https://github.com/IgorGanapolsky/ThumbGate"
10
10
  },
11
- "version": "1.39.1",
11
+ "version": "1.40.2",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "thumbgate",
17
- "version": "1.39.1",
17
+ "version": "1.40.2",
18
18
  "runtimeHint": "npx",
19
19
  "runtimeArguments": [
20
20
  {