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
@@ -1,5 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
+ const { resolveLocalProject, projectForRecord, validProjectKey } = require('./project-identity');
4
+ function eventProject(input = {}) { return validProjectKey(input.projectKey) ? projectForRecord(input) : tenantDataScope() ? projectForRecord({ projectKey: 'unassigned' }) : resolveLocalProject(input.cwd || input.toolInput?.cwd || process.cwd()); }
5
+
6
+ const { assertScopedDataPath, tenantDataScope } = require('./feedback-scope');
3
7
 
4
8
  /**
5
9
  * Audit Trail — OpenShell-inspired governance layer
@@ -23,8 +27,8 @@ const GATE_EVENTS_LOG_FILENAME = 'gate-events-log.jsonl';
23
27
  // Paths
24
28
  // ---------------------------------------------------------------------------
25
29
 
26
- function getAuditLogPath() {
27
- return path.join(resolveFeedbackDir(), AUDIT_LOG_FILENAME);
30
+ function getAuditLogPath(options = {}) {
31
+ return assertScopedDataPath(path.join(resolveFeedbackDir(options), AUDIT_LOG_FILENAME));
28
32
  }
29
33
 
30
34
  /**
@@ -51,32 +55,33 @@ const REGISTRY_FILENAME = 'agent-registry.jsonl';
51
55
  const OBSERVED_FILENAME = 'observed-agents.jsonl';
52
56
  const OBSERVED_COMPACT_BYTES = 512 * 1024;
53
57
 
54
- function getRegistryPath() {
55
- return path.join(resolveFeedbackDir(), REGISTRY_FILENAME);
58
+ function getRegistryPath(options = {}) {
59
+ return assertScopedDataPath(path.join(resolveFeedbackDir(options), REGISTRY_FILENAME));
56
60
  }
57
61
 
58
- function getObservedAgentsPath() {
59
- return path.join(resolveFeedbackDir(), OBSERVED_FILENAME);
62
+ function getObservedAgentsPath(options = {}) {
63
+ return assertScopedDataPath(path.join(resolveFeedbackDir(options), OBSERVED_FILENAME));
60
64
  }
61
65
 
62
66
  /**
63
67
  * Register an agent session. Called on MCP server startup or agent bootstrap.
64
68
  */
