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,13 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
+ const { resolveLocalProject, projectForRecord, gateAppliesToProject, validProjectKey } = require('./project-identity');
4
+ function gateExecution(toolInput = {}, options = {}) {
5
+ const descriptor = options.projectKey ? projectForRecord(options) : tenantDataScope() ? projectForRecord({ projectKey: 'unassigned' }) : resolveLocalProject(toolInput?.cwd || options.cwd || process.cwd());
6
+ return { ...options, ...descriptor };
7
+ }
8
+ function accountStatePath(name, fallback, options = {}) { return assertScopedDataPath(options.feedbackDir ? path.join(options.feedbackDir, name) : fallback); }
9
+
10
+ const { tenantDataScope, scopedStatePath, assertScopedDataPath } = require('./feedback-scope');
3
11
 
4
12
  const fs = require('fs');
5
13
  const path = require('path');
@@ -12,7 +20,9 @@ const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES, FREE_TIER_DAILY_BLOCKS,
12
20
  const {
13
21
  DEFAULT_BASE_BRANCH,
14
22
  evaluateOperationalIntegrity,
23
+ isDestructiveDeleteCommand,
15
24
  } = require('./operational-integrity');
25
+ const { canonicalizeToolCall } = require('./harness-tool-names');
16
26
  const {
17
27
  evaluateWorkflowSentinel,
18
28
  } = require('./workflow-sentinel');
@@ -137,7 +147,7 @@ const DEFAULT_PROTECTED_FILE_GLOBS = [
137
147
  'SKILL.md',
138
148
  'config/gates/**',
139
149
  ];
140
- const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit']);
150
+ const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
141
151
  const HIGH_RISK_BASH_PATTERN = /\b(?:git\s+(?:add|commit|push)|gh\s+pr\s+(?:create|merge)|npm\s+publish|yarn\s+publish|pnpm\s+publish|rm\s+-rf)\b/i;
142
152
  const REMOTE_SIDE_EFFECT_BASH_PATTERN = /\b(?:git\s+push\b|gh\s+pr\s+(?:create|merge|close|reopen|ready|edit)\b|gh\s+release\s+(?:create|delete|edit|upload)\b|npm\s+publish\b|yarn\s+publish\b|pnpm\s+publish\b)\b/i;
143
153
  const MAX_COMMAND_SCAN_CHARS = 20000;
@@ -199,6 +209,7 @@ const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
199
209
  // separately authenticated admin override bound to the exact action digest
200
210
  // authorizes one retry (AGENT-259 / District Cyber 2026-08-04).
201
211
  'outbound-email-send',
212
+ 'outbound-off-brand-vertical-block',
202
213
  'swarm-claim-exit-3-write-after-loss',
203
214
  'teams-single-reply-per-message',
204
215
  'az-repos-pr-publish-requires-cross-review',
@@ -229,6 +240,7 @@ const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
229
240
  'oneshot-goal-done',
230
241
  // Never daily-cap discount a denied autonomous email send (same class as force-push).
231
242
  'outbound-email-send',
243
+ 'outbound-off-brand-vertical-block',
232
244
  'swarm-claim-exit-3-write-after-loss',
233
245
  'teams-single-reply-per-message',
234
246
  'az-repos-pr-publish-requires-cross-review',
@@ -236,8 +248,8 @@ const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
236
248
  ]);
237
249
  const SELF_PROTECT_CONFIG_TARGET_PATTERN = /(?:^|\/)(?:config\/gates\/|config\/(?:budget|enforcement|mcp-allowlists)\.json$|\.thumbgate\/config\.json$|thumbgate\.json$)/i;
238
250
  const SELF_PROTECT_HOOK_TARGET_PATTERN = /(?:^|\/)(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^/]+\.(?:js|sh))$/i;
