thumbgate 1.39.0 → 1.40.1

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 (180) hide show
  1. package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
  2. package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.well-known/llms.txt +2 -2
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +11 -5
  7. package/adapters/claude/.mcp.json +6 -2
  8. package/adapters/codex/config.toml +5 -0
  9. package/adapters/forge/forge.yaml +4 -4
  10. package/adapters/future-agi/.mcp.json +1 -1
  11. package/adapters/future-agi/config.toml +1 -1
  12. package/adapters/future-agi/opencode.json +1 -1
  13. package/adapters/herdr/herdr-plugin.toml +2 -2
  14. package/adapters/mcp/server-stdio.js +104 -7
  15. package/adapters/opencode/opencode.json +1 -1
  16. package/adapters/strands/strands-middleware.js +31 -4
  17. package/bin/cli.js +191 -54
  18. package/config/brand-standards.json +131 -0
  19. package/config/gates/default.json +18 -1
  20. package/config/github-about.json +1 -1
  21. package/config/mcp-allowlists.json +16 -3
  22. package/config/merge-quality-checks.json +3 -1
  23. package/config/post-deploy-marketing-pages.json +4 -4
  24. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  25. package/hooks/hooks.json +24 -0
  26. package/openapi/openapi.yaml +7 -3
  27. package/package.json +87 -33
  28. package/public/about.html +2 -2
  29. package/public/admin.html +771 -0
  30. package/public/agent-manager.html +3 -3
  31. package/public/agents-cost-savings.html +1 -1
  32. package/public/ai-malpractice-prevention.html +12 -12
  33. package/public/architecture.html +0 -1
  34. package/public/assets/diagrams/decision.svg +3 -3
  35. package/public/assets/diagrams/hero-thumbs.svg +2 -4
  36. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  37. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  38. package/public/blog/git-at-agent-scale.html +2 -2
  39. package/public/blog/inside-your-boundary.html +1 -1
  40. package/public/blog/process-over-outcome-gates.html +1 -1
  41. package/public/case-studies.html +5 -6
  42. package/public/codex-enterprise.html +1 -1
  43. package/public/codex-plugin.html +1 -1
  44. package/public/dashboard.html +775 -483
  45. package/public/diagnostic.html +15 -10
  46. package/public/enterprise-governance.html +26 -174
  47. package/public/eval-scorecard.html +3 -4
  48. package/public/eval-scorecard.json +2 -2
  49. package/public/evaluations.html +0 -1
  50. package/public/founders.html +3 -3
  51. package/public/gaming-playbook.html +4 -4
  52. package/public/guide.html +3 -5
  53. package/public/index.html +302 -97
  54. package/public/install.html +16 -10
  55. package/public/js/buyer-intent.js +49 -8
  56. package/public/lessons.html +246 -83
  57. package/public/numbers.html +32 -33
  58. package/public/operator-framework.html +44 -72
  59. package/public/peter.html +3 -3
  60. package/public/platform-partners.html +1 -1
  61. package/public/pricing.html +163 -66
  62. package/public/pro.html +3 -1
  63. package/public/project-switcher.js +76 -0
  64. package/public/whitepaper.html +1 -2
  65. package/scripts/action-receipts.js +393 -0
  66. package/scripts/activation-quickstart.js +15 -3
  67. package/scripts/activation-tracker.js +280 -3
  68. package/scripts/agent-action-inventory.js +235 -143
  69. package/scripts/agent-operations-planner.js +1 -1
  70. package/scripts/agent-readiness.js +36 -6
  71. package/scripts/agentic-prompt-pipelines.js +901 -0
  72. package/scripts/analytics-window.js +7 -1
  73. package/scripts/async-job-runner.js +66 -11
  74. package/scripts/audit-trail.js +37 -24
  75. package/scripts/auto-promote-gates.js +37 -27
  76. package/scripts/auto-wire-hooks.js +64 -25
  77. package/scripts/backfill-lesson-scopes.js +122 -0
  78. package/scripts/billing.js +889 -132
  79. package/scripts/bot-detection.js +112 -0
  80. package/scripts/brand-standards-gate.js +571 -0
  81. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  82. package/scripts/cli-demo.js +5 -27
  83. package/scripts/cli-schema.js +25 -1
  84. package/scripts/commercial-offer.js +2 -2
  85. package/scripts/contextfs.js +9 -3
  86. package/scripts/craft-playbook-gate.js +550 -0
  87. package/scripts/cross-encoder-reranker.js +4 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +574 -167
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/docker-sandbox-planner.js +3 -3
  92. package/scripts/export-dpo-pairs.js +12 -7
  93. package/scripts/failure-diagnostics.js +11 -0
  94. package/scripts/feedback-aggregate.js +4 -0
  95. package/scripts/feedback-attribution.js +6 -4
  96. package/scripts/feedback-history-distiller.js +18 -6
  97. package/scripts/feedback-loop.js +255 -89
  98. package/scripts/feedback-paths.js +8 -1
  99. package/scripts/feedback-sanitizer.js +5 -0
  100. package/scripts/feedback-scope.js +106 -0
  101. package/scripts/feedback-session.js +8 -2
  102. package/scripts/filesystem-search.js +13 -8
  103. package/scripts/financial-control-plane.js +707 -45
  104. package/scripts/gate-stats.js +38 -5
  105. package/scripts/gates-engine.js +1326 -240
  106. package/scripts/generate-eval-scorecard.js +0 -1
  107. package/scripts/gitlab-sdlc-prompts.js +397 -0
  108. package/scripts/harness-tool-names.js +31 -5
  109. package/scripts/hook-runtime.js +10 -0
  110. package/scripts/hybrid-feedback-context.js +7 -2
  111. package/scripts/intervention-policy.js +2 -1
  112. package/scripts/lesson-canonical.js +2 -2
  113. package/scripts/lesson-db.js +55 -14
  114. package/scripts/lesson-graph.js +2 -1
  115. package/scripts/lesson-retrieval.js +95 -9
  116. package/scripts/lesson-search.js +86 -22
  117. package/scripts/lesson-synthesis.js +21 -5
  118. package/scripts/mabl-failure-honesty.js +273 -0
  119. package/scripts/mailer/index.js +17 -1
  120. package/scripts/mailer/resend-mailer.js +213 -179
  121. package/scripts/migrate-project-scope.js +209 -0
  122. package/scripts/model-distress-detector.js +3 -3
  123. package/scripts/operational-integrity.js +436 -3
  124. package/scripts/override-audit.js +2 -0
  125. package/scripts/owner-admin.js +338 -0
  126. package/scripts/pr-manager.js +194 -1
  127. package/scripts/product-feedback.js +35 -0
  128. package/scripts/progressive-signoff.js +260 -0
  129. package/scripts/project-catalog.js +243 -0
  130. package/scripts/project-dashboard.js +61 -0
  131. package/scripts/project-evidence.js +172 -0
  132. package/scripts/project-identity.js +182 -0
  133. package/scripts/project-scope.js +381 -0
  134. package/scripts/prompt-eval.js +1 -1
  135. package/scripts/prompt-guard.js +446 -52
  136. package/scripts/proof-report.js +232 -0
  137. package/scripts/provider-action-normalizer.js +14 -6
  138. package/scripts/qwenwork-policy-group.js +413 -0
  139. package/scripts/rate-limiter.js +41 -0
  140. package/scripts/secret-redaction.js +171 -25
  141. package/scripts/secret-scanner.js +101 -42
  142. package/scripts/self-protection.js +2 -2
  143. package/scripts/seo-gsd.js +14 -14
  144. package/scripts/session-context-dedupe.js +66 -0
  145. package/scripts/settings-hierarchy.js +4 -2
  146. package/scripts/statusline-meta.js +34 -23
  147. package/scripts/tailscale-october-access.js +416 -0
  148. package/scripts/task-outcomes.js +58 -2
  149. package/scripts/telemetry-analytics.js +260 -16
  150. package/scripts/thumbgate-search.js +23 -9
  151. package/scripts/tool-kpi-tracker.js +5 -2
  152. package/scripts/tool-registry.js +42 -1
  153. package/scripts/triage-savings-calculator.js +1 -1
  154. package/scripts/vector-store.js +4 -1
  155. package/scripts/verified-lessons.js +270 -0
  156. package/scripts/verify-marketing-pages-deployed.js +2 -2
  157. package/scripts/workflow-sentinel.js +29 -10
  158. package/server.json +2 -2
  159. package/src/api/server.js +2478 -470
  160. package/src/feedback.js +21 -0
  161. package/src/hermes-sync-plane.js +2 -1
  162. package/src/index.js +2 -0
  163. package/src/lesson-search.js +9 -0
  164. package/src/mckinsey-top-company-ai-coding.js +493 -0
  165. package/src/mcp/email-triage-server/index.js +973 -0
  166. package/src/mcp/email-triage-server/package.json +12 -0
  167. package/src/mcp/server.js +3 -0
  168. package/src/mcp-writeguard.js +772 -11
  169. package/src/openshell-lovable-engine.js +1475 -0
  170. package/src/task-outcome.js +3 -0
  171. package/config/evals/agent-safety-eval.json +0 -447
  172. package/config/evals/retrieval-ranking-golden.json +0 -522
  173. package/config/progressive/01-wire-only.json +0 -11
  174. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  175. package/config/progressive/03-one-lesson.json +0 -10
  176. package/config/progressive/04-warn-fires.json +0 -11
  177. package/config/progressive/05-strict-optional.json +0 -11
  178. package/config/progressive/README.md +0 -15
  179. package/public/assets/diagrams/agent-integration.png +0 -0
  180. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -73,6 +73,10 @@ function normalizeWindow(value) {
73
73
  case '30days':
74
74
  case '30-day':
75
75
  return '30d';
76
+ case '90':
77
+ case '90days':
78
+ case '90-day':
79
+ return '90d';
76
80
  default:
77
81
  return normalized;
78
82
  }