65
- function registerAgent({ agentId, source, project, branch, metadata } = {}) {
69
+ function registerAgent({ agentId, source, project, branch, metadata, ...options } = {}) {
66
70
  const id = agentId || `agent_${Date.now()}_${crypto.randomUUID().slice(0, 8)}`;
67
71
  const record = {
72
+ ...eventProject(options),
68
73
  id,
69
74
  registeredAt: new Date().toISOString(),
70
75
  lastSeenAt: new Date().toISOString(),
71
76
  source: source || 'unknown',
72
- project: project || path.basename(process.cwd()),
77
+ project: project || (tenantDataScope() ? null : path.basename(process.cwd())),
73
78
  branch: branch || null,
74
79
  toolCalls: 0,
75
80
  gateBlocks: 0,
76
81
  gateWarns: 0,
77
82
  metadata: { lifecycleStatus: 'active', ...(metadata || {}) },
78
83
  };
79
- const registryPath = getRegistryPath();
84
+ const registryPath = getRegistryPath(options);
80
85
  ensureDir(path.dirname(registryPath));
81
86
  fs.appendFileSync(registryPath, JSON.stringify(record) + '\n');
82
87
  return record;
@@ -85,8 +90,8 @@ function registerAgent({ agentId, source, project, branch, metadata } = {}) {
85
90
  /**
86
91
  * Record agent activity — called after each tool call evaluation.
87
92
  */
88
- function recordAgentActivity(agentId, decision) {
89
- const registryPath = getRegistryPath();
93
+ function recordAgentActivity(agentId, decision, options = {}) {
94
+ const registryPath = getRegistryPath(options);
90
95
  if (!fs.existsSync(registryPath)) return;
91
96
  const lines = fs.readFileSync(registryPath, 'utf-8').trim().split('\n');
92
97
  const updated = [];
@@ -164,18 +169,18 @@ function retireAgent(agentId, reason) {
164
169
  * only under the cross-process ledger lock so a concurrent agent's append can
165
170
  * never be truncated by the read-aggregate-rewrite window.
166
171
  */
167
- function recordObservedAgent(agentId) {
172
+ function recordObservedAgent(agentId, options = {}) {
168
173
  const id = String(agentId || '').trim();
169
174
  if (!id) return null;
170
- const observedPath = getObservedAgentsPath();
175
+ const observedPath = getObservedAgentsPath(options);
171
176
  ensureDir(path.dirname(observedPath));
172
- const event = { id, seenAt: new Date().toISOString() };
177
+ const event = { ...eventProject(options), id, seenAt: new Date().toISOString() };
173
178
  fs.appendFileSync(observedPath, JSON.stringify(event) + '\n');
174
179
  try {
175
180
  if (fs.statSync(observedPath).size > OBSERVED_COMPACT_BYTES) {
176
181
  const { withFileLedgerLock } = require('./file-ledger-lock');
177
182
  withFileLedgerLock(observedPath + '.lock', () => {
178
- const compacted = loadObservedAgents()
183
+ const compacted = loadObservedAgents(options)
179
184
  .map((row) => JSON.stringify(row))
180
185
  .join('\n');
181
186
  fs.writeFileSync(observedPath, compacted + '\n');
@@ -191,8 +196,8 @@ function recordObservedAgent(agentId) {
191
196
  * Aggregate observation events into one row per agent id:
192
197
  * { id, firstSeenAt, lastSeenAt, observations }.
193
198
  */
194
- function loadObservedAgents() {
195
- const observedPath = getObservedAgentsPath();
199
+ function loadObservedAgents(options = {}) {
200
+ const observedPath = getObservedAgentsPath(options);
196
201
  if (!fs.existsSync(observedPath)) return [];
197
202
  const byId = new Map();
198
203
  const raw = fs.readFileSync(observedPath, 'utf-8').trim();
@@ -207,7 +212,10 @@ function loadObservedAgents() {
207
212
  const id = String(event.id || '').trim();
208
213
  if (!id) continue;
209
214
  const seenAt = event.seenAt || event.lastSeenAt || new Date().toISOString();
210
- const row = byId.get(id) || {
215
+ const descriptor = projectForRecord(event);
216
+ const key = descriptor.projectKey + ':' + id;
217
+ const row = byId.get(key) || {
218
+ ...descriptor,
211
219
  id,
212
220
  firstSeenAt: event.firstSeenAt || seenAt,
213
221
  lastSeenAt: seenAt,
@@ -216,7 +224,7 @@ function loadObservedAgents() {
216
224
  if (seenAt < row.firstSeenAt) row.firstSeenAt = seenAt;
217
225
  if (seenAt > row.lastSeenAt) row.lastSeenAt = seenAt;
218
226
  row.observations += Number(event.observations) > 0 ? Number(event.observations) : 1;
219
- byId.set(id, row);
227
+ byId.set(key, row);
220
228
  }
221
229
  return [...byId.values()];
222
230
  }
@@ -239,10 +247,13 @@ function loadObservedAgents() {
239
247
  * @returns {object} the stored audit record
240
248
  */
241
249
  function recordAuditEvent(params = {}) {
242
- const logPath = getAuditLogPath();
250
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1' || params.dryRun) {
251
+ return { id: 'audit_sandbox', decision: params.decision || 'allow', _sandbox: true };
252
+ }
253
+ const logPath = getAuditLogPath(params);
243
254
  ensureDir(path.dirname(logPath));
244
-
245
255
  const record = {
256
+ ...eventProject(params),
246
257
  id: `audit_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
247
258
  timestamp: new Date().toISOString(),
248
259
  toolName: params.toolName || 'unknown',
@@ -345,15 +356,17 @@ function getCircularReplacer() {
345
356
  * vs ~300 real). Gate events are now logged to gate-events-log.jsonl for
346
357
  * internal analytics only — they never pollute thumbs-up/thumbs-down counts.
347
358
  */
348
- function auditToFeedback(auditRecord) {
359
+ function auditToFeedback(auditRecord, options = {}) {
360
+ if (!auditRecord || auditRecord._sandbox || process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
349
361
  if (auditRecord.decision === 'allow') return null;
350
362
 
351
363
  try {
352
364
  const { getFeedbackPaths } = require('./feedback-paths');
353
- const { FEEDBACK_DIR } = getFeedbackPaths();
365
+ const { FEEDBACK_DIR } = getFeedbackPaths(options);
354
366
  const gateLogPath = path.join(FEEDBACK_DIR, GATE_EVENTS_LOG_FILENAME);
355
367
  ensureDir(path.dirname(gateLogPath));
356
368
  const entry = {
369
+ ...projectForRecord(auditRecord),
357
370
  id: `gate_${crypto.randomUUID()}`,
358
371
  gateId: auditRecord.gateId,
359
372
  decision: auditRecord.decision,
@@ -375,7 +388,7 @@ function auditToFeedback(auditRecord) {
375
388
  // ---------------------------------------------------------------------------
376
389
 
377
390
  function readAuditLog(logPath) {
378
- const p = logPath || getAuditLogPath();
391
+ const p = assertScopedDataPath(logPath || getAuditLogPath());
379
392
  if (!fs.existsSync(p)) return [];
380
393
  const raw = fs.readFileSync(p, 'utf-8').trim();
381
394
  if (!raw) return [];
@@ -0,0 +1,249 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Auto-Context Packs
6
+ *
7
+ * Automatically assembles context packs from the top recurring failure patterns.
8
+ * Reads feedback logs and gate stats, identifies the top 5 most-blocked gate IDs
9
+ * and top 5 most-common failure tags, then assembles context packs for each.
10
+ *
11
+ * Output: .claude/memory/feedback/contextfs/auto/<pack-name>.json
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const { analyzeFeedback } = require('./feedback-loop');
18
+ const { calculateStats, loadGatesFile, MANUAL_GATES_PATH } = require('./gate-stats');
19
+ const { resolveFeedbackDir } = require('./feedback-paths');
20
+ const { ensureDir } = require('./fs-utils');
21
+
22
+ const TOP_N = 5;
23
+ const MAX_FEEDBACK_ENTRIES = 10;
24
+
25
+ function getAutoPacksDir() {
26
+ if (process.env.THUMBGATE_AUTO_PACKS_DIR) return process.env.THUMBGATE_AUTO_PACKS_DIR;
27
+ const feedbackDir = resolveFeedbackDir();
28
+ return path.join(feedbackDir, 'contextfs', 'auto');
29
+ }
30
+
31
+ function loadFeedbackEntries(logPath) {
32
+ if (!logPath || !fs.existsSync(logPath)) return [];
33
+ const lines = fs.readFileSync(logPath, 'utf-8').split('\n');
34
+ const entries = [];
35
+ for (const line of lines) {
36
+ const trimmed = line.trim();
37
+ if (!trimmed) continue;
38
+ try {
39
+ entries.push(JSON.parse(trimmed));
40
+ } catch {
41
+ // skip malformed lines
42
+ }
43
+ }
44
+ return entries;
45
+ }
46
+
47
+ function loadAllGateDefinitions() {
48
+ const PROJECT_ROOT = path.join(__dirname, '..');
49
+ const manualGates = loadGatesFile(MANUAL_GATES_PATH);
50
+
51
+ // Also try to load auto-promoted gates
52
+ let autoGates = [];
53
+ try {
54
+ const { getAutoGatesPath } = require('./auto-promote-gates');
55
+ autoGates = loadGatesFile(getAutoGatesPath());
56
+ } catch {
57
+ // auto-promoted gates not available — that's fine
58
+ }
59
+
60
+ return [...manualGates, ...autoGates];
61
+ }
62
+
63
+ function getTopBlockedGateIds(stats) {
64
+ const gates = (stats.gates || []).filter(
65
+ (g) => g.action === 'block' && Number(g.occurrences || 0) > 0
66
+ );
67
+ gates.sort((a, b) => (b.occurrences || 0) - (a.occurrences || 0));
68
+ return gates.slice(0, TOP_N).map((g) => g.id).filter(Boolean);
69
+ }
70
+
71
+ function getTopFailureTags(analysis) {
72
+ const tags = analysis.tags || {};
73
+ const tagList = Object.entries(tags)
74
+ .map(([tag, counts]) => ({ tag, negative: counts.negative || 0, total: counts.total || 0 }))
75
+ .filter((t) => t.negative > 0)
76
+ .sort((a, b) => b.negative - a.negative);
77
+ return tagList.slice(0, TOP_N).map((t) => t.tag);
78
+ }
79
+
80
+ function getFeedbackForGate(entries, gateId) {
81
+ return entries
82
+ .filter((e) => {
83
+ const tags = e.tags || [];
84
+ return (
85
+ e.gateId === gateId ||
86
+ tags.includes(gateId) ||
87
+ (e.context || '').includes(gateId) ||
88
+ (e.whatWentWrong || '').includes(gateId)
89
+ );
90
+ })
91
+ .slice(-MAX_FEEDBACK_ENTRIES);
92
+ }
93
+
94
+ function getFeedbackForTag(entries, tag) {
95
+ return entries
96
+ .filter((e) => {
97
+ const tags = e.tags || [];
98
+ return tags.includes(tag);
99
+ })
100
+ .slice(-MAX_FEEDBACK_ENTRIES);
101
+ }
102
+
103
+ function extractCorrectiveAction(entry) {
104
+ return entry.whatToChange || entry.correctiveAction || entry.lesson || null;
105
+ }
106
+
107
+ function buildPackForGate(gateId, gateDef, feedbackEntries, allEntries) {
108
+ const relevantFeedback = getFeedbackForGate(allEntries, gateId);
109
+ const correctiveActions = relevantFeedback
110
+ .map(extractCorrectiveAction)
111
+ .filter(Boolean)
112
+ .slice(0, 3);
113
+
114
+ return {
115
+ type: 'gate-failure',
116
+ gateId,
117
+ generatedAt: new Date().toISOString(),
118
+ gate: gateDef || { id: gateId },
119
+ recentFeedback: relevantFeedback.map((e) => ({
120
+ signal: e.signal,
121
+ tags: e.tags || [],
122
+ context: (e.context || '').slice(0, 300),
123
+ whatWentWrong: (e.whatWentWrong || '').slice(0, 300),
124
+ timestamp: e.timestamp || null,
125
+ })),
126
+ correctiveActions,
127
+ summary: {
128
+ totalFeedbackMatched: relevantFeedback.length,
129
+ hasCorrectiveAction: correctiveActions.length > 0,
130
+ },
131
+ };
132
+ }
133
+
134
+ function buildPackForTag(tag, feedbackEntries) {
135
+ const relevantFeedback = getFeedbackForTag(feedbackEntries, tag);
136
+ const correctiveActions = relevantFeedback
137
+ .map(extractCorrectiveAction)
138
+ .filter(Boolean)
139
+ .slice(0, 3);
140
+
141
+ return {
142
+ type: 'tag-failure',
143
+ tag,
144
+ generatedAt: new Date().toISOString(),
145
+ recentFeedback: relevantFeedback.map((e) => ({
146
+ signal: e.signal,
147
+ tags: e.tags || [],
148
+ context: (e.context || '').slice(0, 300),
149
+ whatWentWrong: (e.whatWentWrong || '').slice(0, 300),
150
+ timestamp: e.timestamp || null,
151
+ })),
152
+ correctiveActions,
153
+ summary: {
154
+ totalFeedbackMatched: relevantFeedback.length,
155
+ hasCorrectiveAction: correctiveActions.length > 0,
156
+ },
157
+ };
158
+ }
159
+
160
+ function toSlug(input) {
161
+ return String(input || 'item')
162
+ .toLowerCase()
163
+ .replace(/[^a-z0-9]+/g, '-')
164
+ .replace(/^-+|-+$/g, '')
165
+ .slice(0, 60) || 'item';
166
+ }
167
+
168
+ /**
169
+ * Generate context packs from top failure patterns.
170
+ *
171
+ * @param {Object} [options]
172
+ * @param {string} [options.feedbackLogPath] - Override the feedback log path.
173
+ * @param {string} [options.outputDir] - Override the output directory.
174
+ * @returns {{ packCount: number, packs: Array<{name: string, filePath: string, type: string, id: string}> }}
175
+ */
176
+ function generateAutoContextPacks(options = {}) {
177
+ const outputDir = options.outputDir || getAutoPacksDir();
178
+ ensureDir(outputDir);
179
+
180
+ // Load analysis data — handle empty/missing gracefully
181
+ let analysis = { tags: {}, topTags: [] };
182
+ try {
183
+ analysis = analyzeFeedback(options.feedbackLogPath || undefined);
184
+ } catch {
185
+ // degrade gracefully if feedback log is missing or unreadable
186
+ }
187
+
188
+ let stats = { gates: [], totalBlocked: 0 };
189
+ try {
190
+ stats = calculateStats();
191
+ } catch {
192
+ // degrade gracefully if gate stats cannot be loaded
193
+ }
194
+
195
+ // Load raw feedback entries for context matching
196
+ const { getFeedbackPaths } = require('./feedback-loop');
197
+ const feedbackPaths = getFeedbackPaths();
198
+ const logPath = options.feedbackLogPath || feedbackPaths.FEEDBACK_LOG_PATH;
199
+ const allEntries = loadFeedbackEntries(logPath);
200
+
201
+ // Load gate definitions for enrichment
202
+ const allGates = loadAllGateDefinitions();
203
+ const gateById = {};
204
+ for (const g of allGates) {
205
+ if (g.id) gateById[g.id] = g;
206
+ }
207
+
208
+ const packs = [];
209
+
210
+ // -- Top 5 blocked gate IDs --
211
+ const topGateIds = getTopBlockedGateIds(stats);
212
+ for (const gateId of topGateIds) {
213
+ const pack = buildPackForGate(gateId, gateById[gateId] || null, [], allEntries);
214
+ const slug = `gate-${toSlug(gateId)}`;
215
+ const filePath = path.join(outputDir, `${slug}.json`);
216
+ fs.writeFileSync(filePath, JSON.stringify(pack, null, 2) + '\n');
217
+ packs.push({ name: slug, filePath, type: 'gate-failure', id: gateId });
218
+ }
219
+
220
+ // -- Top 5 failure tags --
221
+ const topTags = getTopFailureTags(analysis);
222
+ for (const tag of topTags) {
223
+ const pack = buildPackForTag(tag, allEntries);
224
+ const slug = `tag-${toSlug(tag)}`;
225
+ const filePath = path.join(outputDir, `${slug}.json`);
226
+ fs.writeFileSync(filePath, JSON.stringify(pack, null, 2) + '\n');
227
+ packs.push({ name: slug, filePath, type: 'tag-failure', id: tag });
228
+ }
229
+
230
+ return { packCount: packs.length, packs };
231
+ }
232
+
233
+ module.exports = {
234
+ generateAutoContextPacks,
235
+ getAutoPacksDir,
236
+ getTopBlockedGateIds,
237
+ getTopFailureTags,
238
+ };
239
+
240
+ if (path.resolve(process.argv[1]) === path.resolve(__filename)) {
241
+ const result = generateAutoContextPacks();
242
+ console.log(`Generated ${result.packCount} context pack(s):`);
243
+ for (const p of result.packs) {
244
+ console.log(` [${p.type}] ${p.name} -> ${p.filePath}`);
245
+ }
246
+ if (result.packCount === 0) {
247
+ console.log(' (No failure patterns found yet — capture some feedback first.)');
248
+ }
249
+ }
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { tenantDataScope, assertScopedDataPath } = require('./feedback-scope');
5
+
4
6
  const fs = require('fs');
5
7
  const path = require('path');
6
8
  const { resolveFeedbackDir } = require('./feedback-paths');
@@ -32,6 +34,8 @@ function getRuleTtlMs() {
32
34
  const NEG_SIGNALS = new Set(['negative', 'negative_strong', 'down', 'thumbs_down']);
33
35
 
34
36
  function getFeedbackLogPath() {
37
+ const scope = tenantDataScope();
38
+ if (scope) return assertScopedDataPath(path.join(scope.feedbackDir, 'feedback-log.jsonl'));
35
39
  if (process.env.THUMBGATE_FEEDBACK_DIR) {
36
40
  return path.join(process.env.THUMBGATE_FEEDBACK_DIR, 'feedback-log.jsonl');
37
41
  }
@@ -45,8 +49,9 @@ function getFeedbackLogPath() {
45
49
  return localFallback; // default even if doesn't exist
46
50
  }
47
51
 
48
- function getAutoGatesPath() {
49
- return path.join(path.dirname(getFeedbackLogPath()), 'auto-promoted-gates.json');
52
+ function getAutoGatesPath(options = {}) {
53
+ const feedbackDir = options.feedbackDir ? resolveFeedbackDir(options) : path.dirname(getFeedbackLogPath());
54
+ return assertScopedDataPath(path.join(feedbackDir, 'auto-promoted-gates.json'));
50
55
  }
51
56
 
52
57
  function readJSONL(filePath) {
@@ -70,7 +75,7 @@ function readJSONL(filePath) {
70
75
  const REGRESSION_FALSE_BLOCK_LIMIT = 0; // any prior safe action it would block => quarantine
71
76
 
72
77
  function getAuditTrailPath() {
73
- return path.join(path.dirname(getFeedbackLogPath()), 'audit-trail.jsonl');
78
+ return assertScopedDataPath(path.join(path.dirname(getFeedbackLogPath()), 'audit-trail.jsonl'));
74
79
  }
75
80
 
76
81
  // Returns { falseBlocks, allowSampleSize } or null when there is no history /
@@ -84,7 +89,7 @@ function regressionCheck(gate, options = {}) {
84
89
  let matchesGate;
85
90
  try { ({ matchesGate } = require('./gates-engine')); } catch { return null; }
86
91
  if (typeof matchesGate !== 'function') return null;
87
- let allowed = entries.filter((e) => e && e.decision === 'allow' && e.toolName);
92
+ let allowed = entries.filter((e) => e && e.decision === 'allow' && e.toolName && require('./project-identity').matchesProject(e, gate.projectKey));
88
93
  if (!allowed.length) return null;
89
94
 
90
95
  // The command we just learned to block was, by definition, ALLOWED before we
@@ -113,7 +118,7 @@ function regressionCheck(gate, options = {}) {
113
118
  let falseBlocks = 0;
114
119
  for (const e of allowed) {
115
120
  try {
116
- if (matchesGate(gate, e.toolName, e.toolInput || {})) falseBlocks += 1;
121
+ if (matchesGate(gate, e.toolName, e.toolInput || {}, { projectKey: gate.projectKey })) falseBlocks += 1;
117
122
  } catch { /* a bad pattern/entry never counts as a false block */ }
118
123
  }
119
124
  return { falseBlocks, allowSampleSize: allowed.length };
@@ -123,8 +128,8 @@ function safeRegressionCheck(gate, options) {
123
128
  try { return regressionCheck(gate, options); } catch { return null; }
124
129
  }
125
130
 
126
- function loadAutoGates() {
127
- const autoGatesPath = getAutoGatesPath();
131
+ function loadAutoGates(options = {}) {
132
+ const autoGatesPath = getAutoGatesPath(options);
128
133
  if (!fs.existsSync(autoGatesPath)) {
129
134
  return { version: 1, gates: [], promotionLog: [] };
130
135
  }
@@ -135,8 +140,8 @@ function loadAutoGates() {
135
140
  }
136
141
  }
137
142
 
138
- function saveAutoGates(data) {
139
- const autoGatesPath = getAutoGatesPath();
143
+ function saveAutoGates(data, options = {}) {
144
+ const autoGatesPath = getAutoGatesPath(options);
140
145
  const dir = path.dirname(autoGatesPath);
141
146
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
142
147
  fs.writeFileSync(autoGatesPath, JSON.stringify(data, null, 2) + '\n');
@@ -277,12 +282,15 @@ function groupNegativeFeedback(entries, windowDays) {
277
282
  // Enforcement groups ONLY by executable action. Tag/diagnosis metadata is
278
283
  // useful for memory and dashboards, but must not create hard-block thresholds
279
284
  // that attach to an unrelated latest command.
280
- const key = extractPatternKey(entry);
281
- if (!key) continue;
285
+ const patternKey = extractPatternKey(entry);
286
+ if (!patternKey) continue;
287
+ const project = require('./project-identity').projectForRecord(entry);
288
+ const key = project.projectKey + ':' + patternKey;
282
289
 
283
290
  if (!groups[key]) {
284
291
  groups[key] = {
285
- key,
292
+ ...project,
293
+ key: patternKey,
286
294
  count: 0,
287
295
  entries: [],
288
296
  latestContext: '',
@@ -429,7 +437,10 @@ function buildGateRule(group, actionOverride) {
429
437
  const expiresAt = isManual ? null : new Date(nowMs + getRuleTtlMs()).toISOString();
430
438
 
431
439
  return {
432
- id: patternToGateId(String(g.key || 'unknown')),
440
+ ...require('./project-identity').projectForRecord(g),
441
+ scope: 'project',
442
+ active: require('./project-identity').projectForRecord(g).projectKey !== 'unassigned',
443
+ id: patternToGateId(String(g.key || 'unknown')) + '-' + require('./project-identity').hash(require('./project-identity').projectForRecord(g).projectKey).slice(0, 16),
433
444
  trigger: `auto:${g.key || 'unknown'}`,
434
445
  // Derived from executable action OR known surface class — never raw prose.
435
446
  pattern,
@@ -516,7 +527,7 @@ function recordGateFire(data, gateId, now = Date.now()) {
516
527
  return updated;
517
528
  }
518
529
 
519
- function forcePromote(context, action = 'block') {
530
+ function forcePromote(context, action = 'block', options = {}) {
520
531
  if (!context) throw new Error('context is required for force-promote');
521
532
  let executable = extractExecutableAction({ context });
522
533
  // If extractExecutableAction returned narration that would become inert prose,
@@ -538,13 +549,10 @@ function forcePromote(context, action = 'block') {
538
549
  );
539
550
  }
540
551
 
541
- const data = loadAutoGates();
542
- const gateId = patternToGateId(context);
543
-
544
- // Remove existing if any
545
- data.gates = data.gates.filter(g => g.id !== gateId);
546
-
552
+ const data = loadAutoGates(options);
553
+ const project = require('./project-identity').projectForCapture(options, options);
547
554
  const gate = buildGateRule({
555
+ ...project,
548
556
  key: context,
549
557
  latestContext: context,
550
558
  latestExecutable: executable || '',
@@ -561,6 +569,8 @@ function forcePromote(context, action = 'block') {
561
569
  );
562
570
  }
563
571
 
572
+ const gateId = gate.id;
573
+ data.gates = data.gates.filter((existing) => existing.id !== gateId || existing.projectKey !== project.projectKey);
564
574
  data.gates.unshift(gate);
565
575
 
566
576
  if (data.gates.length > MAX_AUTO_GATES) {
@@ -578,7 +588,7 @@ function forcePromote(context, action = 'block') {
578
588
  source: 'force-promote',
579
589
  });
580
590
 
581
- saveAutoGates(data);
591
+ saveAutoGates(data, options);
582
592
  return {
583
593
  gateId,
584
594
  action,
@@ -589,14 +599,14 @@ function forcePromote(context, action = 'block') {
589
599
  }
590
600
 
591
601
  function promote(feedbackLogPath, options) {
592
- const opts = options || {};
602
+ const opts = { ...(options || {}), ...(feedbackLogPath ? { feedbackDir: path.dirname(feedbackLogPath) } : {}) };
593
603
  const logPath = feedbackLogPath || getFeedbackLogPath();
594
604
  const entries = readJSONL(logPath);
595
605
  const groups = groupNegativeFeedback(entries, WINDOW_DAYS);
596
606
  // Expire stale gates BEFORE running the promotion loop so an expiring
597
607
  // gate that's about to be re-promoted gets a fresh TTL via the normal
598
608
  // path rather than carrying a near-stale expiresAt.
599
- const { data: expiredData, expired } = expireGates(loadAutoGates());
609
+ const { data: expiredData, expired } = expireGates(loadAutoGates(opts));
600
610
  const data = expiredData;
601
611
  // Drop permanently inert prose gates left by older force-promote / promotion bugs.
602
612
  const inertRemoved = [];
@@ -608,7 +618,7 @@ function promote(feedbackLogPath, options) {
608
618
  return true;
609
619
  });
610
620
  if (expired.length > 0 || inertRemoved.length > 0) {
611
- saveAutoGates(data);
621
+ saveAutoGates(data, opts);
612
622
  }
613
623
  const promotions = [
614
624
  ...expired.map((e) => ({ type: 'expired', gateId: e.id, expiredAt: e.expiresAt })),
@@ -618,7 +628,7 @@ function promote(feedbackLogPath, options) {
618
628
  for (const group of Object.values(groups)) {
619
629
  if (group.count < WARN_THRESHOLD) continue;
620
630
 
621
- const gateId = patternToGateId(group.key);
631
+ const gateId = buildGateRule(group).id;
622
632
 
623
633
  // Contexts that produced this gate. Their prior "allow" decisions are the
624
634
  // incident the operator thumbs-downed, not false positives — both the
@@ -628,7 +638,7 @@ function promote(feedbackLogPath, options) {
628
638
  group.latestContext,
629
639
  ...(group.entries || []).map((e) => e && (e.context || e.whatWentWrong)),
630
640
  ].filter(Boolean);
631
- const regressionOpts = { ...opts, incidentContexts };
641
+ const regressionOpts = { ...opts, auditTrailPath: opts.auditTrailPath || path.join(path.dirname(logPath), 'audit-trail.jsonl'), incidentContexts };
632
642
 
633
643
  // Check for existing gate — possibly upgrade
634
644
  const existingIdx = data.gates.findIndex((g) => g.id === gateId);
@@ -715,7 +725,7 @@ function promote(feedbackLogPath, options) {
715
725
  data.promotionLog.push({ ...p, timestamp: new Date().toISOString() });
716
726
  }
717
727
 
718
- saveAutoGates(data);
728
+ saveAutoGates(data, opts);
719
729
 
720
730
  return { promotions, totalGates: data.gates.length, data };
721
731
  }