239
- const SELF_PROTECT_CONFIG_COMMAND_PATTERN = /(?:config\/gates\/|config\/(?:budget|enforcement|mcp-allowlists)\.json\b|\.thumbgate\/config\.json\b|thumbgate\.json\b)/i;
240
- const SELF_PROTECT_HOOK_COMMAND_PATTERN = /(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^\s'";|]+\.(?:js|sh))\b/i;
251
+ const SELF_PROTECT_CONFIG_COMMAND_PATTERN = /(?:config\/gates(?:\/|$|\b)|config\/(?:budget|enforcement|mcp-allowlists)\.json\b|\.thumbgate\/config\.json\b|thumbgate\.json\b)/i;
252
+ const SELF_PROTECT_HOOK_COMMAND_PATTERN = /(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^/\s'";|]+\.(?:js|sh))\b/i;
241
253
  const SHELL_FILE_MUTATION_PATTERN = /\b(?:sed\s+-i|perl\s+-pi|python\d*\s+-c|node\s+-e|ruby\s+-e|tee|truncate|rm|mv|cp|install|patch|jq)\b|(?:^|[\s;&|])>{1,2}\s*\S/i;
242
254
 
243
255
  function isSelfProtectGate(gateId) {
@@ -422,8 +434,9 @@ function isRecursiveChmodCommand(command) {
422
434
  // Config loading
423
435
  // ---------------------------------------------------------------------------
424
436
 
425
- function loadGatesConfig(configPath, harnessPath) {
426
- const primaryPath = configPath || process.env.THUMBGATE_GATES_CONFIG || DEFAULT_CONFIG_PATH;
437
+ function loadGatesConfig(configPath, harnessPath, options = {}) {
438
+ if (tenantDataScope()) { configPath = undefined; harnessPath = undefined; }
439
+ const primaryPath = tenantDataScope() ? DEFAULT_CONFIG_PATH : (configPath || process.env.THUMBGATE_GATES_CONFIG || DEFAULT_CONFIG_PATH);
427
440
 
428
441
  if (!fs.existsSync(primaryPath)) {
429
442
  throw new Error(`Gates config not found: ${primaryPath}`);
@@ -452,9 +465,11 @@ function loadGatesConfig(configPath, harnessPath) {
452
465
 
453
466
  // Always preserve the full primary/default safety policy. Free tier limits apply
454
467
  // only to auto-promoted add-on gates so core protections never disappear.
455
- const autoConfigPath = getAutoGatesPath();
468
+ const autoConfigPath = getAutoGatesPath(options);
456
469
  if (!configPath && fs.existsSync(autoConfigPath)) {
457
- const autoGates = loadOne(autoConfigPath, false).map(g => ({ ...g, layer: g.layer || 'Execution' }));
470
+ const autoGates = loadOne(autoConfigPath, false).map(g => ({ ...g, scope: 'project', projectKey: g.projectKey || 'unassigned', legacyUnscoped: g.projectKey && g.projectKey !== 'unassigned' ? g.legacyUnscoped : true, layer: g.layer || 'Execution' }));
471
+ const legacyUnscoped = autoGates.filter((g) => g.legacyUnscoped).length;
472
+ if (legacyUnscoped && !globalThis.__thumbgateLegacyGateNotice) { globalThis.__thumbgateLegacyGateNotice = true; process.stderr.write('[thumbgate] ' + legacyUnscoped + ' auto-promoted gate(s) have no recorded project and apply in every project until assigned.\n'); }
458
473
  const limitedAutoGates = isProTier()
459
474
  ? autoGates
460
475
  : autoGates.slice(0, FREE_TIER_MAX_GATES);
@@ -463,7 +478,7 @@ function loadGatesConfig(configPath, harnessPath) {
463
478
 
464
479
  // Load workflow-specific harness gates (always additive, never replaces default).
465
480
  // Resolved by harness-selector based on tool name + command context.
466
- const resolvedHarness = harnessPath || process.env.THUMBGATE_HARNESS_CONFIG;
481
+ const resolvedHarness = tenantDataScope() ? null : (harnessPath || process.env.THUMBGATE_HARNESS_CONFIG);
467
482
  if (resolvedHarness && fs.existsSync(resolvedHarness)) {
468
483
  const harnessGates = (loadOne(resolvedHarness, false) || [])
469
484
  .map(g => ({ ...g, layer: g.layer || 'Execution', source: g.source || 'harness' }));
@@ -487,12 +502,13 @@ function loadJSON(filePath) {
487
502
  }
488
503
 
489
504
  function saveJSON(filePath, data) {
505
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return;
490
506
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
491
507
  fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n');
492
508
  }
493
509
 
494
- function loadState() { return loadJSON(module.exports.STATE_PATH); }
495
- function saveState(state) { saveJSON(module.exports.STATE_PATH, state); }
510
+ function loadState(options = {}) { return loadJSON(accountStatePath('gate-state.json', module.exports.STATE_PATH, options)); }
511
+ function saveState(state, options = {}) { saveJSON(accountStatePath('gate-state.json', module.exports.STATE_PATH, options), state); }
496
512
 
497
513
  function loadConstraints() { return loadJSON(module.exports.CONSTRAINTS_PATH); }
498
514
  function saveConstraints(constraints) { saveJSON(module.exports.CONSTRAINTS_PATH, constraints); }
@@ -676,10 +692,11 @@ function stableCanonicalStringify(value) {
676
692
  )).join(',')}}`;
677
693
  }
678
694
 
679
- function actionApprovalDigest(toolName, toolInput) {
695
+ function actionApprovalDigest(toolName, toolInput, options = {}) {
680
696
  return crypto.createHash('sha256').update(stableCanonicalStringify({
681
697
  toolInput: toolInput && typeof toolInput === 'object' ? toolInput : {},
682
698
  toolName: String(toolName || ''),
699
+ projectKey: gateExecution(toolInput, options).projectKey,
683
700
  })).digest('hex');
684
701
  }
685
702
 
@@ -687,8 +704,8 @@ function adminOverrideTaskId(gateId, digest) {
687
704
  return `admin-override:${gateId}:${digest}`;
688
705
  }
689
706
 
690
- function selectAdminOverrideAttempt(baseTaskId) {
691
- const attempts = listEscalations().filter((entry) => (
707
+ function selectAdminOverrideAttempt(baseTaskId, options = {}) {
708
+ const attempts = listEscalations(options).filter((entry) => (
692
709
  entry.taskId === baseTaskId || String(entry.taskId || '').startsWith(`${baseTaskId}:attempt:`)
693
710
  ));
694
711
  const latest = attempts[0] || null;
@@ -704,15 +721,15 @@ function selectAdminOverrideAttempt(baseTaskId) {
704
721
  return `${baseTaskId}:attempt:${highestAttempt + 1}`;
705
722
  }
706
723
 
707
- function evaluateAdminOverride(gate, toolName, toolInput) {
724
+ function evaluateAdminOverride(gate, toolName, toolInput, options = {}) {
708
725
  const policy = gate && gate.adminOverride;
709
726
  if (!policy || policy.required !== true) return null;
710
727
 
711
- const approvalContextDigest = actionApprovalDigest(toolName, toolInput);
728
+ const approvalContextDigest = actionApprovalDigest(toolName, toolInput, options);
712
729
  const baseTaskId = adminOverrideTaskId(gate.id, approvalContextDigest);
713
730
  let taskId;
714
731
  try {
715
- taskId = selectAdminOverrideAttempt(baseTaskId);
732
+ taskId = selectAdminOverrideAttempt(baseTaskId, options);
716
733
  } catch {
717
734
  return {
718
735
  authorized: false,
@@ -738,7 +755,7 @@ function evaluateAdminOverride(gate, toolName, toolInput) {
738
755
  idempotencyKey: taskId,
739
756
  approvalContextDigest,
740
757
  requiredReviewerRole: 'admin',
741
- });
758
+ }, options);
742
759
  } catch {
743
760
  return {
744
761
  authorized: false,
@@ -752,6 +769,7 @@ function evaluateAdminOverride(gate, toolName, toolInput) {
752
769
  let consumption = null;
753
770
  try {
754
771
  consumption = consumeVerifiedApproval(escalationId, {
772
+ ...options,
755
773
  consumer: { id: 'thumbgate-gates-engine', kind: 'service' },
756
774
  });
757
775
  } catch {
@@ -975,16 +993,19 @@ function refreshLocalOnlyConstraint(governanceState = loadGovernanceState()) {
975
993
  }
976
994
  }
977
995
 
978
- function isConditionSatisfied(conditionId) {
979
- const state = loadState();
980
- const entry = state[conditionId];
996
+ function isConditionSatisfied(conditionId, options = {}) {
997
+ options = gateExecution({}, options);
998
+ const state = loadState(options);
999
+ const projectKey = options.projectKey || 'unassigned';
1000
+ const entry = state.satisfiedByProject?.[projectKey]?.[conditionId] || (projectKey === 'unassigned' ? state[conditionId] : null);
981
1001
  if (!entry) return false;
982
1002
  const age = Date.now() - entry.timestamp;
983
1003
  return age < TTL_MS;
984
1004
  }
985
1005
 
986
1006
  function satisfyCondition(conditionId, evidence, structuredReasoning, options = {}) {
987
- const state = loadState();
1007
+ options = gateExecution({}, options);
1008
+ const state = loadState(options);
988
1009
  const entry = {
989
1010
  timestamp: Date.now(),
990
1011
  evidence: evidence || '',
@@ -997,8 +1018,12 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
997
1018
  conclusion: structuredReasoning.conclusion || null,
998
1019
  };
999
1020
  }
1000
- state[conditionId] = entry;
1001
- saveState(state);
1021
+ const projectKey = options.projectKey || 'unassigned';
1022
+ if (!validProjectKey(projectKey)) throw new Error('Invalid project key');
1023
+ state.satisfiedByProject ||= {};
1024
+ state.satisfiedByProject[projectKey] ||= {};
1025
+ state.satisfiedByProject[projectKey][conditionId] = entry;
1026
+ saveState(state, options);
1002
1027
 
1003
1028
  // Satisfying a gate condition IS an override: it unlocks an action the gate
1004
1029
  // had blocked. Previously this wrote only to the state store, so an override
@@ -1010,6 +1035,7 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
1010
1035
  // already loads; requiring at call time avoids any circular-init surprise.
1011
1036
  const { recordOverride } = require('./override-audit');
1012
1037
  recordOverride({
1038
+ ...options,
1013
1039
  gateId: conditionId,
1014
1040
  source: options.source || 'cli',
1015
1041
  actor: options.actor,
@@ -1028,13 +1054,13 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
1028
1054
  // Stats tracking
1029
1055
  // ---------------------------------------------------------------------------
1030
1056
 
1031
- function loadStats() {
1032
- const stats = loadJSON(module.exports.STATS_PATH);
1057
+ function loadStats(options = {}) {
1058
+ const stats = loadJSON(accountStatePath('gate-stats.json', module.exports.STATS_PATH, options));
1033
1059
  if (Object.keys(stats).length === 0) return { blocked: 0, warned: 0, passed: 0, byGate: {} };
1034
1060
  return stats;
1035
1061
  }
1036
1062
 
1037
- function saveStats(stats) { saveJSON(module.exports.STATS_PATH, stats); }
1063
+ function saveStats(stats, options = {}) { saveJSON(accountStatePath('gate-stats.json', module.exports.STATS_PATH, options), stats); }
1038
1064
 
1039
1065
  function buildGateActionFingerprint(gateId, options = {}) {
1040
1066
  if (options.actionFingerprint) return String(options.actionFingerprint);
@@ -1055,13 +1081,28 @@ function buildGateActionFingerprint(gateId, options = {}) {
1055
1081
  );
1056
1082
  if (Array.isArray(toolInput.affectedFiles)) parts.push(...toolInput.affectedFiles);
1057
1083
  }
1058
- return actionFingerprint(parts);
1084
+ const fingerprint = actionFingerprint(parts);
1085
+ return fingerprint ? `${options.projectKey || 'unassigned'}:${fingerprint}` : null;
1059
1086
  }
1060
1087
 
1061
1088
  function recordStat(gateId, action, gate, options = {}) {
1062
- const stats = loadStats();
1063
- if (action === 'block') stats.blocked = (stats.blocked || 0) + 1;
1064
- else if (action === 'warn') stats.warned = (stats.warned || 0) + 1;
1089
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return;
1090
+ options = gateExecution(options.toolInput, options);
1091
+ const stats = loadStats(options);
1092
+ stats.byProject ||= {};
1093
+ const bucket = stats.byProject[options.projectKey] ||= { blocked: 0, warned: 0, passed: 0, byGate: {} };
1094
+ const metric = action === 'block' ? 'blocked' : action === 'warn' ? 'warned' : 'passed';
1095
+ bucket[metric]++;
1096
+ const gateBucket = bucket.byGate[gateId] ||= { blocked: 0, warned: 0, passed: 0 };
1097
+ gateBucket[metric]++;
1098
+ if (action === 'block') {
1099
+ stats.blocked = (stats.blocked || 0) + 1;
1100
+ try {
1101
+ const { reportFirstBlockActivation } = require('./activation-tracker');
1102
+ reportFirstBlockActivation({ gateId });
1103
+ } catch { /* activation report is best-effort */ }
1104
+ } else if (action === 'warn') stats.warned = (stats.warned || 0) + 1;
1105
+
1065
1106
  else if (action === 'approve') stats.pendingApproval = (stats.pendingApproval || 0) + 1;
1066
1107
  else if (action === 'log') stats.logged = (stats.logged || 0) + 1;
1067
1108
  else stats.passed = (stats.passed || 0) + 1;
@@ -1078,7 +1119,7 @@ function recordStat(gateId, action, gate, options = {}) {
1078
1119
  if (action === 'block' || action === 'warn') {
1079
1120
  if (!stats.sessionFiredGates) stats.sessionFiredGates = {};
1080
1121
  if (!stats.sessionFiredActions) stats.sessionFiredActions = {};
1081
- const sessionKey = `session_${Math.floor(Date.now() / SESSION_ACTION_TTL_MS)}`;
1122
+ const sessionKey = `session_${options.projectKey}_${Math.floor(Date.now() / SESSION_ACTION_TTL_MS)}`;
1082
1123
  if (!stats.sessionFiredGates[sessionKey]) stats.sessionFiredGates[sessionKey] = {};
1083
1124
  stats.sessionFiredGates[sessionKey][gateId] = true;
1084
1125
 
@@ -1094,13 +1135,13 @@ function recordStat(gateId, action, gate, options = {}) {
1094
1135
  }
1095
1136
  }
1096
1137
 
1097
- saveStats(stats);
1138
+ saveStats(stats, options);
1098
1139
  // Track lesson freshness when an auto-promoted gate fires
1099
1140
  if (gate && gate.sourceLessonId) {
1100
1141
  try {
1101
1142
  const { recordTrigger } = require('./lesson-rotation');
1102
1143
  const { initDB } = require('./lesson-db');
1103
- const db = initDB();
1144
+ const db = initDB(options.feedbackDir ? path.join(options.feedbackDir, 'lessons.sqlite') : undefined);
1104
1145
  recordTrigger(db, gate.sourceLessonId);
1105
1146
  db.close();
1106
1147
  } catch (_) { /* lesson DB may not be available */ }
@@ -1145,6 +1186,7 @@ function incrementTodayBlockCount() {
1145
1186
  * a deny result to a warn with an upgrade CTA. Returns null if no cap applies.
1146
1187
  */
1147
1188
  function applyDailyBlockCap(denyResult) {
1189
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
1148
1190
  // Catastrophic/irreversible commands (force-push, git reset --hard, git
1149
1191
  // clean -f, rm -rf on home/root) never get the free-tier daily-cap
1150
1192
  // discount — see issue #2782. Checked first, before any tier/CI shortcut,
@@ -1374,6 +1416,8 @@ function collectInlineAffectedFiles(toolInput = {}, repoRoot) {
1374
1416
  const scalarFields = [
1375
1417
  toolInput.file_path,
1376
1418
  toolInput.filePath,
1419
+ toolInput.notebook_path,
1420
+ toolInput.notebookPath,
1377
1421
  toolInput.path,
1378
1422
  ];
1379
1423
  for (const field of scalarFields) {
@@ -1741,6 +1785,7 @@ function patternMatchesCommand(regex, matchText) {
1741
1785
  }
1742
1786
 
1743
1787
  function extractAffectedFiles(toolName, toolInput = {}) {
1788
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return { repoRoot: null, files: [] };
1744
1789
  const repoRoot = resolveRepoRoot(toolInput);
1745
1790
  const files = new Set(collectInlineAffectedFiles(toolInput, repoRoot));
1746
1791
  // Full canonicalization, not just the git-option pass: `"git" add .` and `sudo git add .`
@@ -1802,7 +1847,7 @@ function isHighRiskAction(toolName, toolInput = {}, affectedFiles = []) {
1802
1847
  if (toolName !== 'Bash') return false;
1803
1848
  const command = String(toolInput.command || '');
1804
1849
  // Original high-risk pattern (git writes, publishes, destructive ops)
1805
- if (HIGH_RISK_BASH_PATTERN.test(command)) return true;
1850
+ if (HIGH_RISK_BASH_PATTERN.test(command) || isDestructiveDeleteCommand(command)) return true;
1806
1851
  if (isGhApiPrCreateCommand(command)) return true;
1807
1852
  // Broadened: any Bash command that modifies files or has side effects.
1808
1853
  // Excludes pure read/analysis commands (node --test, cat, ls, echo, etc.)
@@ -2094,9 +2139,9 @@ function registerPrThreadResolutionClaimGate(toolName, toolInput = {}, execOverr
2094
2139
  return claimGate;
2095
2140
  }
2096
2141
 
2097
- function isThreadResolutionSatisfied() {
2142
+ function isThreadResolutionSatisfied(options = {}) {
2098
2143
  return PR_THREAD_RESOLUTION_REQUIRED_ACTIONS.some((actionId) => (
2099
- hasAction(actionId) || isConditionSatisfied(actionId)
2144
+ hasAction(actionId) || isConditionSatisfied(actionId, options)
2100
2145
  ));
2101
2146
  }
2102
2147
 
@@ -2189,7 +2234,7 @@ function isReadOnlyObservabilityTool(toolName) {
2189
2234
  return names.has(toolName) || names.has(bareToolName(toolName));
2190
2235
  }
2191
2236
 
2192
- function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}) {
2237
+ function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}, options = {}) {
2193
2238
  const pendingEntry = loadSessionActions()[PR_THREAD_RESOLUTION_ACTION];
2194
2239
  if (!pendingEntry) return null;
2195
2240
 
@@ -2205,7 +2250,7 @@ function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}) {
2205
2250
  if (currentRepoRoot && currentRepoRoot !== trackedRepoRoot) return null;
2206
2251
  }
2207
2252
 
2208
- if (isThreadResolutionSatisfied()) return null;
2253
+ if (isThreadResolutionSatisfied(options)) return null;
2209
2254
  if (isReadOnlyObservabilityTool(toolName)) return null;
2210
2255
  // Evidence actions (gh pr view/checks/status, gh api .../reviewThreads, git
2211
2256
  // status/diff/show, the satisfy_gate/track_action tools themselves) are exempt
@@ -2398,9 +2443,9 @@ function evaluateStatefulHelperBypassGate(toolName, toolInput = {}) {
2398
2443
  return null;
2399
2444
  }
2400
2445
 
2401
- function recordStructuralGateBlock(toolName, toolInput, result) {
2402
- recordStat(result.gate, 'block', null, { toolName, toolInput });
2403
- const auditRecord = recordAuditEvent({
2446
+ function recordStructuralGateBlock(toolName, toolInput, result, options = {}) {
2447
+ recordStat(result.gate, 'block', null, { ...options, toolName, toolInput });
2448
+ const auditRecord = recordAuditEvent({ ...options,
2404
2449
  toolName,
2405
2450
  toolInput,
2406
2451
  decision: 'deny',
@@ -2409,7 +2454,7 @@ function recordStructuralGateBlock(toolName, toolInput, result) {
2409
2454
  severity: result.severity,
2410
2455
  source: 'gates-engine',
2411
2456
  });
2412
- auditToFeedback(auditRecord);
2457
+ auditToFeedback(auditRecord, options);
2413
2458
  return result;
2414
2459
  }
2415
2460
 
@@ -2426,7 +2471,7 @@ function recordStructuralGateBlock(toolName, toolInput, result) {
2426
2471
  * Metric-backed gates are excluded because their condition is asynchronous and
2427
2472
  * none of the catastrophic command boundaries may depend on a remote metric.
2428
2473
  */
2429
- function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, toolInput) {
2474
+ function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, toolInput, options = {}) {
2430
2475
  if (!config || !Array.isArray(config.gates)) return null;
2431
2476
 
2432
2477
  for (const gate of config.gates) {
@@ -2437,10 +2482,10 @@ function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, tool
2437
2482
  // still unconditional hard floors and cannot be posture/cap downgraded.
2438
2483
  if (gate.adminOverride && gate.adminOverride.required === true) continue;
2439
2484
 
2440
- const matchDetails = matchGate(gate, toolName, toolInput);
2485
+ const matchDetails = matchGate(gate, toolName, toolInput, options);
2441
2486
  if (!matchDetails.matched) continue;
2442
2487
  if (gate.when && !checkWhenClause(gate.when, constraints)) continue;
2443
- if (gate.unless && isConditionSatisfied(gate.unless)) continue;
2488
+ if (gate.unless && isConditionSatisfied(gate.unless, options)) continue;
2444
2489
 
2445
2490
  return {
2446
2491
  decision: 'deny',
@@ -2475,17 +2520,17 @@ function isAgentHookSettingsFile(filePath) {
2475
2520
  return matchesAnyGlob(filePath, BREAK_GLASS_SETTINGS_GLOBS);
2476
2521
  }
2477
2522
 
2478
- function isBreakGlassSettingsBypass(gate, affectedFiles) {
2523
+ function isBreakGlassSettingsBypass(gate, affectedFiles, options = {}) {
2479
2524
  if (!gate || !['task-scope-edit-boundary', 'protected-file-approval-required'].includes(gate.id)) {
2480
2525
  return false;
2481
2526
  }
2482
- if (!isConditionSatisfied(BREAK_GLASS_CONDITION)) return false;
2527
+ if (!isConditionSatisfied(BREAK_GLASS_CONDITION, options)) return false;
2483
2528
  return Array.isArray(affectedFiles) && affectedFiles.length > 0 && affectedFiles.every(isAgentHookSettingsFile);
2484
2529
  }
2485
2530
 
2486
- function isBreakGlassSettingsRecoveryAction(toolName, toolInput = {}) {
2531
+ function isBreakGlassSettingsRecoveryAction(toolName, toolInput = {}, options = {}) {
2487
2532
  if (!EDIT_LIKE_TOOLS.has(toolName)) return false;
2488
- if (!isConditionSatisfied(BREAK_GLASS_CONDITION)) return false;
2533
+ if (!isConditionSatisfied(BREAK_GLASS_CONDITION, options)) return false;
2489
2534
  const affectedFiles = extractAffectedFiles(toolName, toolInput).files;
2490
2535
  return affectedFiles.length > 0 && affectedFiles.every(isAgentHookSettingsFile);
2491
2536
  }
@@ -2780,10 +2825,19 @@ function buildMatchSurfaces(toolName, toolInput = {}) {
2780
2825
  push(v);
2781
2826
  if (name) push(`${name} ${v}`);
2782
2827
  }
2828
+ if (/(?:browseros[-_]neo|browser_(?:type|fill|navigate|click)|zernio|linkedin|bluesky|threads|reddit)/i.test(name)) {
2829
+ for (const key of ['code', 'text', 'value', 'post', 'caption']) {
2830
+ if (toolInput[key] == null) continue;
2831
+ const v = String(toolInput[key]).slice(0, 4000);
2832
+ push(v);
2833
+ if (name) push(`${name} ${v}`);
2834
+ }
2835
+ }
2783
2836
  return surfaces;
2784
2837
  }
2785
2838
 
2786
- function matchGate(gate, toolName, toolInput = {}) {
2839
+ function matchGate(gate, toolName, toolInput = {}, options = {}) {
2840
+ if (!gateAppliesToProject(gate, gateExecution(toolInput, options).projectKey)) return { matched: false };
2787
2841
  // Primary text for audit/reasoning: prefer command, then tool name (MCP).
2788
2842
  const matchSurfaces = buildMatchSurfaces(toolName, toolInput);
2789
2843
  let matchText = matchSurfaces[0] || String(toolName || '');
@@ -2823,16 +2877,30 @@ function matchGate(gate, toolName, toolInput = {}) {
2823
2877
  if (!matchSurfaces.includes(matchText)) matchSurfaces.push(matchText);
2824
2878
  }
2825
2879
 
2826
- const affected = extractAffectedFiles(toolName, toolInput);
2880
+ const affected = options.affected || extractAffectedFiles(toolName, toolInput);
2827
2881
  const affectedFiles = affected.files;
2828
2882
  const repoRoot = affected.repoRoot;
2829
- const governanceState = loadGovernanceState();
2830
- const constraints = loadConstraints();
2883
+ const governanceState = options.governanceState || loadGovernanceState();
2884
+ const constraints = options.constraints || loadConstraints();
2831
2885
 
2832
2886
  if (isSelfProtectGate(gate.id) && hasActiveProtectedApproval(governanceState, affectedFiles)) {
2833
2887
  return { matched: false, matchText, affectedFiles };
2834
2888
  }
2835
2889
 
2890
+ if (gate.id === 'self-protect-config' || gate.id === 'self-protect-hooks-disable') {
2891
+ const floorMatch = matchSelfProtectHardFloor(gate, toolName, toolInput);
2892
+ if (!floorMatch) {
2893
+ return { matched: false, matchText, affectedFiles };
2894
+ }
2895
+ return {
2896
+ matched: true,
2897
+ matchText: floorMatch.matchText || matchText,
2898
+ affectedFiles: floorMatch.affectedFiles || affectedFiles,
2899
+ taskScopeViolation: null,
2900
+ branchGovernanceViolation: null,
2901
+ };
2902
+ }
2903
+
2836
2904
  if (gate.id === 'on-demand-freeze-mode' || (gate.when && gate.when.constraints && gate.when.constraints.freeze_mode)) {
2837
2905
  let freezePaths = [];
2838
2906
  if (process.env.THUMBGATE_FREEZE_PATHS) {
@@ -2859,6 +2927,18 @@ function matchGate(gate, toolName, toolInput = {}) {
2859
2927
  return { matched: false, matchText, affectedFiles };
2860
2928
  }
2861
2929
 
2930
+ if (gate.id === 'outbound-off-brand-vertical-block') {
2931
+ if (EDIT_LIKE_TOOLS.has(toolName) || toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep' || toolName === 'LS') {
2932
+ return { matched: false, matchText, affectedFiles };
2933
+ }
2934
+ if (toolName === 'Bash') {
2935
+ const trimmedCmd = String(toolInput.command || '').trimStart();
2936
+ if (/^(?:git|rg|grep|ls|cat|head|tail|wc|find)\b/.test(trimmedCmd) || /^node\s+--test\b/.test(trimmedCmd) || /^npm\s+(?:test|run\s+test)\b/.test(trimmedCmd)) {
2937
+ return { matched: false, matchText, affectedFiles };
2938
+ }
2939
+ }
2940
+ }
2941
+
2862
2942
  if (gate.pattern) {
2863
2943
  try {
2864
2944
  if (gate.id === 'permission-change-approval') {
@@ -2883,7 +2963,7 @@ function matchGate(gate, toolName, toolInput = {}) {
2883
2963
  return { matched: false, matchText, affectedFiles };
2884
2964
  }
2885
2965
  }
2886
- if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
2966
+ if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
2887
2967
  return { matched: false, matchText, affectedFiles };
2888
2968
  }
2889
2969
  } catch {
@@ -2903,7 +2983,7 @@ function matchGate(gate, toolName, toolInput = {}) {
2903
2983
 
2904
2984
  let taskScopeViolation = null;
2905
2985
  if (gate.requireTaskScope) {
2906
- if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
2986
+ if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
2907
2987
  return { matched: false, matchText, affectedFiles };
2908
2988
  }
2909
2989
  if (!shouldEnforceTaskScope(gate, governanceState, toolName, toolInput, affectedFiles)) {
@@ -2915,7 +2995,7 @@ function matchGate(gate, toolName, toolInput = {}) {
2915
2995
 
2916
2996
  let protectedApprovalViolation = null;
2917
2997
  if (gate.requireProtectedApproval) {
2918
- if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
2998
+ if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
2919
2999
  return { matched: false, matchText, affectedFiles };
2920
3000
  }
2921
3001
  const protectedGlobs = sanitizeGlobList(
@@ -2952,8 +3032,8 @@ function matchGate(gate, toolName, toolInput = {}) {
2952
3032
  };
2953
3033
  }
2954
3034
 
2955
- function matchesGate(gate, toolName, toolInput) {
2956
- return matchGate(gate, toolName, toolInput).matched;
3035
+ function matchesGate(gate, toolName, toolInput, options = {}) {
3036
+ return matchGate(gate, toolName, toolInput, options).matched;
2957
3037
  }
2958
3038
 
2959
3039
  function hasActiveProtectedApproval(governanceState, affectedFiles) {
@@ -2966,6 +3046,300 @@ function hasActiveProtectedApproval(governanceState, affectedFiles) {
2966
3046
  }));
2967
3047
  }
2968
3048
 
3049
+ const HEREDOC_INTERPRETER_BINARIES = new Set([
3050
+ 'bash', 'sh', 'zsh', 'dash', 'ksh', 'python', 'python2', 'python3', 'node', 'perl', 'ruby',
3051
+ ]);
3052
+
3053
+ function parseHeredocHeaderLine(line) {
3054
+ let quote = null;
3055
+ for (let i = 0; i < line.length - 1; i += 1) {
3056
+ const ch = line[i];
3057
+ if (quote) {
3058
+ if (ch === '\\' && quote === '"' && i + 1 < line.length) {
3059
+ i += 1;
3060
+ } else if (ch === quote) {
3061
+ quote = null;
3062
+ }
3063
+ continue;
3064
+ }
3065
+ if (ch === '\'' || ch === '"') {
3066
+ quote = ch;
3067
+ continue;
3068
+ }
3069
+ if (ch === '<' && line[i + 1] === '<' && line[i + 2] !== '<') {
3070
+ let j = i + 2;
3071
+ if (line[j] === '-' || line[j] === '~') j += 1;
3072
+ while (j < line.length && (line[j] === ' ' || line[j] === '\t')) j += 1;
3073
+ if (j >= line.length) return null;
3074
+ let delim = '';
3075
+ if (line[j] === '\'' || line[j] === '"') {
3076
+ const q = line[j];
3077
+ j += 1;
3078
+ while (j < line.length && line[j] !== q) {
3079
+ delim += line[j];
3080
+ j += 1;
3081
+ }
3082
+ } else {
3083
+ if (line[j] === '\\') j += 1;
3084
+ while (j < line.length && !/[\s;&|<>]/.test(line[j])) {
3085
+ delim += line[j];
3086
+ j += 1;
3087
+ }
3088
+ }
3089
+ if (!delim) return null;
3090
+ const prefixTokens = tokenizeShellWords(line.slice(0, i));
3091
+ const invokesInterpreter = prefixTokens.some((tok) => {
3092
+ const base = tok.split('/').at(-1)?.toLowerCase() || '';
3093
+ return HEREDOC_INTERPRETER_BINARIES.has(base);
3094
+ });
3095
+ return { delim, invokesInterpreter };
3096
+ }
3097
+ }
3098
+ return null;
3099
+ }
3100
+
3101
+ function stripNonInterpreterHeredocBodies(command) {
3102
+ const lines = String(command || '').split(/\r?\n/);
3103
+ const kept = [];
3104
+ let activeHeredoc = null;
3105
+ for (const line of lines) {
3106
+ if (activeHeredoc) {
3107
+ if (line.trim() === activeHeredoc.delim) {
3108
+ activeHeredoc = null;
3109
+ } else if (activeHeredoc.invokesInterpreter) {
3110
+ kept.push(line);
3111
+ }
3112
+ continue;
3113
+ }
3114
+ kept.push(line);
3115
+ const parsed = parseHeredocHeaderLine(line);
3116
+ if (parsed) {
3117
+ activeHeredoc = parsed;
3118
+ }
3119
+ }
3120
+ return kept.join('\n');
3121
+ }
3122
+
3123
+ function splitSelfProtectShellSegments(command) {
3124
+ const segments = [];
3125
+ let current = '';
3126
+ let quote = null;
3127
+ for (let i = 0; i < command.length; i += 1) {
3128
+ const ch = command[i];
3129
+ if (quote) {
3130
+ current += ch;
3131
+ if (ch === '\\' && quote === '"' && i + 1 < command.length) {
3132
+ i += 1;
3133
+ current += command[i];
3134
+ } else if (ch === quote) {
3135
+ quote = null;
3136
+ }
3137
+ continue;
3138
+ }
3139
+ if (ch === '\'' || ch === '"') {
3140
+ quote = ch;
3141
+ current += ch;
3142
+ continue;
3143
+ }
3144
+ if (ch === '\\' && i + 1 < command.length) {
3145
+ current += ch + command[i + 1];
3146
+ i += 1;
3147
+ continue;
3148
+ }
3149
+ if ((ch === '&' && command[i + 1] === '&') || (ch === '|' && command[i + 1] === '|')) {
3150
+ segments.push(current);
3151
+ current = '';
3152
+ i += 1;
3153
+ continue;
3154
+ }
3155
+ if (ch === ';' || ch === '\n' || ch === '|') {
3156
+ segments.push(current);
3157
+ current = '';
3158
+ continue;
3159
+ }
3160
+ current += ch;
3161
+ }
3162
+ if (current) segments.push(current);
3163
+ return segments;
3164
+ }
3165
+
3166
+ function extractRedirectTargetsFromSegment(segment) {
3167
+ const targets = [];
3168
+ let cleaned = '';
3169
+ let quote = null;
3170
+ let i = 0;
3171
+ while (i < segment.length) {
3172
+ const ch = segment[i];
3173
+ if (quote) {
3174
+ cleaned += ch;
3175
+ if (ch === '\\' && quote === '"' && i + 1 < segment.length) {
3176
+ i += 1;
3177
+ cleaned += segment[i];
3178
+ } else if (ch === quote) {
3179
+ quote = null;
3180
+ }
3181
+ i += 1;
3182
+ continue;
3183
+ }
3184
+ if (ch === '\'' || ch === '"') {
3185
+ quote = ch;
3186
+ cleaned += ch;
3187
+ i += 1;
3188
+ continue;
3189
+ }
3190
+ if (ch === '\\' && i + 1 < segment.length) {
3191
+ cleaned += ch + segment[i + 1];
3192
+ i += 2;
3193
+ continue;
3194
+ }
3195
+ if (ch === '>') {
3196
+ const prev = i > 0 ? segment[i - 1] : '';
3197
+ if (prev === '-' || prev === '=' || prev === '<') {
3198
+ cleaned += ch;
3199
+ i += 1;
3200
+ continue;
3201
+ }
3202
+ let j = i + 1;
3203
+ if (segment[j] === '>' || segment[j] === '|') j += 1;
3204
+ if (segment[j] === '&') {
3205
+ j += 1;
3206
+ while (j < segment.length && /[0-9-]/.test(segment[j])) j += 1;
3207
+ i = j;
3208
+ continue;
3209
+ }
3210
+ while (j < segment.length && (segment[j] === ' ' || segment[j] === '\t')) j += 1;
3211
+ let target = '';
3212
+ while (j < segment.length && !/[\s;&|<>]/.test(segment[j])) {
3213
+ if (segment[j] === '\'' || segment[j] === '"') {
3214
+ const q = segment[j];
3215
+ j += 1;
3216
+ while (j < segment.length && segment[j] !== q) {
3217
+ if (segment[j] === '\\' && q === '"' && j + 1 < segment.length) {
3218
+ j += 1;
3219
+ }
3220
+ target += segment[j];
3221
+ j += 1;
3222
+ }
3223
+ if (j < segment.length && segment[j] === q) j += 1;
3224
+ } else if (segment[j] === '\\' && j + 1 < segment.length) {
3225
+ target += segment[j + 1];
3226
+ j += 2;
3227
+ } else {
3228
+ target += segment[j];
3229
+ j += 1;
3230
+ }
3231
+ }
3232
+ if (target) targets.push(target);
3233
+ cleaned += ' ';
3234
+ i = j;
3235
+ continue;
3236
+ }
3237
+ cleaned += ch;
3238
+ i += 1;
3239
+ }
3240
+ return { targets, cleaned };
3241
+ }
3242
+
3243
+ const INLINE_SCRIPT_WRITE_CALL_PATTERN = /(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|unlinkSync|rmSync|renameSync|copyFileSync|truncateSync|chmodSync|\.write\s*\(|open\s*\([^()\n]{0,120}['"][wa+]|os\.(?:remove|unlink|rename|replace)|shutil\.(?:copy|move)|\.write_text\s*\(|\.write_bytes\s*\(|File\.write|IO\.write)/;
3244
+
3245
+ function doesSegmentMutateProtectedTarget(segment, commandTargetPattern, depth = 0) {
3246
+ if (depth > 4) return false;
3247
+ const { targets, cleaned } = extractRedirectTargetsFromSegment(segment);
3248
+ if (targets.some((target) => commandTargetPattern.test(target))) {
3249
+ return true;
3250
+ }
3251
+
3252
+ const tokens = tokenizeShellWords(cleaned);
3253
+ let idx = 0;
3254
+ while (idx < tokens.length) {
3255
+ const tok = tokens[idx];
3256
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tok)) {
3257
+ idx += 1;
3258
+ continue;
3259
+ }
3260
+ const base = tok.split('/').at(-1)?.toLowerCase() || '';
3261
+ if (COMMAND_WRAPPERS.has(base)) {
3262
+ idx += 1;
3263
+ while (idx < tokens.length && tokens[idx].startsWith('-')) idx += 1;
3264
+ continue;
3265
+ }
3266
+ break;
3267
+ }
3268
+ if (idx >= tokens.length) return false;
3269
+
3270
+ const executable = tokens[idx].split('/').at(-1)?.toLowerCase() || '';
3271
+ const args = tokens.slice(idx + 1);
3272
+
3273
+ if (['bash', 'sh', 'zsh', 'dash', 'ksh'].includes(executable)) {
3274
+ for (let i = 0; i < args.length; i += 1) {
3275
+ if (/^-[A-Za-z]*c$/.test(args[i]) && i + 1 < args.length) {
3276
+ if (doesBashCommandMutateProtectedTarget(args[i + 1], commandTargetPattern, depth + 1)) {
3277
+ return true;
3278
+ }
3279
+ }
3280
+ }
3281
+ return false;
3282
+ }
3283
+
3284
+ if (executable === 'sed') {
3285
+ const hasInPlace = args.some((arg) => /^-(?:[A-Za-z]*i|-in-place(?:=|$))/.test(arg));
3286
+ if (!hasInPlace) return false;
3287
+ return args.some((arg) => !arg.startsWith('-') && commandTargetPattern.test(arg));
3288
+ }
3289
+
3290
+ if (executable === 'perl' || executable === 'ruby') {
3291
+ const hasInPlace = args.some((arg) => /^-[A-Za-z]*i/.test(arg));
3292
+ if (hasInPlace && args.some((arg) => !arg.startsWith('-') && commandTargetPattern.test(arg))) {
3293
+ return true;
3294
+ }
3295
+ return commandTargetPattern.test(cleaned) && INLINE_SCRIPT_WRITE_CALL_PATTERN.test(cleaned);
3296
+ }
3297
+
3298
+ if (executable === 'cp' || executable === 'install') {
3299
+ for (let i = 0; i < args.length; i += 1) {
3300
+ const arg = args[i];
3301
+ if ((arg === '-t' || arg === '--target-directory') && i + 1 < args.length) {
3302
+ return commandTargetPattern.test(args[i + 1]);
3303
+ }
3304
+ if (arg.startsWith('--target-directory=')) {
3305
+ return commandTargetPattern.test(arg.slice('--target-directory='.length));
3306
+ }
3307
+ }
3308
+ const positional = args.filter((arg) => !arg.startsWith('-'));
3309
+ if (positional.length === 0) return false;
3310
+ const destination = positional.at(-1);
3311
+ return commandTargetPattern.test(destination);
3312
+ }
3313
+
3314
+ if (['mv', 'rm', 'unlink', 'tee', 'truncate', 'patch', 'chmod', 'chown'].includes(executable)) {
3315
+ return args.some((arg) => !arg.startsWith('-') && commandTargetPattern.test(arg));
3316
+ }
3317
+
3318
+ if (executable === 'dd') {
3319
+ return args.some((arg) => arg.startsWith('of=') && commandTargetPattern.test(arg.slice(3)));
3320
+ }
3321
+
3322
+ if (executable === 'git') {
3323
+ const subcommand = args.find((arg) => !arg.startsWith('-'))?.toLowerCase();
3324
+ if (['rm', 'mv', 'checkout', 'restore'].includes(subcommand)) {
3325
+ return args.some((arg) => commandTargetPattern.test(arg));
3326
+ }
3327
+ return false;
3328
+ }
3329
+
3330
+ if (['node', 'python', 'python2', 'python3'].includes(executable)) {
3331
+ return commandTargetPattern.test(cleaned) && INLINE_SCRIPT_WRITE_CALL_PATTERN.test(cleaned);
3332
+ }
3333
+
3334
+ return false;
3335
+ }
3336
+
3337
+ function doesBashCommandMutateProtectedTarget(command, commandTargetPattern, depth = 0) {
3338
+ const stripped = stripNonInterpreterHeredocBodies(command);
3339
+ const segments = splitSelfProtectShellSegments(stripped);
3340
+ return segments.some((segment) => doesSegmentMutateProtectedTarget(segment, commandTargetPattern, depth));
3341
+ }
3342
+
2969
3343
  function matchSelfProtectHardFloor(gate, toolName, toolInput = {}) {
2970
3344
  const affected = extractAffectedFiles(toolName, toolInput);
2971
3345
  const affectedFiles = affected.files;
@@ -2986,26 +3360,8 @@ function matchSelfProtectHardFloor(gate, toolName, toolInput = {}) {
2986
3360
  ? SELF_PROTECT_CONFIG_COMMAND_PATTERN
2987
3361
  : SELF_PROTECT_HOOK_COMMAND_PATTERN;
2988
3362
 
2989
- // Inspect every shell redirection destination (optional fd, optional/no
2990
- // spaces, attached forms like printf x>file, multiple redirects).
2991
- const redirectPattern = /(?:^|[\s;&|]|[^\s;&|<>])(?:\d*)>{1,2}\s*([^\s;&|<>]+)/g;
2992
- const redirectTargets = [];
2993
- let redirectMatch = redirectPattern.exec(command);
2994
- while (redirectMatch) {
2995
- if (redirectMatch[1]) redirectTargets.push(redirectMatch[1]);
2996
- redirectMatch = redirectPattern.exec(command);
2997
- }
2998
- if (redirectTargets.length > 0) {
2999
- // Deny when any redirect destination is protected.
3000
- if (redirectTargets.some((target) => commandTargetPattern.test(target))) {
3001
- // fall through to deny
3002
- } else if (!SHELL_FILE_MUTATION_PATTERN.test(command) || !commandTargetPattern.test(command)) {
3003
- // Benign redirects and no other protected mutation → allow.
3004
- return null;
3005
- }
3006
- // Benign redirects but command still mutates a protected path another way → deny.
3007
- } else {
3008
- if (!SHELL_FILE_MUTATION_PATTERN.test(command) || !commandTargetPattern.test(command)) return null;
3363
+ if (!doesBashCommandMutateProtectedTarget(command, commandTargetPattern)) {
3364
+ return null;
3009
3365
  }
3010
3366
  } else {
3011
3367
  return null;
@@ -3072,7 +3428,7 @@ function isSafeLocalCredentialHardeningCommand(toolName, toolInput = {}) {
3072
3428
  return looksLikeCredentialPath;
3073
3429
  }
3074
3430
 
3075
- function evaluateMemoryGuard(toolName, toolInput = {}) {
3431
+ function evaluateMemoryGuard(toolName, toolInput = {}, options = {}) {
3076
3432
  const affected = extractAffectedFiles(toolName, toolInput);
3077
3433
  const affectedFiles = affected.files;
3078
3434
  if (isSafeSecretStorageWrite(toolName, toolInput, process.cwd())) {
@@ -3101,7 +3457,7 @@ function evaluateMemoryGuard(toolName, toolInput = {}) {
3101
3457
  const isPrCreateCommand = toolName === 'Bash' && (
3102
3458
  /\bgh\s+pr\s+create\b/i.test(command) || isGhApiPrCreateCommand(command)
3103
3459
  );
3104
- if (isPrCreateCommand && isConditionSatisfied('pr_create_allowed')) {
3460
+ if (isPrCreateCommand && isConditionSatisfied('pr_create_allowed', options)) {
3105
3461
  const branchGovernanceViolation = buildBranchGovernanceViolation(
3106
3462
  governanceState,
3107
3463
  toolInput,
@@ -3165,9 +3521,9 @@ function evaluateMemoryGuard(toolName, toolInput = {}) {
3165
3521
  let guard;
3166
3522
  if (toolInput && (toolInput.clawContext || toolInput._claw || toolInput.hybridRoute || toolInput.agentId)) {
3167
3523
  const clawCtx = toolInput.clawContext || toolInput._claw || { actionType: toolInput.actionType || 'unknown', agentId: toolInput.agentId || 'unknown', hybridRoute: toolInput.hybridRoute || 'unknown' };
3168
- guard = hybrid.evaluateClawPretool ? hybrid.evaluateClawPretool(toolName, serializedInput, clawCtx) : hybrid.evaluatePretool(toolName, serializedInput);
3524
+ guard = hybrid.evaluateClawPretool ? hybrid.evaluateClawPretool(toolName, serializedInput, clawCtx, options) : hybrid.evaluatePretool(toolName, serializedInput, options);
3169
3525
  } else {
3170
- guard = hybrid.evaluatePretool(toolName, serializedInput);
3526
+ guard = hybrid.evaluatePretool(toolName, serializedInput, options);
3171
3527
  }
3172
3528
  if (!guard || guard.mode !== 'block') {
3173
3529
  return null;
@@ -3209,8 +3565,8 @@ function buildSentinelGateResult(report) {
3209
3565
  };
3210
3566
  }
3211
3567
 
3212
- function recordSentinelDecision(report, toolName, toolInput) {
3213
- if (!report) return null;
3568
+ function recordSentinelDecision(report, toolName, toolInput, options = {}) {
3569
+ if (!report || process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
3214
3570
  const entry = recordDecisionEvaluation(report, {
3215
3571
  source: 'gates-engine',
3216
3572
  toolName,
@@ -3218,7 +3574,7 @@ function recordSentinelDecision(report, toolName, toolInput) {
3218
3574
  changedFiles: report && report.blastRadius && Array.isArray(report.blastRadius.affectedFiles)
3219
3575
  ? report.blastRadius.affectedFiles
3220
3576
  : [],
3221
- });
3577
+ }, options);
3222
3578
  report.actionId = entry.actionId;
3223
3579
  if (report.decisionControl && !report.decisionControl.actionId) {
3224
3580
  report.decisionControl.actionId = entry.actionId;
@@ -3226,7 +3582,7 @@ function recordSentinelDecision(report, toolName, toolInput) {
3226
3582
  return entry;
3227
3583
  }
3228
3584
 
3229
- function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard) {
3585
+ function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, options = {}) {
3230
3586
  if (!sentinelDecision) return;
3231
3587
  recordDecisionOutcome({
3232
3588
  actionId: sentinelDecision.actionId,
@@ -3235,10 +3591,10 @@ function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard) {
3235
3591
  actor: 'system',
3236
3592
  source: 'gates-engine',
3237
3593
  notes: enrichedMemoryGuard.message,
3238
- });
3594
+ }, options);
3239
3595
  }
3240
3596
 
3241
- function recordSentinelBlockDecision(sentinelDecision, sentinelResult) {
3597
+ function recordSentinelBlockDecision(sentinelDecision, sentinelResult, options = {}) {
3242
3598
  if (!sentinelDecision) return;
3243
3599
  recordDecisionOutcome({
3244
3600
  actionId: sentinelDecision.actionId,
@@ -3247,7 +3603,7 @@ function recordSentinelBlockDecision(sentinelDecision, sentinelResult) {
3247
3603
  actor: 'system',
3248
3604
  source: 'workflow-sentinel',
3249
3605
  notes: sentinelResult.message,
3250
- });
3606
+ }, options);
3251
3607
  }
3252
3608
 
3253
3609
  function enrichResultWithSentinel(result, report) {
@@ -3299,7 +3655,8 @@ function isAutonomousRun() {
3299
3655
  return raw === '1' || raw === 'true';
3300
3656
  }
3301
3657
 
3302
- async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3658
+ async function evaluateGatesAsyncInner(toolName, toolInput, configPath, options = {}) {
3659
+ const execution = gateExecution(toolInput, options);
3303
3660
  let config;
3304
3661
  try {
3305
3662
  let harnessPath;
@@ -3322,13 +3679,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3322
3679
  severity: 'high',
3323
3680
  message: burst.message,
3324
3681
  receipt: 'threat_defense_interdicted=true:type=RateBurst:action=block',
3325
- });
3682
+ }, execution);
3326
3683
  }
3327
3684
  }
3328
3685
  }
3329
3686
  } catch { /* optional */ }
3330
3687
  } catch { /* harness-selector is optional */ }
3331
- config = loadGatesConfig(configPath, harnessPath);
3688
+ config = loadGatesConfig(configPath, harnessPath, execution);
3332
3689
  } catch {
3333
3690
  return null;
3334
3691
  }
@@ -3343,18 +3700,18 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3343
3700
  constraints,
3344
3701
  );
3345
3702
  if (localOnlyRemoteSideEffectGate) {
3346
- return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate);
3703
+ return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate, execution);
3347
3704
  }
3348
3705
  const statefulHelperBypassGate = evaluateStatefulHelperBypassGate(toolName, toolInput);
3349
3706
  if (statefulHelperBypassGate) {
3350
- return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate);
3707
+ return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate, execution);
3351
3708
  }
3352
3709
  const stealthMemoryInjectionGate = evaluateStealthMemoryInjection(toolName, toolInput);
3353
3710
  if (stealthMemoryInjectionGate) {
3354
- return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate);
3711
+ return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate, execution);
3355
3712
  }
3356
- if (isBreakGlassSettingsRecoveryAction(toolName, toolInput)) {
3357
- recordAuditEvent({
3713
+ if (isBreakGlassSettingsRecoveryAction(toolName, toolInput, execution)) {
3714
+ recordAuditEvent({ ...execution,
3358
3715
  toolName,
3359
3716
  toolInput,
3360
3717
  decision: 'allow',
@@ -3368,8 +3725,8 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3368
3725
 
3369
3726
  const agentIdentityLifecycleGate = evaluateAgentIdentityLifecycleGate(toolName, toolInput);
3370
3727
  if (agentIdentityLifecycleGate) {
3371
- recordStat(agentIdentityLifecycleGate.gate, 'block', null, { toolName, toolInput });
3372
- const identityAuditRecord = recordAuditEvent({
3728
+ recordStat(agentIdentityLifecycleGate.gate, 'block', null, { ...execution, toolName, toolInput });
3729
+ const identityAuditRecord = recordAuditEvent({ ...execution,
3373
3730
  toolName,
3374
3731
  toolInput,
3375
3732
  decision: 'deny',
@@ -3382,10 +3739,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3382
3739
  return agentIdentityLifecycleGate;
3383
3740
  }
3384
3741
 
3385
- const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput);
3742
+ const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput, execution);
3386
3743
  if (pendingThreadResolutionGate) {
3387
- recordStat(pendingThreadResolutionGate.gate, 'block', null, { toolName, toolInput });
3388
- const auditRecord = recordAuditEvent({
3744
+ recordStat(pendingThreadResolutionGate.gate, 'block', null, { ...execution, toolName, toolInput });
3745
+ const auditRecord = recordAuditEvent({ ...execution,
3389
3746
  toolName,
3390
3747
  toolInput,
3391
3748
  decision: 'deny',
@@ -3394,14 +3751,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3394
3751
  severity: pendingThreadResolutionGate.severity,
3395
3752
  source: 'gates-engine',
3396
3753
  });
3397
- auditToFeedback(auditRecord);
3754
+ auditToFeedback(auditRecord, execution);
3398
3755
  return pendingThreadResolutionGate;
3399
3756
  }
3400
3757
 
3401
3758
  const boostedRiskGuard = evaluateBoostedRiskTagGuard(toolName, toolInput);
3402
3759
  if (boostedRiskGuard) {
3403
- recordStat(boostedRiskGuard.gate, 'block', null, { toolName, toolInput });
3404
- const auditRecord = recordAuditEvent({
3760
+ recordStat(boostedRiskGuard.gate, 'block', null, { ...execution, toolName, toolInput });
3761
+ const auditRecord = recordAuditEvent({ ...execution,
3405
3762
  toolName,
3406
3763
  toolInput,
3407
3764
  decision: 'deny',
@@ -3410,7 +3767,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3410
3767
  severity: boostedRiskGuard.severity,
3411
3768
  source: 'gates-engine',
3412
3769
  });
3413
- auditToFeedback(auditRecord);
3770
+ auditToFeedback(auditRecord, execution);
3414
3771
  return boostedRiskGuard;
3415
3772
  }
3416
3773
 
@@ -3419,9 +3776,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3419
3776
  constraints,
3420
3777
  toolName,
3421
3778
  toolInput,
3779
+ execution,
3422
3780
  );
3423
3781
  if (catastrophicDeclarativeGate) {
3424
- return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate);
3782
+ return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate, execution);
3425
3783
  }
3426
3784
 
3427
3785
  // Tier 1b: Planning and Trajectory (v1.26.0 - CodeRabbit Pattern).
@@ -3430,13 +3788,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3430
3788
  if (isRuntimePlanGateEnabled()) {
3431
3789
  const planGate = evaluatePlanGate(toolName, toolInput);
3432
3790
  if (planGate) {
3433
- recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
3791
+ recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
3434
3792
  return planGate;
3435
3793
  }
3436
3794
 
3437
3795
  const trajectory = getTrajectoryScore();
3438
3796
  if (trajectory.isDrifting) {
3439
- recordStat('strategic-drift', 'block', null, { toolName, toolInput });
3797
+ recordStat('strategic-drift', 'block', null, { ...execution, toolName, toolInput });
3440
3798
  return { decision: 'deny', gate: 'strategic-drift', message: trajectory.message, severity: 'high' };
3441
3799
  }
3442
3800
  }
@@ -3445,8 +3803,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3445
3803
  const METRIC_SKIP_TOOLS = ['capture_feedback', 'feedback_stats', 'recall', 'feedback_summary', 'prevention_rules'];
3446
3804
  const skipMetrics = METRIC_SKIP_TOOLS.includes(toolName);
3447
3805
 
3806
+ const sharedAffectedAsync = extractAffectedFiles(toolName, toolInput);
3448
3807
  for (const gate of config.gates) {
3449
- const matchDetails = matchGate(gate, toolName, toolInput);
3808
+ if (!gateAppliesToProject(gate, execution.projectKey)) continue;
3809
+ const matchDetails = matchGate(gate, toolName, toolInput, { ...execution, affected: sharedAffectedAsync, governanceState, constraints });
3450
3810
  if (!matchDetails.matched) continue;
3451
3811
 
3452
3812
  // EvoSkill Hardening: check contextual 'when' clause
@@ -3475,7 +3835,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3475
3835
  }
3476
3836
 
3477
3837
  // Check unless condition
3478
- if (gate.unless && isConditionSatisfied(gate.unless)) {
3838
+ if (gate.unless && isConditionSatisfied(gate.unless, execution)) {
3479
3839
  continue;
3480
3840
  }
3481
3841
 
@@ -3486,10 +3846,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3486
3846
  });
3487
3847
 
3488
3848
  if (gate.action === 'block') {
3489
- const adminOverride = evaluateAdminOverride(gate, toolName, toolInput);
3849
+ const adminOverride = evaluateAdminOverride(gate, toolName, toolInput, execution);
3490
3850
  if (adminOverride && adminOverride.authorized) {
3491
- recordStat(gate.id, 'approve', gate, { toolName, toolInput });
3492
- const auditRecord = recordAuditEvent({
3851
+ recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
3852
+ const auditRecord = recordAuditEvent({ ...execution,
3493
3853
  toolName,
3494
3854
  toolInput,
3495
3855
  decision: 'allow',
@@ -3498,7 +3858,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3498
3858
  severity: gate.severity,
3499
3859
  source: 'gates-engine-admin-override',
3500
3860
  });
3501
- auditToFeedback(auditRecord);
3861
+ auditToFeedback(auditRecord, execution);
3502
3862
  return {
3503
3863
  decision: 'allow',
3504
3864
  gate: gate.id,
@@ -3528,14 +3888,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3528
3888
  // Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
3529
3889
  const cappedResult = applyDailyBlockCap(denyResult);
3530
3890
  if (cappedResult) {
3531
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
3532
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
3533
- auditToFeedback(auditRecord);
3891
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
3892
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
3893
+ auditToFeedback(auditRecord, execution);
3534
3894
  return cappedResult;
3535
3895
  }
3536
- recordStat(gate.id, 'block', gate, { toolName, toolInput });
3537
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
3538
- auditToFeedback(auditRecord);
3896
+ recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
3897
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
3898
+ auditToFeedback(auditRecord, execution);
3539
3899
  return denyResult;
3540
3900
  }
3541
3901
 
@@ -3546,38 +3906,38 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3546
3906
  // Autonomous run: no human to approve. Fail CLOSED so the actions that
3547
3907
  // most need sign-off cannot slip through unattended.
3548
3908
  const failClosedMessage = `[autonomous run — no approver present, failing closed] ${message}`;
3549
- recordStat(gate.id, 'block', gate, { toolName, toolInput });
3550
- const failClosedAudit = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
3551
- auditToFeedback(failClosedAudit);
3909
+ recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
3910
+ const failClosedAudit = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
3911
+ auditToFeedback(failClosedAudit, execution);
3552
3912
  return { decision: 'deny', gate: gate.id, message: failClosedMessage, severity: gate.severity, reasoning, requiresApproval: true, failedClosed: true };
3553
3913
  }
3554
- recordStat(gate.id, 'approve', gate, { toolName, toolInput });
3914
+ recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
3555
3915
  const result = { decision: 'approve', gate: gate.id, message, severity: gate.severity, reasoning, requiresApproval: true };
3556
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3557
- auditToFeedback(auditRecord);
3916
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3917
+ auditToFeedback(auditRecord, execution);
3558
3918
  return result;
3559
3919
  }
3560
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
3920
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
3561
3921
  const result = { decision: 'warn', gate: gate.id, message: `[approval gate disabled] ${message}`, severity: gate.severity, reasoning };
3562
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3563
- auditToFeedback(auditRecord);
3922
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3923
+ auditToFeedback(auditRecord, execution);
3564
3924
  return result;
3565
3925
  }
3566
3926
 
3567
3927
  if (gate.action === 'log') {
3568
- recordStat(gate.id, 'log', gate, { toolName, toolInput });
3928
+ recordStat(gate.id, 'log', gate, { ...execution, toolName, toolInput });
3569
3929
  const result = { decision: 'log', gate: gate.id, message, severity: gate.severity, reasoning, logged: true };
3570
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3571
- auditToFeedback(auditRecord);
3930
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3931
+ auditToFeedback(auditRecord, execution);
3572
3932
  // 'log' action allows the tool call to proceed — do not return early, continue to next gate
3573
3933
  continue;
3574
3934
  }
3575
3935
 
3576
3936
  if (gate.action === 'warn') {
3577
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
3937
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
3578
3938
  const result = { decision: 'warn', gate: gate.id, message, severity: gate.severity, reasoning };
3579
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3580
- auditToFeedback(auditRecord);
3939
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3940
+ auditToFeedback(auditRecord, execution);
3581
3941
  return result;
3582
3942
  }
3583
3943
  }
@@ -3586,13 +3946,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3586
3946
  const sentinelReport = skipAdvisoryGuards ? null : evaluateWorkflowSentinel(toolName, toolInput, {
3587
3947
  governanceState,
3588
3948
  });
3589
- const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput);
3590
- const memoryGuard = evaluateMemoryGuard(toolName, toolInput);
3949
+ const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput, execution);
3950
+ const memoryGuard = evaluateMemoryGuard(toolName, toolInput, execution);
3591
3951
  if (memoryGuard) {
3592
3952
  const enrichedMemoryGuard = enrichResultWithSentinel(memoryGuard, sentinelReport);
3593
- recordStat(enrichedMemoryGuard.gate, 'block', null, { toolName, toolInput });
3594
- recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard);
3595
- const auditRecord = recordAuditEvent({
3953
+ recordStat(enrichedMemoryGuard.gate, 'block', null, { ...execution, toolName, toolInput });
3954
+ recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, execution);
3955
+ const auditRecord = recordAuditEvent({ ...execution,
3596
3956
  toolName,
3597
3957
  toolInput,
3598
3958
  decision: 'deny',
@@ -3601,15 +3961,15 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3601
3961
  severity: enrichedMemoryGuard.severity,
3602
3962
  source: 'gates-engine',
3603
3963
  });
3604
- auditToFeedback(auditRecord);
3964
+ auditToFeedback(auditRecord, execution);
3605
3965
  return enrichedMemoryGuard;
3606
3966
  }
3607
3967
 
3608
3968
  if (sentinelReport && sentinelReport.decision !== 'allow') {
3609
3969
  const sentinelResult = buildSentinelGateResult(sentinelReport);
3610
- recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
3611
- recordSentinelBlockDecision(sentinelDecision, sentinelResult);
3612
- const auditRecord = recordAuditEvent({
3970
+ recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
3971
+ recordSentinelBlockDecision(sentinelDecision, sentinelResult, execution);
3972
+ const auditRecord = recordAuditEvent({ ...execution,
3613
3973
  toolName,
3614
3974
  toolInput,
3615
3975
  decision: sentinelResult.decision,
@@ -3618,14 +3978,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3618
3978
  severity: sentinelResult.severity,
3619
3979
  source: 'workflow-sentinel',
3620
3980
  });
3621
- auditToFeedback(auditRecord);
3981
+ auditToFeedback(auditRecord, execution);
3622
3982
  return sentinelResult;
3623
3983
  }
3624
3984
 
3625
3985
  const brokerReceiptResultAsync = evaluateBrokerReceiptGate(toolName, toolInput);
3626
3986
  if (brokerReceiptResultAsync && brokerReceiptResultAsync.decision === 'deny') {
3627
- recordStat(brokerReceiptResultAsync.gate, 'block', null, { toolName, toolInput });
3628
- const auditRecord = recordAuditEvent({
3987
+ recordStat(brokerReceiptResultAsync.gate, 'block', null, { ...execution, toolName, toolInput });
3988
+ const auditRecord = recordAuditEvent({ ...execution,
3629
3989
  toolName,
3630
3990
  toolInput,
3631
3991
  decision: 'deny',
@@ -3634,20 +3994,21 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
3634
3994
  severity: brokerReceiptResultAsync.severity,
3635
3995
  source: 'broker-execution-receipts',
3636
3996
  });
3637
- auditToFeedback(auditRecord);
3997
+ auditToFeedback(auditRecord, execution);
3638
3998
  return brokerReceiptResultAsync;
3639
3999
  }
3640
4000
 
3641
4001
  // Audit trail: record allow (no gate matched)
3642
- recordAuditEvent({ toolName, toolInput, decision: 'allow', source: 'gates-engine' });
4002
+ recordAuditEvent({ ...execution, toolName, toolInput, decision: 'allow', source: 'gates-engine' });
3643
4003
  return null;
3644
4004
  }
3645
4005
 
3646
- function evaluateGatesInner(toolName, toolInput, configPath) {
4006
+ function evaluateGatesInner(toolName, toolInput, configPath, options = {}) {
4007
+ const execution = gateExecution(toolInput, options);
3647
4008
  let config;
3648
4009
  try {
3649
4010
  let harnessPath;
3650
- try {
4011
+ if (process.env.THUMBGATE_SANDBOX_EVAL !== '1') try {
3651
4012
  const { selectHarness } = require('./harness-selector');
3652
4013
  harnessPath = selectHarness(toolName, toolInput);
3653
4014
  try {
@@ -3666,13 +4027,13 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3666
4027
  severity: 'high',
3667
4028
  message: burst.message,
3668
4029
  receipt: 'threat_defense_interdicted=true:type=RateBurst:action=block',
3669
- });
4030
+ }, execution);
3670
4031
  }
3671
4032
  }
3672
4033
  }
3673
4034
  } catch { /* optional */ }
3674
4035
  } catch { /* harness-selector is optional */ }
3675
- config = loadGatesConfig(configPath, harnessPath);
4036
+ config = loadGatesConfig(configPath, harnessPath, execution);
3676
4037
  } catch {
3677
4038
  // If config can't be loaded, pass through
3678
4039
  return null;
@@ -3688,18 +4049,18 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3688
4049
  constraints,
3689
4050
  );
3690
4051
  if (localOnlyRemoteSideEffectGate) {
3691
- return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate);
4052
+ return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate, execution);
3692
4053
  }
3693
4054
  const statefulHelperBypassGate = evaluateStatefulHelperBypassGate(toolName, toolInput);
3694
4055
  if (statefulHelperBypassGate) {
3695
- return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate);
4056
+ return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate, execution);
3696
4057
  }
3697
4058
  const stealthMemoryInjectionGate = evaluateStealthMemoryInjection(toolName, toolInput);
3698
4059
  if (stealthMemoryInjectionGate) {
3699
- return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate);
4060
+ return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate, execution);
3700
4061
  }
3701
- if (isBreakGlassSettingsRecoveryAction(toolName, toolInput)) {
3702
- recordAuditEvent({
4062
+ if (isBreakGlassSettingsRecoveryAction(toolName, toolInput, execution)) {
4063
+ recordAuditEvent({ ...execution,
3703
4064
  toolName,
3704
4065
  toolInput,
3705
4066
  decision: 'allow',
@@ -3713,8 +4074,8 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3713
4074
 
3714
4075
  const agentIdentityLifecycleGate = evaluateAgentIdentityLifecycleGate(toolName, toolInput);
3715
4076
  if (agentIdentityLifecycleGate) {
3716
- recordStat(agentIdentityLifecycleGate.gate, 'block', null, { toolName, toolInput });
3717
- const identityAuditRecord = recordAuditEvent({
4077
+ recordStat(agentIdentityLifecycleGate.gate, 'block', null, { ...execution, toolName, toolInput });
4078
+ const identityAuditRecord = recordAuditEvent({ ...execution,
3718
4079
  toolName,
3719
4080
  toolInput,
3720
4081
  decision: 'deny',
@@ -3727,10 +4088,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3727
4088
  return agentIdentityLifecycleGate;
3728
4089
  }
3729
4090
 
3730
- const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput);
4091
+ const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput, execution);
3731
4092
  if (pendingThreadResolutionGate) {
3732
- recordStat(pendingThreadResolutionGate.gate, 'block', null, { toolName, toolInput });
3733
- const auditRecord = recordAuditEvent({
4093
+ recordStat(pendingThreadResolutionGate.gate, 'block', null, { ...execution, toolName, toolInput });
4094
+ const auditRecord = recordAuditEvent({ ...execution,
3734
4095
  toolName,
3735
4096
  toolInput,
3736
4097
  decision: 'deny',
@@ -3739,14 +4100,14 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3739
4100
  severity: pendingThreadResolutionGate.severity,
3740
4101
  source: 'gates-engine',
3741
4102
  });
3742
- auditToFeedback(auditRecord);
4103
+ auditToFeedback(auditRecord, execution);
3743
4104
  return pendingThreadResolutionGate;
3744
4105
  }
3745
4106
 
3746
- const boostedRiskGuard = evaluateBoostedRiskTagGuard(toolName, toolInput);
4107
+ const boostedRiskGuard = process.env.THUMBGATE_SANDBOX_EVAL === '1' ? null : evaluateBoostedRiskTagGuard(toolName, toolInput);
3747
4108
  if (boostedRiskGuard) {
3748
- recordStat(boostedRiskGuard.gate, 'block', null, { toolName, toolInput });
3749
- const auditRecord = recordAuditEvent({
4109
+ recordStat(boostedRiskGuard.gate, 'block', null, { ...execution, toolName, toolInput });
4110
+ const auditRecord = recordAuditEvent({ ...execution,
3750
4111
  toolName,
3751
4112
  toolInput,
3752
4113
  decision: 'deny',
@@ -3755,7 +4116,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3755
4116
  severity: boostedRiskGuard.severity,
3756
4117
  source: 'gates-engine',
3757
4118
  });
3758
- auditToFeedback(auditRecord);
4119
+ auditToFeedback(auditRecord, execution);
3759
4120
  return boostedRiskGuard;
3760
4121
  }
3761
4122
 
@@ -3764,9 +4125,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3764
4125
  constraints,
3765
4126
  toolName,
3766
4127
  toolInput,
4128
+ execution,
3767
4129
  );
3768
4130
  if (catastrophicDeclarativeGate) {
3769
- return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate);
4131
+ return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate, execution);
3770
4132
  }
3771
4133
 
3772
4134
  // Tier 1b: Planning and Trajectory (v1.26.0 - CodeRabbit Pattern).
@@ -3775,19 +4137,20 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3775
4137
  if (isRuntimePlanGateEnabled()) {
3776
4138
  const planGate = evaluatePlanGate(toolName, toolInput);
3777
4139
  if (planGate) {
3778
- recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
4140
+ recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
3779
4141
  return planGate;
3780
4142
  }
3781
4143
 
3782
4144
  const trajectory = getTrajectoryScore();
3783
4145
  if (trajectory.isDrifting) {
3784
- recordStat('strategic-drift', 'block', null, { toolName, toolInput });
4146
+ recordStat('strategic-drift', 'block', null, { ...execution, toolName, toolInput });
3785
4147
  return { decision: 'deny', gate: 'strategic-drift', message: trajectory.message, severity: 'high' };
3786
4148
  }
3787
4149
  }
3788
-
4150
+ const sharedAffected = extractAffectedFiles(toolName, toolInput);
3789
4151
  for (const gate of config.gates) {
3790
- const matchDetails = matchGate(gate, toolName, toolInput);
4152
+ if (!gateAppliesToProject(gate, execution.projectKey)) continue;
4153
+ const matchDetails = matchGate(gate, toolName, toolInput, { ...execution, affected: sharedAffected, governanceState, constraints });
3791
4154
  if (!matchDetails.matched) continue;
3792
4155
 
3793
4156
  // EvoSkill Hardening: check contextual 'when' clause
@@ -3796,7 +4159,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3796
4159
  }
3797
4160
 
3798
4161
  // Check unless condition
3799
- if (gate.unless && isConditionSatisfied(gate.unless)) {
4162
+ if (gate.unless && isConditionSatisfied(gate.unless, execution)) {
3800
4163
  continue;
3801
4164
  }
3802
4165
 
@@ -3804,10 +4167,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3804
4167
  const reasoning = buildReasoning(gate, toolName, toolInput, matchDetails);
3805
4168
 
3806
4169
  if (gate.action === 'block') {
3807
- const adminOverride = evaluateAdminOverride(gate, toolName, toolInput);
4170
+ const adminOverride = evaluateAdminOverride(gate, toolName, toolInput, execution);
3808
4171
  if (adminOverride && adminOverride.authorized) {
3809
- recordStat(gate.id, 'approve', gate, { toolName, toolInput });
3810
- const auditRecord = recordAuditEvent({
4172
+ recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
4173
+ const auditRecord = recordAuditEvent({ ...execution,
3811
4174
  toolName,
3812
4175
  toolInput,
3813
4176
  decision: 'allow',
@@ -3816,7 +4179,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3816
4179
  severity: gate.severity,
3817
4180
  source: 'gates-engine-admin-override',
3818
4181
  });
3819
- auditToFeedback(auditRecord);
4182
+ auditToFeedback(auditRecord, execution);
3820
4183
  return {
3821
4184
  decision: 'allow',
3822
4185
  gate: gate.id,
@@ -3846,14 +4209,14 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3846
4209
  // Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
3847
4210
  const cappedResult = applyDailyBlockCap(denyResult);
3848
4211
  if (cappedResult) {
3849
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
3850
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
3851
- auditToFeedback(auditRecord);
4212
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
4213
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
4214
+ auditToFeedback(auditRecord, execution);
3852
4215
  return cappedResult;
3853
4216
  }
3854
- recordStat(gate.id, 'block', gate, { toolName, toolInput });
3855
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
3856
- auditToFeedback(auditRecord);
4217
+ recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
4218
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
4219
+ auditToFeedback(auditRecord, execution);
3857
4220
  return denyResult;
3858
4221
  }
3859
4222
 
@@ -3864,52 +4227,53 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3864
4227
  // Autonomous run: no human to approve. Fail CLOSED so the actions that
3865
4228
  // most need sign-off cannot slip through unattended.
3866
4229
  const failClosedMessage = `[autonomous run — no approver present, failing closed] ${message}`;
3867
- recordStat(gate.id, 'block', gate, { toolName, toolInput });
3868
- const failClosedAudit = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
3869
- auditToFeedback(failClosedAudit);
4230
+ recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
4231
+ const failClosedAudit = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
4232
+ auditToFeedback(failClosedAudit, execution);
3870
4233
  return { decision: 'deny', gate: gate.id, message: failClosedMessage, severity: gate.severity, reasoning, requiresApproval: true, failedClosed: true };
3871
4234
  }
3872
- recordStat(gate.id, 'approve', gate, { toolName, toolInput });
4235
+ recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
3873
4236
  const result = { decision: 'approve', gate: gate.id, message, severity: gate.severity, reasoning, requiresApproval: true };
3874
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3875
- auditToFeedback(auditRecord);
4237
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
4238
+ auditToFeedback(auditRecord, execution);
3876
4239
  return result;
3877
4240
  }
3878
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
4241
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
3879
4242
  const result = { decision: 'warn', gate: gate.id, message: `[approval gate disabled] ${message}`, severity: gate.severity, reasoning };
3880
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3881
- auditToFeedback(auditRecord);
4243
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
4244
+ auditToFeedback(auditRecord, execution);
3882
4245
  return result;
3883
4246
  }
3884
4247
 
3885
4248
  if (gate.action === 'log') {
3886
- recordStat(gate.id, 'log', gate, { toolName, toolInput });
3887
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3888
- auditToFeedback(auditRecord);
4249
+ recordStat(gate.id, 'log', gate, { ...execution, toolName, toolInput });
4250
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
4251
+ auditToFeedback(auditRecord, execution);
3889
4252
  // 'log' action allows the tool call to proceed — continue to next gate
3890
4253
  continue;
3891
4254
  }
3892
4255
 
3893
4256
  if (gate.action === 'warn') {
3894
- recordStat(gate.id, 'warn', gate, { toolName, toolInput });
4257
+ recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
3895
4258
  const result = { decision: 'warn', gate: gate.id, message, severity: gate.severity, reasoning };
3896
- const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
3897
- auditToFeedback(auditRecord);
4259
+ const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
4260
+ auditToFeedback(auditRecord, execution);
3898
4261
  return result;
3899
4262
  }
3900
4263
  }
4264
+ if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
3901
4265
 
3902
4266
  const skipAdvisoryGuards = isSafeSecretStorageWrite(toolName, toolInput, process.cwd());
3903
4267
  const sentinelReport = skipAdvisoryGuards ? null : evaluateWorkflowSentinel(toolName, toolInput, {
3904
4268
  governanceState,
3905
4269
  });
3906
- const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput);
3907
- const memoryGuard = evaluateMemoryGuard(toolName, toolInput);
4270
+ const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput, execution);
4271
+ const memoryGuard = evaluateMemoryGuard(toolName, toolInput, execution);
3908
4272
  if (memoryGuard) {
3909
4273
  const enrichedMemoryGuard = enrichResultWithSentinel(memoryGuard, sentinelReport);
3910
- recordStat(enrichedMemoryGuard.gate, 'block', null, { toolName, toolInput });
3911
- recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard);
3912
- const auditRecord = recordAuditEvent({
4274
+ recordStat(enrichedMemoryGuard.gate, 'block', null, { ...execution, toolName, toolInput });
4275
+ recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, execution);
4276
+ const auditRecord = recordAuditEvent({ ...execution,
3913
4277
  toolName,
3914
4278
  toolInput,
3915
4279
  decision: 'deny',
@@ -3918,15 +4282,15 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3918
4282
  severity: enrichedMemoryGuard.severity,
3919
4283
  source: 'gates-engine',
3920
4284
  });
3921
- auditToFeedback(auditRecord);
4285
+ auditToFeedback(auditRecord, execution);
3922
4286
  return enrichedMemoryGuard;
3923
4287
  }
3924
4288
 
3925
4289
  if (sentinelReport && sentinelReport.decision !== 'allow') {
3926
4290
  const sentinelResult = buildSentinelGateResult(sentinelReport);
3927
- recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
3928
- recordSentinelBlockDecision(sentinelDecision, sentinelResult);
3929
- const auditRecord = recordAuditEvent({
4291
+ recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
4292
+ recordSentinelBlockDecision(sentinelDecision, sentinelResult, execution);
4293
+ const auditRecord = recordAuditEvent({ ...execution,
3930
4294
  toolName,
3931
4295
  toolInput,
3932
4296
  decision: sentinelResult.decision,
@@ -3935,7 +4299,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3935
4299
  severity: sentinelResult.severity,
3936
4300
  source: 'workflow-sentinel',
3937
4301
  });
3938
- auditToFeedback(auditRecord);
4302
+ auditToFeedback(auditRecord, execution);
3939
4303
  return sentinelResult;
3940
4304
  }
3941
4305
 
@@ -3943,8 +4307,8 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3943
4307
  // for high-risk provider side effects (THUMBGATE_BROKER_RECEIPT_MODE=enforce).
3944
4308
  const brokerReceiptResult = evaluateBrokerReceiptGate(toolName, toolInput);
3945
4309
  if (brokerReceiptResult && brokerReceiptResult.decision === 'deny') {
3946
- recordStat(brokerReceiptResult.gate, 'block', null, { toolName, toolInput });
3947
- const auditRecord = recordAuditEvent({
4310
+ recordStat(brokerReceiptResult.gate, 'block', null, { ...execution, toolName, toolInput });
4311
+ const auditRecord = recordAuditEvent({ ...execution,
3948
4312
  toolName,
3949
4313
  toolInput,
3950
4314
  decision: 'deny',
@@ -3953,12 +4317,12 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
3953
4317
  severity: brokerReceiptResult.severity,
3954
4318
  source: 'broker-execution-receipts',
3955
4319
  });
3956
- auditToFeedback(auditRecord);
4320
+ auditToFeedback(auditRecord, execution);
3957
4321
  return brokerReceiptResult;
3958
4322
  }
3959
4323
 
3960
4324
  // Audit trail: record allow
3961
- recordAuditEvent({ toolName, toolInput, decision: 'allow', source: 'gates-engine' });
4325
+ recordAuditEvent({ ...execution, toolName, toolInput, decision: 'allow', source: 'gates-engine' });
3962
4326
  return null;
3963
4327
  }
3964
4328
 
@@ -4632,7 +4996,22 @@ function evaluateRepeatedMistakeGates(input = {}) {
4632
4996
  || evaluateMablFailureHonestyGate(view);
4633
4997
  }
4634
4998
 
4635
- function evaluateUnconditionalHardFloor(input = {}, options = {}) {
4999
+ function canonicalizeHookInput(input = {}) {
5000
+ if (!input || typeof input !== 'object') return {};
5001
+ const rawName = input.tool_name ?? input.toolName ?? '';
5002
+ const rawToolInput = input.tool_input ?? input.toolInput ?? {};
5003
+ const { toolName, toolInput } = canonicalizeToolCall(rawName, rawToolInput);
5004
+ return {
5005
+ ...input,
5006
+ tool_name: toolName,
5007
+ tool_input: toolInput,
5008
+ ...('toolName' in input ? { toolName } : {}),
5009
+ ...('toolInput' in input ? { toolInput } : {}),
5010
+ };
5011
+ }
5012
+
5013
+ function evaluateUnconditionalHardFloor(rawInput = {}, options = {}) {
5014
+ const input = canonicalizeHookInput(rawInput);
4636
5015
  const secretGuard = evaluateSecretGuard(input);
4637
5016
  if (secretGuard) return { hardFloor: secretGuard, securityScan: null };
4638
5017
 
@@ -4959,7 +5338,7 @@ function buildRecentCorrectiveActionsContext(options = {}) {
4959
5338
  * active governor. Without this, lessons stay in the DB and never get surfaced at
4960
5339
  * decision time — so the agent repeats mistakes.
4961
5340
  */
4962
- function buildRelevantLessonContext(toolName, toolInput) {
5341
+ function buildRelevantLessonContext(toolName, toolInput, options = {}) {
4963
5342
  if (!toolName) return null;
4964
5343
 
4965
5344
  const { retrieveRelevantLessons, calculateRetrievalEntropy } = loadOptionalModule("./lesson-retrieval", () => ({ retrieveRelevantLessons: () => [], calculateRetrievalEntropy: () => 0 }));
@@ -4969,7 +5348,11 @@ function buildRelevantLessonContext(toolName, toolInput) {
4969
5348
  if (!actionContext) return null;
4970
5349
 
4971
5350
  try {
4972
- const lessons = retrieveRelevantLessons(toolName, actionContext, { maxResults: 3 });
5351
+ const lessons = retrieveRelevantLessons(toolName, actionContext, {
5352
+ maxResults: 3,
5353
+ cwd: options.cwd || toolInput?.cwd,
5354
+ project: options.project,
5355
+ });
4973
5356
 
4974
5357
  const entropy = calculateRetrievalEntropy(lessons);
4975
5358
  if (entropy > KNOWLEDGE_ENTROPY_THRESHOLD) {
@@ -4987,7 +5370,7 @@ function buildRelevantLessonContext(toolName, toolInput) {
4987
5370
  * even when they share no keywords with the current action. Wired into runAsync.
4988
5371
  * Degrades to the lexical result automatically when no embedder is available.
4989
5372
  */
4990
- async function buildRelevantLessonContextAsync(toolName, toolInput) {
5373
+ async function buildRelevantLessonContextAsync(toolName, toolInput, options = {}) {
4991
5374
  if (!toolName) return null;
4992
5375
 
4993
5376
  const { retrieveRelevantLessonsAsync, retrieveRelevantLessons, calculateRetrievalEntropy } = loadOptionalModule(
@@ -4999,9 +5382,14 @@ async function buildRelevantLessonContextAsync(toolName, toolInput) {
4999
5382
  if (!actionContext) return null;
5000
5383
 
5001
5384
  try {
5385
+ const retrievalOpts = {
5386
+ maxResults: 3,
5387
+ cwd: options.cwd || toolInput?.cwd,
5388
+ project: options.project,
5389
+ };
5002
5390
  const lessons = retrieveRelevantLessonsAsync
5003
- ? await retrieveRelevantLessonsAsync(toolName, actionContext, { maxResults: 3 })
5004
- : retrieveRelevantLessons(toolName, actionContext, { maxResults: 3 });
5391
+ ? await retrieveRelevantLessonsAsync(toolName, actionContext, retrievalOpts)
5392
+ : retrieveRelevantLessons(toolName, actionContext, retrievalOpts);
5005
5393
 
5006
5394
  // Knowledge Conflict Detection: if retrieved lessons have high sentiment entropy,
5007
5395
  // it indicates conflicting past evidence. Warn by default; hard-block only in
@@ -5100,7 +5488,33 @@ function mergeContextStrings(...ctxs) {
5100
5488
  return ctxs.filter((c) => typeof c === 'string' && c.length > 0).join('\n\n') || null;
5101
5489
  }
5102
5490
 
5103
- async function runAsync(input) {
5491
+ function buildDesignSelfCorrectionContext(toolName, toolInput = {}) {
5492
+ try {
5493
+ const filePath = String(toolInput.file_path || toolInput.filePath || '').trim();
5494
+ const hasVisual = Array.isArray(toolInput.visualFindings) && toolInput.visualFindings.length > 0;
5495
+ const isUiFile = /\.(?:html?|jsx|tsx|css)$/i.test(filePath);
5496
+ if (!hasVisual && (!EDIT_LIKE_TOOLS.has(toolName) || !isUiFile)) return null;
5497
+ const source = String(toolInput.content ?? toolInput.new_string ?? toolInput.sourceCode ?? '');
5498
+ if (!source && !hasVisual) return null;
5499
+ if (source.length > 262144) return null;
5500
+ const { inspectAndPatchDesignSource } = require('../src/openshell-lovable-engine');
5501
+ const report = inspectAndPatchDesignSource(source, {
5502
+ filePath: filePath || null,
5503
+ visualFindings: toolInput.visualFindings,
5504
+ });
5505
+ if (!report || report.issueCount === 0) return null;
5506
+ const lines = report.patches.slice(0, 5).map((p) => {
5507
+ const tw = p.tailwindPatch?.add?.length ? ` | Tailwind +[${p.tailwindPatch.add.join(' ')}]` : '';
5508
+ return ` • [${p.type}] ${p.selector || p.astPath}: CSS { ${p.cssOverride} }${tw}`;
5509
+ });
5510
+ return `[ThumbGate Active Design Engine] ${report.issueCount} layout/AST optimization(s) auto-synthesized:\n${lines.join('\n')}`;
5511
+ } catch {
5512
+ return null;
5513
+ }
5514
+ }
5515
+
5516
+ async function runAsync(rawInput) {
5517
+ const input = canonicalizeHookInput(rawInput);
5104
5518
  const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
5105
5519
  if (hardFloor) return formatOutput(hardFloor);
5106
5520
 
@@ -5142,12 +5556,14 @@ async function runAsync(input) {
5142
5556
  if (financialAuthorization) return formatOutput(financialAuthorization);
5143
5557
 
5144
5558
  const recentContext = buildRecentCorrectiveActionsContext();
5145
- const combinedContext = mergeContextStrings(lessonContext, recentContext, behavioralContext);
5559
+ const designContext = safeSecretStorageWrite ? null : buildDesignSelfCorrectionContext(toolName, toolInput);
5560
+ const combinedContext = combineWithSessionDedupe(input, lessonContext, recentContext, behavioralContext, designContext);
5146
5561
  return formatOutput(posturedResult, combinedContext);
5147
5562
 
5148
5563
  }
5149
5564
 
5150
- function run(input) {
5565
+ function run(rawInput) {
5566
+ const input = canonicalizeHookInput(rawInput);
5151
5567
  const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
5152
5568
  if (hardFloor) return formatOutput(hardFloor);
5153
5569
 
@@ -5189,11 +5605,34 @@ function run(input) {
5189
5605
  if (financialAuthorization) return formatOutput(financialAuthorization);
5190
5606
 
5191
5607
  const recentContext = buildRecentCorrectiveActionsContext();
5192
- const combinedContext = mergeContextStrings(lessonContext, recentContext, behavioralContext);
5608
+ const designContext = safeSecretStorageWrite ? null : buildDesignSelfCorrectionContext(toolName, toolInput);
5609
+ const combinedContext = combineWithSessionDedupe(input, lessonContext, recentContext, behavioralContext, designContext);
5193
5610
  return formatOutput(posturedResult, combinedContext);
5194
5611
 
5195
5612
  }
5196
5613
 
5614
+ // Recent-corrections and recurring-pattern text is identical call after call; inject it
5615
+ // only when it changed since the last injection in this session. Lesson context (matched to
5616
+ // the current tool call) and design context (derived from this call's content) always pass.
5617
+ function combineWithSessionDedupe(input, lessonContext, recentContext, behavioralContext, designContext) {
5618
+ const { dedupeSessionContext, logInjection } = require('./session-context-dedupe');
5619
+ const sessionId = input.session_id || input.sessionId || '';
5620
+ const staticContext = mergeContextStrings(recentContext, behavioralContext);
5621
+ const injectedStatic = dedupeSessionContext(sessionId, staticContext);
5622
+ const before = mergeContextStrings(lessonContext, staticContext, designContext);
5623
+ const after = mergeContextStrings(lessonContext, injectedStatic, designContext);
5624
+ if (before) {
5625
+ logInjection({
5626
+ ts: new Date().toISOString(),
5627
+ session: String(sessionId).slice(0, 12),
5628
+ tool: input.tool_name || '',
5629
+ bytesBefore: Buffer.byteLength(before),
5630
+ bytesAfter: after ? Buffer.byteLength(after) : 0,
5631
+ });
5632
+ }
5633
+ return after;
5634
+ }
5635
+
5197
5636
 
5198
5637
  // A command can be spelled many ways without changing what it does: `sudo git …`,
5199
5638
  // `"git" …`, `/usr/bin/git …`, `GIT_DIR=… git …`, a chained `echo hi && git …`, or a git
@@ -5259,25 +5698,37 @@ function applyOneShotPretool(toolName, toolInput) {
5259
5698
  return oneshotUnreadableDeny();
5260
5699
  }
5261
5700
  }
5701
+ function applyBrandStandardsHook(toolName, toolInput) {
5702
+ try {
5703
+ const { applyBrandStandardsPretool } = require('./brand-standards-gate');
5704
+ return applyBrandStandardsPretool(toolName, toolInput);
5705
+ } catch {
5706
+ return null;
5707
+ }
5708
+ }
5262
5709
 
5263
- async function evaluateGatesAsync(toolName, toolInput, configPath) {
5710
+ async function evaluateGatesAsync(toolName, toolInput, configPath, options = {}) {
5264
5711
  const oneshot = applyOneShotPretool(toolName, toolInput);
5265
5712
  if (oneshot) return oneshot;
5266
- const direct = await evaluateGatesAsyncInner(toolName, toolInput, configPath);
5713
+ const direct = await evaluateGatesAsyncInner(toolName, toolInput, configPath, options);
5267
5714
  if (direct) return direct;
5715
+ const brandStandards = applyBrandStandardsHook(toolName, toolInput);
5716
+ if (brandStandards) return brandStandards;
5268
5717
  const retry = canonicalRetryInput(toolName, toolInput);
5269
5718
  if (!retry) return null;
5270
- return evaluateGatesAsyncInner(toolName, retry, configPath);
5719
+ return evaluateGatesAsyncInner(toolName, retry, configPath, options);
5271
5720
  }
5272
5721
 
5273
- function evaluateGates(toolName, toolInput, configPath) {
5722
+ function evaluateGates(toolName, toolInput, configPath, options = {}) {
5274
5723
  const oneshot = applyOneShotPretool(toolName, toolInput);
5275
5724
  if (oneshot) return oneshot;
5276
- const direct = evaluateGatesInner(toolName, toolInput, configPath);
5725
+ const direct = evaluateGatesInner(toolName, toolInput, configPath, options);
5277
5726
  if (direct) return direct;
5727
+ const brandStandards = applyBrandStandardsHook(toolName, toolInput);
5728
+ if (brandStandards) return brandStandards;
5278
5729
  const retry = canonicalRetryInput(toolName, toolInput);
5279
5730
  if (!retry) return null;
5280
- return evaluateGatesInner(toolName, retry, configPath);
5731
+ return evaluateGatesInner(toolName, retry, configPath, options);
5281
5732
  }
5282
5733
 
5283
5734
  // ---------------------------------------------------------------------------
@@ -5734,6 +6185,7 @@ module.exports = {
5734
6185
  DEFAULT_PROTECTED_FILE_GLOBS,
5735
6186
  buildBehavioralContext,
5736
6187
  buildRecentCorrectiveActionsContext,
6188
+ combineWithSessionDedupe,
5737
6189
  buildRelevantLessonContext,
5738
6190
  buildRelevantLessonContextAsync,
5739
6191
  extractActionContext,
@@ -5789,3 +6241,15 @@ if (require.main === module) {
5789
6241
  }
5790
6242
  });
5791
6243
  }
6244
+
6245
+ for (const key of ['STATE_PATH', 'CONSTRAINTS_PATH', 'STATS_PATH', 'SESSION_ACTIONS_PATH', 'CUSTOM_CLAIM_GATES_PATH', 'GOVERNANCE_STATE_PATH']) {
6246
+ let legacyPath = module.exports[key];
6247
+ Object.defineProperty(module.exports, key, {
6248
+ enumerable: true,
6249
+ get() { return scopedStatePath(legacyPath); },
6250
+ set(value) {
6251
+ if (tenantDataScope()) throw new Error('Tenant scope cannot replace shared state paths');
6252
+ legacyPath = value;
6253
+ },
6254
+ });
6255
+ }