@@ -95,7 +99,7 @@ function resolveAnalyticsWindow(options = {}) {
95
99
  }
96
100
 
97
101
  const window = normalizeWindow(options.window);
98
- if (!['lifetime', 'today', '7d', '30d'].includes(window)) {
102
+ if (!['lifetime', 'today', '7d', '30d', '90d'].includes(window)) {
99
103
  const err = new Error(`Invalid analytics window: ${window}`);
100
104
  err.code = 'invalid_window';
101
105
  throw err;
@@ -112,6 +116,8 @@ function resolveAnalyticsWindow(options = {}) {
112
116
  startLocalDate = shiftLocalDate(endLocalDate, -6);
113
117
  } else if (window === '30d') {
114
118
  startLocalDate = shiftLocalDate(endLocalDate, -29);
119
+ } else if (window === '90d') {
120
+ startLocalDate = shiftLocalDate(endLocalDate, -89);
115
121
  }
116
122
 
117
123
  return {
@@ -1,6 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ const { tenantDataScope, assertScopedDataPath, restrictedWorkerEnv, withDataScope } = require('./feedback-scope');
4
+
3
5
  const fs = require('fs');
6
+ const { randomUUID } = require('node:crypto');
4
7
  const path = require('path');
5
8
  const { spawnSync } = require('child_process');
6
9
 
@@ -25,7 +28,7 @@ function nowIso() {
25
28
  }
26
29
 
27
30
  function generateJobId() {
28
- return `job_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
31
+ return `job_${Date.now()}_${randomUUID()}`;
29
32
  }
30
33
 
31
34
  function readJson(filePath) {
@@ -39,7 +42,13 @@ function readJson(filePath) {
39
42
 
40
43
  function writeJson(filePath, value) {
41
44
  ensureDir(path.dirname(filePath));
42
- fs.writeFileSync(filePath, JSON.stringify(value, null, 2) + '\n', 'utf8');
45
+ const serialized = JSON.stringify(value, null, 2) + '\n';
46
+ const temporary = assertScopedDataPath(`${filePath}.${process.pid}.${randomUUID()}.tmp`);
47
+ const descriptor = fs.openSync(temporary, 'wx', 0o600);
48
+ try {
49
+ try { fs.writeFileSync(descriptor, serialized, 'utf8'); } finally { fs.closeSync(descriptor); }
50
+ fs.renameSync(temporary, filePath);
51
+ } finally { fs.rmSync(temporary, { force: true }); }
43
52
  }
44
53
 
45
54
  function appendJSONL(filePath, record) {
@@ -48,16 +57,19 @@ function appendJSONL(filePath, record) {
48
57
  }
49
58
 
50
59
  function getJobRuntimePaths(jobId) {
60
+ if (jobId && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,159}$/.test(jobId)) {
61
+ const error = new Error('Invalid job identifier'); error.statusCode = 400; throw error;
62
+ }
51
63
  const { FEEDBACK_DIR } = getFeedbackPaths();
52
- const jobsDir = path.join(FEEDBACK_DIR, JOB_STATE_DIRNAME);
53
- const jobDir = jobId ? path.join(jobsDir, jobId) : null;
64
+ const jobsDir = assertScopedDataPath(path.join(FEEDBACK_DIR, JOB_STATE_DIRNAME));
65
+ const jobDir = jobId ? assertScopedDataPath(path.join(jobsDir, jobId)) : null;
54
66
  return {
55
67
  feedbackDir: FEEDBACK_DIR,
56
68
  jobsDir,
57
69
  jobDir,
58
- statePath: jobDir ? path.join(jobDir, 'state.json') : null,
59
- controlPath: jobDir ? path.join(jobDir, JOB_CONTROL_FILENAME) : null,
60
- logPath: path.join(FEEDBACK_DIR, JOB_LOG_FILENAME),
70
+ statePath: jobDir ? assertScopedDataPath(path.join(jobDir, 'state.json')) : null,
71
+ controlPath: jobDir ? assertScopedDataPath(path.join(jobDir, JOB_CONTROL_FILENAME)) : null,
72
+ logPath: assertScopedDataPath(path.join(FEEDBACK_DIR, JOB_LOG_FILENAME)),
61
73
  };
62
74
  }
63
75
 
@@ -137,6 +149,7 @@ function serializeJobForState(job) {
137
149
  }
138
150
 
139
151
  function queueJob(job) {
152
+ assertTenantJob(job);
140
153
  const normalizedJob = {
141
154
  ...job,
142
155
  id: job.id || generateJobId(),
@@ -198,7 +211,7 @@ function listJobStates(options = {}) {
198
211
  : null;
199
212
 
200
213
  const results = fs.readdirSync(jobsDir)
201
- .map((entry) => readJson(path.join(jobsDir, entry, 'state.json')))
214
+ .map((entry) => readJson(assertScopedDataPath(path.join(jobsDir, entry, 'state.json'))))
202
215
  .filter(Boolean)
203
216
  .filter((entry) => !statuses || statuses.has(entry.status))
204
217
  .sort((left, right) => {
@@ -576,7 +589,7 @@ function runCommandStage(stage) {
576
589
  const tokens = parseCommandArgv(stage.command);
577
590
  const result = spawnSync(tokens[0], tokens.slice(1), {
578
591
  cwd: stage.workingDirectory || process.cwd(),
579
- env: process.env,
592
+ env: restrictedWorkerEnv(),
580
593
  encoding: 'utf8',
581
594
  stdio: 'pipe',
582
595
  shell: false,
@@ -842,7 +855,26 @@ function resumeJob(jobId, job = null, options = {}) {
842
855
  * @param {object} job
843
856
  * @returns {object} Job execution result
844
857
  */
858
+ function assertTenantJob(job) {
859
+ if (!tenantDataScope()) return;
860
+ const denied = () => { const error = new Error('Hosted tenant jobs require a verified fixed export or an execution sandbox'); error.statusCode = 403; throw error; };
861
+ if (job.skill !== 'hosted-dpo-export' || job.recordFeedback !== false || job.autoImprove !== false || job.verificationMode !== 'none' || job.taskFn || !Array.isArray(job.stages) || job.stages.length !== 1) denied();
862
+ const stage = job.stages[0];
863
+ if (stage.taskFn || stage.run || typeof stage.command !== 'string') denied();
864
+ const args = parseCommandArgv(stage.command);
865
+ if (args[0] !== process.execPath || args[1] !== path.join(__dirname, 'managed-dpo-export.js')) denied();
866
+ let inputCount = 0;
867
+ for (let index = 2; index < args.length; index += 2) {
868
+ if (!['--inputPath', '--memoryLogPath', '--outputPath'].includes(args[index]) || !args[index + 1]) denied();
869
+ assertScopedDataPath(args[index + 1]);
870
+ if (args[index] !== '--outputPath') inputCount += 1;
871
+ }
872
+ if (inputCount !== 1) denied();
873
+ if (stage.workingDirectory) assertScopedDataPath(stage.workingDirectory);
874
+ }
875
+
845
876
  function executeJob(job, options = {}) {
877
+ assertTenantJob(job);
846
878
  const started = Date.now();
847
879
  const normalizedJob = {
848
880
  ...job,
@@ -1052,7 +1084,7 @@ function executeJob(job, options = {}) {
1052
1084
  }
1053
1085
 
1054
1086
  function runJobFromFile(jobFilePath, options = {}) {
1055
- const resolvedPath = path.resolve(jobFilePath);
1087
+ const resolvedPath = assertScopedDataPath(path.resolve(jobFilePath));
1056
1088
  const spec = readJson(resolvedPath);
1057
1089
  if (!spec) {
1058
1090
  throw new Error(`Unable to read job file: ${resolvedPath}`);
@@ -1118,6 +1150,7 @@ function runBatch(jobs) {
1118
1150
 
1119
1151
  module.exports = {
1120
1152
  recallContext,
1153
+ assertTenantJob,
1121
1154
  executeJob,
1122
1155
  queueJob,
1123
1156
  runBatch,
@@ -1125,6 +1158,7 @@ module.exports = {
1125
1158
  readJobLog,
1126
1159
  getJobStats,
1127
1160
  readJobState,
1161
+ writeJobState,
1128
1162
  listJobStates,
1129
1163
  readJobControl,
1130
1164
  requestJobControl,
@@ -1140,14 +1174,17 @@ module.exports = {
1140
1174
  JOB_STATE_DIRNAME,
1141
1175
  };
1142
1176
 
1143
- if (require.main === module) {
1177
+ function parseCliArguments() {
1144
1178
  const args = {};
1145
1179
  process.argv.slice(2).forEach((arg) => {
1146
1180
  if (!arg.startsWith('--')) return;
1147
1181
  const [key, ...rest] = arg.slice(2).split('=');
1148
1182
  args[key] = rest.length > 0 ? rest.join('=') : true;
1149
1183
  });
1184
+ return args;
1185
+ }
1150
1186
 
1187
+ function runControlCliCommand(args) {
1151
1188
  if (args.pause) {
1152
1189
  console.log(JSON.stringify(requestJobControl(args.pause, 'pause'), null, 2));
1153
1190
  process.exit(0);
@@ -1170,6 +1207,9 @@ if (require.main === module) {
1170
1207
  process.exit(result.failed > 0 || result.cancelled > 0 ? 1 : 0);
1171
1208
  }
1172
1209
 
1210
+ }
1211
+
1212
+ function runHarnessCliCommand(args) {
1173
1213
  if (args['list-harnesses']) {
1174
1214
  const { listHarnesses } = require('./natural-language-harness');
1175
1215
  console.log(JSON.stringify({ harnesses: listHarnesses({ tag: args.tag }) }, null, 2));
@@ -1194,6 +1234,13 @@ if (require.main === module) {
1194
1234
  process.exit(['failed', 'cancelled'].includes(result.status) ? 1 : 0);
1195
1235
  }
1196
1236
 
1237
+ }
1238
+
1239
+ function runCli() {
1240
+ const args = parseCliArguments();
1241
+ runControlCliCommand(args);
1242
+ runHarnessCliCommand(args);
1243
+
1197
1244
  if (args['run-file']) {
1198
1245
  const result = runJobFromFile(args['run-file']);
1199
1246
  console.log(JSON.stringify(result, null, 2));
@@ -1240,3 +1287,11 @@ if (require.main === module) {
1240
1287
  node scripts/async-job-runner.js --stats
1241
1288
  node scripts/async-job-runner.js --log --limit=10`);
1242
1289
  }
1290
+
1291
+ if (require.main === module) {
1292
+ if (process.env.THUMBGATE_WORKER_SCOPE) {
1293
+ withDataScope(JSON.parse(process.env.THUMBGATE_WORKER_SCOPE), runCli);
1294
+ } else {
1295
+ runCli();
1296
+ }
1297
+ }
@@ -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 [];
@@ -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
  }