thumbgate 1.39.0 → 1.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
- package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +11 -5
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +104 -7
- package/adapters/opencode/opencode.json +1 -1
- package/adapters/strands/strands-middleware.js +31 -4
- package/bin/cli.js +191 -54
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +3 -1
- package/config/post-deploy-marketing-pages.json +4 -4
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/hooks/hooks.json +24 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +87 -33
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/assets/diagrams/hero-thumbs.svg +2 -4
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +5 -6
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +775 -483
- package/public/diagnostic.html +15 -10
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +302 -97
- package/public/install.html +16 -10
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +246 -83
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +163 -66
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/action-receipts.js +393 -0
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/auto-wire-hooks.js +64 -25
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/cli-demo.js +5 -27
- package/scripts/cli-schema.js +25 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/craft-playbook-gate.js +550 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +574 -167
- package/scripts/decision-journal.js +7 -4
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/failure-diagnostics.js +11 -0
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/gate-stats.js +38 -5
- package/scripts/gates-engine.js +1326 -240
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/gitlab-sdlc-prompts.js +397 -0
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hook-runtime.js +10 -0
- package/scripts/hybrid-feedback-context.js +7 -2
- package/scripts/intervention-policy.js +2 -1
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mabl-failure-honesty.js +273 -0
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-distress-detector.js +3 -3
- package/scripts/operational-integrity.js +436 -3
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/product-feedback.js +35 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-eval.js +1 -1
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/qwenwork-policy-group.js +413 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/tailscale-october-access.js +416 -0
- package/scripts/task-outcomes.js +58 -2
- package/scripts/telemetry-analytics.js +260 -16
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/src/api/server.js +2478 -470
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/email-triage-server/index.js +973 -0
- package/src/mcp/email-triage-server/package.json +12 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
package/scripts/gates-engine.js
CHANGED
|
@@ -1,18 +1,28 @@
|
|
|
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');
|
|
6
14
|
const os = require('os');
|
|
7
15
|
const crypto = require('crypto');
|
|
8
|
-
const { execFileSync } = require('child_process');
|
|
16
|
+
const { execFileSync, spawnSync } = require('child_process');
|
|
9
17
|
const { loadOptionalModule } = require('./private-core-boundary');
|
|
10
18
|
|
|
11
19
|
const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES, FREE_TIER_DAILY_BLOCKS, todayKey } = require('./rate-limiter');
|
|
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;
|
|
@@ -186,14 +196,24 @@ const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
|
|
|
186
196
|
'secret-exfiltration',
|
|
187
197
|
'security-vuln-scan',
|
|
188
198
|
'slopsquat-guard',
|
|
199
|
+
'tailscale-october-access',
|
|
200
|
+
'gitlab-sdlc-prompts',
|
|
189
201
|
// Money path: even if a refactor later routes financial denials through
|
|
190
202
|
// applyEnforcementPosture, never demote spend blocks to warn-by-default.
|
|
191
203
|
// Apollo $588 incident class (2026-08).
|
|
192
204
|
'financial-control',
|
|
205
|
+
// Quote reserve and done-check. Sidecar must not turn these denies into warnings.
|
|
206
|
+
'oneshot-control',
|
|
207
|
+
'oneshot-goal-done',
|
|
193
208
|
// Outbound email: irreversible delivery. Keep the hard gate intact until a
|
|
194
209
|
// separately authenticated admin override bound to the exact action digest
|
|
195
210
|
// authorizes one retry (AGENT-259 / District Cyber 2026-08-04).
|
|
196
211
|
'outbound-email-send',
|
|
212
|
+
'outbound-off-brand-vertical-block',
|
|
213
|
+
'swarm-claim-exit-3-write-after-loss',
|
|
214
|
+
'teams-single-reply-per-message',
|
|
215
|
+
'az-repos-pr-publish-requires-cross-review',
|
|
216
|
+
'mabl-failure-honesty',
|
|
197
217
|
TASK_SCOPE_LEASE_EXPIRED_GATE_ID,
|
|
198
218
|
...SELF_PROTECT_HARD_FLOOR_GATE_IDS,
|
|
199
219
|
]);
|
|
@@ -213,14 +233,23 @@ const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
|
|
|
213
233
|
'git-reset-hard',
|
|
214
234
|
'git-clean-force',
|
|
215
235
|
'rm-rf-home-or-root',
|
|
236
|
+
'tailscale-october-access',
|
|
237
|
+
'gitlab-sdlc-prompts',
|
|
216
238
|
'financial-control',
|
|
239
|
+
'oneshot-control',
|
|
240
|
+
'oneshot-goal-done',
|
|
217
241
|
// Never daily-cap discount a denied autonomous email send (same class as force-push).
|
|
218
242
|
'outbound-email-send',
|
|
243
|
+
'outbound-off-brand-vertical-block',
|
|
244
|
+
'swarm-claim-exit-3-write-after-loss',
|
|
245
|
+
'teams-single-reply-per-message',
|
|
246
|
+
'az-repos-pr-publish-requires-cross-review',
|
|
247
|
+
'mabl-failure-honesty',
|
|
219
248
|
]);
|
|
220
249
|
const SELF_PROTECT_CONFIG_TARGET_PATTERN = /(?:^|\/)(?:config\/gates\/|config\/(?:budget|enforcement|mcp-allowlists)\.json$|\.thumbgate\/config\.json$|thumbgate\.json$)/i;
|
|
221
250
|
const SELF_PROTECT_HOOK_TARGET_PATTERN = /(?:^|\/)(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^/]+\.(?:js|sh))$/i;
|
|
222
|
-
const SELF_PROTECT_CONFIG_COMMAND_PATTERN = /(?:config\/gates
|
|
223
|
-
const SELF_PROTECT_HOOK_COMMAND_PATTERN = /(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[
|
|
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;
|
|
224
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;
|
|
225
254
|
|
|
226
255
|
function isSelfProtectGate(gateId) {
|
|
@@ -405,8 +434,9 @@ function isRecursiveChmodCommand(command) {
|
|
|
405
434
|
// Config loading
|
|
406
435
|
// ---------------------------------------------------------------------------
|
|
407
436
|
|
|
408
|
-
function loadGatesConfig(configPath, harnessPath) {
|
|
409
|
-
|
|
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);
|
|
410
440
|
|
|
411
441
|
if (!fs.existsSync(primaryPath)) {
|
|
412
442
|
throw new Error(`Gates config not found: ${primaryPath}`);
|
|
@@ -435,9 +465,11 @@ function loadGatesConfig(configPath, harnessPath) {
|
|
|
435
465
|
|
|
436
466
|
// Always preserve the full primary/default safety policy. Free tier limits apply
|
|
437
467
|
// only to auto-promoted add-on gates so core protections never disappear.
|
|
438
|
-
const autoConfigPath = getAutoGatesPath();
|
|
468
|
+
const autoConfigPath = getAutoGatesPath(options);
|
|
439
469
|
if (!configPath && fs.existsSync(autoConfigPath)) {
|
|
440
|
-
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'); }
|
|
441
473
|
const limitedAutoGates = isProTier()
|
|
442
474
|
? autoGates
|
|
443
475
|
: autoGates.slice(0, FREE_TIER_MAX_GATES);
|
|
@@ -446,7 +478,7 @@ function loadGatesConfig(configPath, harnessPath) {
|
|
|
446
478
|
|
|
447
479
|
// Load workflow-specific harness gates (always additive, never replaces default).
|
|
448
480
|
// Resolved by harness-selector based on tool name + command context.
|
|
449
|
-
const resolvedHarness = harnessPath || process.env.THUMBGATE_HARNESS_CONFIG;
|
|
481
|
+
const resolvedHarness = tenantDataScope() ? null : (harnessPath || process.env.THUMBGATE_HARNESS_CONFIG);
|
|
450
482
|
if (resolvedHarness && fs.existsSync(resolvedHarness)) {
|
|
451
483
|
const harnessGates = (loadOne(resolvedHarness, false) || [])
|
|
452
484
|
.map(g => ({ ...g, layer: g.layer || 'Execution', source: g.source || 'harness' }));
|
|
@@ -470,12 +502,13 @@ function loadJSON(filePath) {
|
|
|
470
502
|
}
|
|
471
503
|
|
|
472
504
|
function saveJSON(filePath, data) {
|
|
505
|
+
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return;
|
|
473
506
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
474
507
|
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n');
|
|
475
508
|
}
|
|
476
509
|
|
|
477
|
-
function loadState() { return loadJSON(module.exports.STATE_PATH); }
|
|
478
|
-
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); }
|
|
479
512
|
|
|
480
513
|
function loadConstraints() { return loadJSON(module.exports.CONSTRAINTS_PATH); }
|
|
481
514
|
function saveConstraints(constraints) { saveJSON(module.exports.CONSTRAINTS_PATH, constraints); }
|
|
@@ -659,10 +692,11 @@ function stableCanonicalStringify(value) {
|
|
|
659
692
|
)).join(',')}}`;
|
|
660
693
|
}
|
|
661
694
|
|
|
662
|
-
function actionApprovalDigest(toolName, toolInput) {
|
|
695
|
+
function actionApprovalDigest(toolName, toolInput, options = {}) {
|
|
663
696
|
return crypto.createHash('sha256').update(stableCanonicalStringify({
|
|
664
697
|
toolInput: toolInput && typeof toolInput === 'object' ? toolInput : {},
|
|
665
698
|
toolName: String(toolName || ''),
|
|
699
|
+
projectKey: gateExecution(toolInput, options).projectKey,
|
|
666
700
|
})).digest('hex');
|
|
667
701
|
}
|
|
668
702
|
|
|
@@ -670,8 +704,8 @@ function adminOverrideTaskId(gateId, digest) {
|
|
|
670
704
|
return `admin-override:${gateId}:${digest}`;
|
|
671
705
|
}
|
|
672
706
|
|
|
673
|
-
function selectAdminOverrideAttempt(baseTaskId) {
|
|
674
|
-
const attempts = listEscalations().filter((entry) => (
|
|
707
|
+
function selectAdminOverrideAttempt(baseTaskId, options = {}) {
|
|
708
|
+
const attempts = listEscalations(options).filter((entry) => (
|
|
675
709
|
entry.taskId === baseTaskId || String(entry.taskId || '').startsWith(`${baseTaskId}:attempt:`)
|
|
676
710
|
));
|
|
677
711
|
const latest = attempts[0] || null;
|
|
@@ -687,15 +721,15 @@ function selectAdminOverrideAttempt(baseTaskId) {
|
|
|
687
721
|
return `${baseTaskId}:attempt:${highestAttempt + 1}`;
|
|
688
722
|
}
|
|
689
723
|
|
|
690
|
-
function evaluateAdminOverride(gate, toolName, toolInput) {
|
|
724
|
+
function evaluateAdminOverride(gate, toolName, toolInput, options = {}) {
|
|
691
725
|
const policy = gate && gate.adminOverride;
|
|
692
726
|
if (!policy || policy.required !== true) return null;
|
|
693
727
|
|
|
694
|
-
const approvalContextDigest = actionApprovalDigest(toolName, toolInput);
|
|
728
|
+
const approvalContextDigest = actionApprovalDigest(toolName, toolInput, options);
|
|
695
729
|
const baseTaskId = adminOverrideTaskId(gate.id, approvalContextDigest);
|
|
696
730
|
let taskId;
|
|
697
731
|
try {
|
|
698
|
-
taskId = selectAdminOverrideAttempt(baseTaskId);
|
|
732
|
+
taskId = selectAdminOverrideAttempt(baseTaskId, options);
|
|
699
733
|
} catch {
|
|
700
734
|
return {
|
|
701
735
|
authorized: false,
|
|
@@ -721,7 +755,7 @@ function evaluateAdminOverride(gate, toolName, toolInput) {
|
|
|
721
755
|
idempotencyKey: taskId,
|
|
722
756
|
approvalContextDigest,
|
|
723
757
|
requiredReviewerRole: 'admin',
|
|
724
|
-
});
|
|
758
|
+
}, options);
|
|
725
759
|
} catch {
|
|
726
760
|
return {
|
|
727
761
|
authorized: false,
|
|
@@ -735,6 +769,7 @@ function evaluateAdminOverride(gate, toolName, toolInput) {
|
|
|
735
769
|
let consumption = null;
|
|
736
770
|
try {
|
|
737
771
|
consumption = consumeVerifiedApproval(escalationId, {
|
|
772
|
+
...options,
|
|
738
773
|
consumer: { id: 'thumbgate-gates-engine', kind: 'service' },
|
|
739
774
|
});
|
|
740
775
|
} catch {
|
|
@@ -958,16 +993,19 @@ function refreshLocalOnlyConstraint(governanceState = loadGovernanceState()) {
|
|
|
958
993
|
}
|
|
959
994
|
}
|
|
960
995
|
|
|
961
|
-
function isConditionSatisfied(conditionId) {
|
|
962
|
-
|
|
963
|
-
const
|
|
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);
|
|
964
1001
|
if (!entry) return false;
|
|
965
1002
|
const age = Date.now() - entry.timestamp;
|
|
966
1003
|
return age < TTL_MS;
|
|
967
1004
|
}
|
|
968
1005
|
|
|
969
1006
|
function satisfyCondition(conditionId, evidence, structuredReasoning, options = {}) {
|
|
970
|
-
|
|
1007
|
+
options = gateExecution({}, options);
|
|
1008
|
+
const state = loadState(options);
|
|
971
1009
|
const entry = {
|
|
972
1010
|
timestamp: Date.now(),
|
|
973
1011
|
evidence: evidence || '',
|
|
@@ -980,8 +1018,12 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
|
|
|
980
1018
|
conclusion: structuredReasoning.conclusion || null,
|
|
981
1019
|
};
|
|
982
1020
|
}
|
|
983
|
-
|
|
984
|
-
|
|
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);
|
|
985
1027
|
|
|
986
1028
|
// Satisfying a gate condition IS an override: it unlocks an action the gate
|
|
987
1029
|
// had blocked. Previously this wrote only to the state store, so an override
|
|
@@ -993,6 +1035,7 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
|
|
|
993
1035
|
// already loads; requiring at call time avoids any circular-init surprise.
|
|
994
1036
|
const { recordOverride } = require('./override-audit');
|
|
995
1037
|
recordOverride({
|
|
1038
|
+
...options,
|
|
996
1039
|
gateId: conditionId,
|
|
997
1040
|
source: options.source || 'cli',
|
|
998
1041
|
actor: options.actor,
|
|
@@ -1011,13 +1054,13 @@ function satisfyCondition(conditionId, evidence, structuredReasoning, options =
|
|
|
1011
1054
|
// Stats tracking
|
|
1012
1055
|
// ---------------------------------------------------------------------------
|
|
1013
1056
|
|
|
1014
|
-
function loadStats() {
|
|
1015
|
-
const stats = loadJSON(module.exports.STATS_PATH);
|
|
1057
|
+
function loadStats(options = {}) {
|
|
1058
|
+
const stats = loadJSON(accountStatePath('gate-stats.json', module.exports.STATS_PATH, options));
|
|
1016
1059
|
if (Object.keys(stats).length === 0) return { blocked: 0, warned: 0, passed: 0, byGate: {} };
|
|
1017
1060
|
return stats;
|
|
1018
1061
|
}
|
|
1019
1062
|
|
|
1020
|
-
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); }
|
|
1021
1064
|
|
|
1022
1065
|
function buildGateActionFingerprint(gateId, options = {}) {
|
|
1023
1066
|
if (options.actionFingerprint) return String(options.actionFingerprint);
|
|
@@ -1038,13 +1081,28 @@ function buildGateActionFingerprint(gateId, options = {}) {
|
|
|
1038
1081
|
);
|
|
1039
1082
|
if (Array.isArray(toolInput.affectedFiles)) parts.push(...toolInput.affectedFiles);
|
|
1040
1083
|
}
|
|
1041
|
-
|
|
1084
|
+
const fingerprint = actionFingerprint(parts);
|
|
1085
|
+
return fingerprint ? `${options.projectKey || 'unassigned'}:${fingerprint}` : null;
|
|
1042
1086
|
}
|
|
1043
1087
|
|
|
1044
1088
|
function recordStat(gateId, action, gate, options = {}) {
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
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
|
+
|
|
1048
1106
|
else if (action === 'approve') stats.pendingApproval = (stats.pendingApproval || 0) + 1;
|
|
1049
1107
|
else if (action === 'log') stats.logged = (stats.logged || 0) + 1;
|
|
1050
1108
|
else stats.passed = (stats.passed || 0) + 1;
|
|
@@ -1061,7 +1119,7 @@ function recordStat(gateId, action, gate, options = {}) {
|
|
|
1061
1119
|
if (action === 'block' || action === 'warn') {
|
|
1062
1120
|
if (!stats.sessionFiredGates) stats.sessionFiredGates = {};
|
|
1063
1121
|
if (!stats.sessionFiredActions) stats.sessionFiredActions = {};
|
|
1064
|
-
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)}`;
|
|
1065
1123
|
if (!stats.sessionFiredGates[sessionKey]) stats.sessionFiredGates[sessionKey] = {};
|
|
1066
1124
|
stats.sessionFiredGates[sessionKey][gateId] = true;
|
|
1067
1125
|
|
|
@@ -1077,13 +1135,13 @@ function recordStat(gateId, action, gate, options = {}) {
|
|
|
1077
1135
|
}
|
|
1078
1136
|
}
|
|
1079
1137
|
|
|
1080
|
-
saveStats(stats);
|
|
1138
|
+
saveStats(stats, options);
|
|
1081
1139
|
// Track lesson freshness when an auto-promoted gate fires
|
|
1082
1140
|
if (gate && gate.sourceLessonId) {
|
|
1083
1141
|
try {
|
|
1084
1142
|
const { recordTrigger } = require('./lesson-rotation');
|
|
1085
1143
|
const { initDB } = require('./lesson-db');
|
|
1086
|
-
const db = initDB();
|
|
1144
|
+
const db = initDB(options.feedbackDir ? path.join(options.feedbackDir, 'lessons.sqlite') : undefined);
|
|
1087
1145
|
recordTrigger(db, gate.sourceLessonId);
|
|
1088
1146
|
db.close();
|
|
1089
1147
|
} catch (_) { /* lesson DB may not be available */ }
|
|
@@ -1128,6 +1186,7 @@ function incrementTodayBlockCount() {
|
|
|
1128
1186
|
* a deny result to a warn with an upgrade CTA. Returns null if no cap applies.
|
|
1129
1187
|
*/
|
|
1130
1188
|
function applyDailyBlockCap(denyResult) {
|
|
1189
|
+
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
|
|
1131
1190
|
// Catastrophic/irreversible commands (force-push, git reset --hard, git
|
|
1132
1191
|
// clean -f, rm -rf on home/root) never get the free-tier daily-cap
|
|
1133
1192
|
// discount — see issue #2782. Checked first, before any tier/CI shortcut,
|
|
@@ -1357,6 +1416,8 @@ function collectInlineAffectedFiles(toolInput = {}, repoRoot) {
|
|
|
1357
1416
|
const scalarFields = [
|
|
1358
1417
|
toolInput.file_path,
|
|
1359
1418
|
toolInput.filePath,
|
|
1419
|
+
toolInput.notebook_path,
|
|
1420
|
+
toolInput.notebookPath,
|
|
1360
1421
|
toolInput.path,
|
|
1361
1422
|
];
|
|
1362
1423
|
for (const field of scalarFields) {
|
|
@@ -1724,6 +1785,7 @@ function patternMatchesCommand(regex, matchText) {
|
|
|
1724
1785
|
}
|
|
1725
1786
|
|
|
1726
1787
|
function extractAffectedFiles(toolName, toolInput = {}) {
|
|
1788
|
+
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return { repoRoot: null, files: [] };
|
|
1727
1789
|
const repoRoot = resolveRepoRoot(toolInput);
|
|
1728
1790
|
const files = new Set(collectInlineAffectedFiles(toolInput, repoRoot));
|
|
1729
1791
|
// Full canonicalization, not just the git-option pass: `"git" add .` and `sudo git add .`
|
|
@@ -1785,7 +1847,7 @@ function isHighRiskAction(toolName, toolInput = {}, affectedFiles = []) {
|
|
|
1785
1847
|
if (toolName !== 'Bash') return false;
|
|
1786
1848
|
const command = String(toolInput.command || '');
|
|
1787
1849
|
// Original high-risk pattern (git writes, publishes, destructive ops)
|
|
1788
|
-
if (HIGH_RISK_BASH_PATTERN.test(command)) return true;
|
|
1850
|
+
if (HIGH_RISK_BASH_PATTERN.test(command) || isDestructiveDeleteCommand(command)) return true;
|
|
1789
1851
|
if (isGhApiPrCreateCommand(command)) return true;
|
|
1790
1852
|
// Broadened: any Bash command that modifies files or has side effects.
|
|
1791
1853
|
// Excludes pure read/analysis commands (node --test, cat, ls, echo, etc.)
|
|
@@ -2077,9 +2139,9 @@ function registerPrThreadResolutionClaimGate(toolName, toolInput = {}, execOverr
|
|
|
2077
2139
|
return claimGate;
|
|
2078
2140
|
}
|
|
2079
2141
|
|
|
2080
|
-
function isThreadResolutionSatisfied() {
|
|
2142
|
+
function isThreadResolutionSatisfied(options = {}) {
|
|
2081
2143
|
return PR_THREAD_RESOLUTION_REQUIRED_ACTIONS.some((actionId) => (
|
|
2082
|
-
hasAction(actionId) || isConditionSatisfied(actionId)
|
|
2144
|
+
hasAction(actionId) || isConditionSatisfied(actionId, options)
|
|
2083
2145
|
));
|
|
2084
2146
|
}
|
|
2085
2147
|
|
|
@@ -2172,7 +2234,7 @@ function isReadOnlyObservabilityTool(toolName) {
|
|
|
2172
2234
|
return names.has(toolName) || names.has(bareToolName(toolName));
|
|
2173
2235
|
}
|
|
2174
2236
|
|
|
2175
|
-
function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}) {
|
|
2237
|
+
function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}, options = {}) {
|
|
2176
2238
|
const pendingEntry = loadSessionActions()[PR_THREAD_RESOLUTION_ACTION];
|
|
2177
2239
|
if (!pendingEntry) return null;
|
|
2178
2240
|
|
|
@@ -2188,7 +2250,7 @@ function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}) {
|
|
|
2188
2250
|
if (currentRepoRoot && currentRepoRoot !== trackedRepoRoot) return null;
|
|
2189
2251
|
}
|
|
2190
2252
|
|
|
2191
|
-
if (isThreadResolutionSatisfied()) return null;
|
|
2253
|
+
if (isThreadResolutionSatisfied(options)) return null;
|
|
2192
2254
|
if (isReadOnlyObservabilityTool(toolName)) return null;
|
|
2193
2255
|
// Evidence actions (gh pr view/checks/status, gh api .../reviewThreads, git
|
|
2194
2256
|
// status/diff/show, the satisfy_gate/track_action tools themselves) are exempt
|
|
@@ -2381,9 +2443,9 @@ function evaluateStatefulHelperBypassGate(toolName, toolInput = {}) {
|
|
|
2381
2443
|
return null;
|
|
2382
2444
|
}
|
|
2383
2445
|
|
|
2384
|
-
function recordStructuralGateBlock(toolName, toolInput, result) {
|
|
2385
|
-
recordStat(result.gate, 'block', null, { toolName, toolInput });
|
|
2386
|
-
const auditRecord = recordAuditEvent({
|
|
2446
|
+
function recordStructuralGateBlock(toolName, toolInput, result, options = {}) {
|
|
2447
|
+
recordStat(result.gate, 'block', null, { ...options, toolName, toolInput });
|
|
2448
|
+
const auditRecord = recordAuditEvent({ ...options,
|
|
2387
2449
|
toolName,
|
|
2388
2450
|
toolInput,
|
|
2389
2451
|
decision: 'deny',
|
|
@@ -2392,7 +2454,7 @@ function recordStructuralGateBlock(toolName, toolInput, result) {
|
|
|
2392
2454
|
severity: result.severity,
|
|
2393
2455
|
source: 'gates-engine',
|
|
2394
2456
|
});
|
|
2395
|
-
auditToFeedback(auditRecord);
|
|
2457
|
+
auditToFeedback(auditRecord, options);
|
|
2396
2458
|
return result;
|
|
2397
2459
|
}
|
|
2398
2460
|
|
|
@@ -2409,7 +2471,7 @@ function recordStructuralGateBlock(toolName, toolInput, result) {
|
|
|
2409
2471
|
* Metric-backed gates are excluded because their condition is asynchronous and
|
|
2410
2472
|
* none of the catastrophic command boundaries may depend on a remote metric.
|
|
2411
2473
|
*/
|
|
2412
|
-
function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, toolInput) {
|
|
2474
|
+
function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, toolInput, options = {}) {
|
|
2413
2475
|
if (!config || !Array.isArray(config.gates)) return null;
|
|
2414
2476
|
|
|
2415
2477
|
for (const gate of config.gates) {
|
|
@@ -2420,10 +2482,10 @@ function evaluateCatastrophicDeclarativeGate(config, constraints, toolName, tool
|
|
|
2420
2482
|
// still unconditional hard floors and cannot be posture/cap downgraded.
|
|
2421
2483
|
if (gate.adminOverride && gate.adminOverride.required === true) continue;
|
|
2422
2484
|
|
|
2423
|
-
const matchDetails = matchGate(gate, toolName, toolInput);
|
|
2485
|
+
const matchDetails = matchGate(gate, toolName, toolInput, options);
|
|
2424
2486
|
if (!matchDetails.matched) continue;
|
|
2425
2487
|
if (gate.when && !checkWhenClause(gate.when, constraints)) continue;
|
|
2426
|
-
if (gate.unless && isConditionSatisfied(gate.unless)) continue;
|
|
2488
|
+
if (gate.unless && isConditionSatisfied(gate.unless, options)) continue;
|
|
2427
2489
|
|
|
2428
2490
|
return {
|
|
2429
2491
|
decision: 'deny',
|
|
@@ -2458,17 +2520,17 @@ function isAgentHookSettingsFile(filePath) {
|
|
|
2458
2520
|
return matchesAnyGlob(filePath, BREAK_GLASS_SETTINGS_GLOBS);
|
|
2459
2521
|
}
|
|
2460
2522
|
|
|
2461
|
-
function isBreakGlassSettingsBypass(gate, affectedFiles) {
|
|
2523
|
+
function isBreakGlassSettingsBypass(gate, affectedFiles, options = {}) {
|
|
2462
2524
|
if (!gate || !['task-scope-edit-boundary', 'protected-file-approval-required'].includes(gate.id)) {
|
|
2463
2525
|
return false;
|
|
2464
2526
|
}
|
|
2465
|
-
if (!isConditionSatisfied(BREAK_GLASS_CONDITION)) return false;
|
|
2527
|
+
if (!isConditionSatisfied(BREAK_GLASS_CONDITION, options)) return false;
|
|
2466
2528
|
return Array.isArray(affectedFiles) && affectedFiles.length > 0 && affectedFiles.every(isAgentHookSettingsFile);
|
|
2467
2529
|
}
|
|
2468
2530
|
|
|
2469
|
-
function isBreakGlassSettingsRecoveryAction(toolName, toolInput = {}) {
|
|
2531
|
+
function isBreakGlassSettingsRecoveryAction(toolName, toolInput = {}, options = {}) {
|
|
2470
2532
|
if (!EDIT_LIKE_TOOLS.has(toolName)) return false;
|
|
2471
|
-
if (!isConditionSatisfied(BREAK_GLASS_CONDITION)) return false;
|
|
2533
|
+
if (!isConditionSatisfied(BREAK_GLASS_CONDITION, options)) return false;
|
|
2472
2534
|
const affectedFiles = extractAffectedFiles(toolName, toolInput).files;
|
|
2473
2535
|
return affectedFiles.length > 0 && affectedFiles.every(isAgentHookSettingsFile);
|
|
2474
2536
|
}
|
|
@@ -2763,10 +2825,19 @@ function buildMatchSurfaces(toolName, toolInput = {}) {
|
|
|
2763
2825
|
push(v);
|
|
2764
2826
|
if (name) push(`${name} ${v}`);
|
|
2765
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
|
+
}
|
|
2766
2836
|
return surfaces;
|
|
2767
2837
|
}
|
|
2768
2838
|
|
|
2769
|
-
function matchGate(gate, toolName, toolInput = {}) {
|
|
2839
|
+
function matchGate(gate, toolName, toolInput = {}, options = {}) {
|
|
2840
|
+
if (!gateAppliesToProject(gate, gateExecution(toolInput, options).projectKey)) return { matched: false };
|
|
2770
2841
|
// Primary text for audit/reasoning: prefer command, then tool name (MCP).
|
|
2771
2842
|
const matchSurfaces = buildMatchSurfaces(toolName, toolInput);
|
|
2772
2843
|
let matchText = matchSurfaces[0] || String(toolName || '');
|
|
@@ -2806,16 +2877,30 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2806
2877
|
if (!matchSurfaces.includes(matchText)) matchSurfaces.push(matchText);
|
|
2807
2878
|
}
|
|
2808
2879
|
|
|
2809
|
-
const affected = extractAffectedFiles(toolName, toolInput);
|
|
2880
|
+
const affected = options.affected || extractAffectedFiles(toolName, toolInput);
|
|
2810
2881
|
const affectedFiles = affected.files;
|
|
2811
2882
|
const repoRoot = affected.repoRoot;
|
|
2812
|
-
const governanceState = loadGovernanceState();
|
|
2813
|
-
const constraints = loadConstraints();
|
|
2883
|
+
const governanceState = options.governanceState || loadGovernanceState();
|
|
2884
|
+
const constraints = options.constraints || loadConstraints();
|
|
2814
2885
|
|
|
2815
2886
|
if (isSelfProtectGate(gate.id) && hasActiveProtectedApproval(governanceState, affectedFiles)) {
|
|
2816
2887
|
return { matched: false, matchText, affectedFiles };
|
|
2817
2888
|
}
|
|
2818
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
|
+
|
|
2819
2904
|
if (gate.id === 'on-demand-freeze-mode' || (gate.when && gate.when.constraints && gate.when.constraints.freeze_mode)) {
|
|
2820
2905
|
let freezePaths = [];
|
|
2821
2906
|
if (process.env.THUMBGATE_FREEZE_PATHS) {
|
|
@@ -2842,6 +2927,18 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2842
2927
|
return { matched: false, matchText, affectedFiles };
|
|
2843
2928
|
}
|
|
2844
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
|
+
|
|
2845
2942
|
if (gate.pattern) {
|
|
2846
2943
|
try {
|
|
2847
2944
|
if (gate.id === 'permission-change-approval') {
|
|
@@ -2866,7 +2963,7 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2866
2963
|
return { matched: false, matchText, affectedFiles };
|
|
2867
2964
|
}
|
|
2868
2965
|
}
|
|
2869
|
-
if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
|
|
2966
|
+
if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
|
|
2870
2967
|
return { matched: false, matchText, affectedFiles };
|
|
2871
2968
|
}
|
|
2872
2969
|
} catch {
|
|
@@ -2886,7 +2983,7 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2886
2983
|
|
|
2887
2984
|
let taskScopeViolation = null;
|
|
2888
2985
|
if (gate.requireTaskScope) {
|
|
2889
|
-
if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
|
|
2986
|
+
if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
|
|
2890
2987
|
return { matched: false, matchText, affectedFiles };
|
|
2891
2988
|
}
|
|
2892
2989
|
if (!shouldEnforceTaskScope(gate, governanceState, toolName, toolInput, affectedFiles)) {
|
|
@@ -2898,7 +2995,7 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2898
2995
|
|
|
2899
2996
|
let protectedApprovalViolation = null;
|
|
2900
2997
|
if (gate.requireProtectedApproval) {
|
|
2901
|
-
if (isBreakGlassSettingsBypass(gate, affectedFiles)) {
|
|
2998
|
+
if (isBreakGlassSettingsBypass(gate, affectedFiles, options)) {
|
|
2902
2999
|
return { matched: false, matchText, affectedFiles };
|
|
2903
3000
|
}
|
|
2904
3001
|
const protectedGlobs = sanitizeGlobList(
|
|
@@ -2935,8 +3032,8 @@ function matchGate(gate, toolName, toolInput = {}) {
|
|
|
2935
3032
|
};
|
|
2936
3033
|
}
|
|
2937
3034
|
|
|
2938
|
-
function matchesGate(gate, toolName, toolInput) {
|
|
2939
|
-
return matchGate(gate, toolName, toolInput).matched;
|
|
3035
|
+
function matchesGate(gate, toolName, toolInput, options = {}) {
|
|
3036
|
+
return matchGate(gate, toolName, toolInput, options).matched;
|
|
2940
3037
|
}
|
|
2941
3038
|
|
|
2942
3039
|
function hasActiveProtectedApproval(governanceState, affectedFiles) {
|
|
@@ -2949,6 +3046,300 @@ function hasActiveProtectedApproval(governanceState, affectedFiles) {
|
|
|
2949
3046
|
}));
|
|
2950
3047
|
}
|
|
2951
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
|
+
|
|
2952
3343
|
function matchSelfProtectHardFloor(gate, toolName, toolInput = {}) {
|
|
2953
3344
|
const affected = extractAffectedFiles(toolName, toolInput);
|
|
2954
3345
|
const affectedFiles = affected.files;
|
|
@@ -2969,26 +3360,8 @@ function matchSelfProtectHardFloor(gate, toolName, toolInput = {}) {
|
|
|
2969
3360
|
? SELF_PROTECT_CONFIG_COMMAND_PATTERN
|
|
2970
3361
|
: SELF_PROTECT_HOOK_COMMAND_PATTERN;
|
|
2971
3362
|
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
const redirectPattern = /(?:^|[\s;&|]|[^\s;&|<>])(?:\d*)>{1,2}\s*([^\s;&|<>]+)/g;
|
|
2975
|
-
const redirectTargets = [];
|
|
2976
|
-
let redirectMatch = redirectPattern.exec(command);
|
|
2977
|
-
while (redirectMatch) {
|
|
2978
|
-
if (redirectMatch[1]) redirectTargets.push(redirectMatch[1]);
|
|
2979
|
-
redirectMatch = redirectPattern.exec(command);
|
|
2980
|
-
}
|
|
2981
|
-
if (redirectTargets.length > 0) {
|
|
2982
|
-
// Deny when any redirect destination is protected.
|
|
2983
|
-
if (redirectTargets.some((target) => commandTargetPattern.test(target))) {
|
|
2984
|
-
// fall through to deny
|
|
2985
|
-
} else if (!SHELL_FILE_MUTATION_PATTERN.test(command) || !commandTargetPattern.test(command)) {
|
|
2986
|
-
// Benign redirects and no other protected mutation → allow.
|
|
2987
|
-
return null;
|
|
2988
|
-
}
|
|
2989
|
-
// Benign redirects but command still mutates a protected path another way → deny.
|
|
2990
|
-
} else {
|
|
2991
|
-
if (!SHELL_FILE_MUTATION_PATTERN.test(command) || !commandTargetPattern.test(command)) return null;
|
|
3363
|
+
if (!doesBashCommandMutateProtectedTarget(command, commandTargetPattern)) {
|
|
3364
|
+
return null;
|
|
2992
3365
|
}
|
|
2993
3366
|
} else {
|
|
2994
3367
|
return null;
|
|
@@ -3055,7 +3428,7 @@ function isSafeLocalCredentialHardeningCommand(toolName, toolInput = {}) {
|
|
|
3055
3428
|
return looksLikeCredentialPath;
|
|
3056
3429
|
}
|
|
3057
3430
|
|
|
3058
|
-
function evaluateMemoryGuard(toolName, toolInput = {}) {
|
|
3431
|
+
function evaluateMemoryGuard(toolName, toolInput = {}, options = {}) {
|
|
3059
3432
|
const affected = extractAffectedFiles(toolName, toolInput);
|
|
3060
3433
|
const affectedFiles = affected.files;
|
|
3061
3434
|
if (isSafeSecretStorageWrite(toolName, toolInput, process.cwd())) {
|
|
@@ -3084,7 +3457,7 @@ function evaluateMemoryGuard(toolName, toolInput = {}) {
|
|
|
3084
3457
|
const isPrCreateCommand = toolName === 'Bash' && (
|
|
3085
3458
|
/\bgh\s+pr\s+create\b/i.test(command) || isGhApiPrCreateCommand(command)
|
|
3086
3459
|
);
|
|
3087
|
-
if (isPrCreateCommand && isConditionSatisfied('pr_create_allowed')) {
|
|
3460
|
+
if (isPrCreateCommand && isConditionSatisfied('pr_create_allowed', options)) {
|
|
3088
3461
|
const branchGovernanceViolation = buildBranchGovernanceViolation(
|
|
3089
3462
|
governanceState,
|
|
3090
3463
|
toolInput,
|
|
@@ -3148,9 +3521,9 @@ function evaluateMemoryGuard(toolName, toolInput = {}) {
|
|
|
3148
3521
|
let guard;
|
|
3149
3522
|
if (toolInput && (toolInput.clawContext || toolInput._claw || toolInput.hybridRoute || toolInput.agentId)) {
|
|
3150
3523
|
const clawCtx = toolInput.clawContext || toolInput._claw || { actionType: toolInput.actionType || 'unknown', agentId: toolInput.agentId || 'unknown', hybridRoute: toolInput.hybridRoute || 'unknown' };
|
|
3151
|
-
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);
|
|
3152
3525
|
} else {
|
|
3153
|
-
guard = hybrid.evaluatePretool(toolName, serializedInput);
|
|
3526
|
+
guard = hybrid.evaluatePretool(toolName, serializedInput, options);
|
|
3154
3527
|
}
|
|
3155
3528
|
if (!guard || guard.mode !== 'block') {
|
|
3156
3529
|
return null;
|
|
@@ -3192,8 +3565,8 @@ function buildSentinelGateResult(report) {
|
|
|
3192
3565
|
};
|
|
3193
3566
|
}
|
|
3194
3567
|
|
|
3195
|
-
function recordSentinelDecision(report, toolName, toolInput) {
|
|
3196
|
-
if (!report) return null;
|
|
3568
|
+
function recordSentinelDecision(report, toolName, toolInput, options = {}) {
|
|
3569
|
+
if (!report || process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
|
|
3197
3570
|
const entry = recordDecisionEvaluation(report, {
|
|
3198
3571
|
source: 'gates-engine',
|
|
3199
3572
|
toolName,
|
|
@@ -3201,7 +3574,7 @@ function recordSentinelDecision(report, toolName, toolInput) {
|
|
|
3201
3574
|
changedFiles: report && report.blastRadius && Array.isArray(report.blastRadius.affectedFiles)
|
|
3202
3575
|
? report.blastRadius.affectedFiles
|
|
3203
3576
|
: [],
|
|
3204
|
-
});
|
|
3577
|
+
}, options);
|
|
3205
3578
|
report.actionId = entry.actionId;
|
|
3206
3579
|
if (report.decisionControl && !report.decisionControl.actionId) {
|
|
3207
3580
|
report.decisionControl.actionId = entry.actionId;
|
|
@@ -3209,7 +3582,7 @@ function recordSentinelDecision(report, toolName, toolInput) {
|
|
|
3209
3582
|
return entry;
|
|
3210
3583
|
}
|
|
3211
3584
|
|
|
3212
|
-
function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard) {
|
|
3585
|
+
function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, options = {}) {
|
|
3213
3586
|
if (!sentinelDecision) return;
|
|
3214
3587
|
recordDecisionOutcome({
|
|
3215
3588
|
actionId: sentinelDecision.actionId,
|
|
@@ -3218,10 +3591,10 @@ function recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard) {
|
|
|
3218
3591
|
actor: 'system',
|
|
3219
3592
|
source: 'gates-engine',
|
|
3220
3593
|
notes: enrichedMemoryGuard.message,
|
|
3221
|
-
});
|
|
3594
|
+
}, options);
|
|
3222
3595
|
}
|
|
3223
3596
|
|
|
3224
|
-
function recordSentinelBlockDecision(sentinelDecision, sentinelResult) {
|
|
3597
|
+
function recordSentinelBlockDecision(sentinelDecision, sentinelResult, options = {}) {
|
|
3225
3598
|
if (!sentinelDecision) return;
|
|
3226
3599
|
recordDecisionOutcome({
|
|
3227
3600
|
actionId: sentinelDecision.actionId,
|
|
@@ -3230,7 +3603,7 @@ function recordSentinelBlockDecision(sentinelDecision, sentinelResult) {
|
|
|
3230
3603
|
actor: 'system',
|
|
3231
3604
|
source: 'workflow-sentinel',
|
|
3232
3605
|
notes: sentinelResult.message,
|
|
3233
|
-
});
|
|
3606
|
+
}, options);
|
|
3234
3607
|
}
|
|
3235
3608
|
|
|
3236
3609
|
function enrichResultWithSentinel(result, report) {
|
|
@@ -3282,7 +3655,8 @@ function isAutonomousRun() {
|
|
|
3282
3655
|
return raw === '1' || raw === 'true';
|
|
3283
3656
|
}
|
|
3284
3657
|
|
|
3285
|
-
async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
3658
|
+
async function evaluateGatesAsyncInner(toolName, toolInput, configPath, options = {}) {
|
|
3659
|
+
const execution = gateExecution(toolInput, options);
|
|
3286
3660
|
let config;
|
|
3287
3661
|
try {
|
|
3288
3662
|
let harnessPath;
|
|
@@ -3305,13 +3679,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3305
3679
|
severity: 'high',
|
|
3306
3680
|
message: burst.message,
|
|
3307
3681
|
receipt: 'threat_defense_interdicted=true:type=RateBurst:action=block',
|
|
3308
|
-
});
|
|
3682
|
+
}, execution);
|
|
3309
3683
|
}
|
|
3310
3684
|
}
|
|
3311
3685
|
}
|
|
3312
3686
|
} catch { /* optional */ }
|
|
3313
3687
|
} catch { /* harness-selector is optional */ }
|
|
3314
|
-
config = loadGatesConfig(configPath, harnessPath);
|
|
3688
|
+
config = loadGatesConfig(configPath, harnessPath, execution);
|
|
3315
3689
|
} catch {
|
|
3316
3690
|
return null;
|
|
3317
3691
|
}
|
|
@@ -3326,18 +3700,18 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3326
3700
|
constraints,
|
|
3327
3701
|
);
|
|
3328
3702
|
if (localOnlyRemoteSideEffectGate) {
|
|
3329
|
-
return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate);
|
|
3703
|
+
return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate, execution);
|
|
3330
3704
|
}
|
|
3331
3705
|
const statefulHelperBypassGate = evaluateStatefulHelperBypassGate(toolName, toolInput);
|
|
3332
3706
|
if (statefulHelperBypassGate) {
|
|
3333
|
-
return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate);
|
|
3707
|
+
return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate, execution);
|
|
3334
3708
|
}
|
|
3335
3709
|
const stealthMemoryInjectionGate = evaluateStealthMemoryInjection(toolName, toolInput);
|
|
3336
3710
|
if (stealthMemoryInjectionGate) {
|
|
3337
|
-
return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate);
|
|
3711
|
+
return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate, execution);
|
|
3338
3712
|
}
|
|
3339
|
-
if (isBreakGlassSettingsRecoveryAction(toolName, toolInput)) {
|
|
3340
|
-
recordAuditEvent({
|
|
3713
|
+
if (isBreakGlassSettingsRecoveryAction(toolName, toolInput, execution)) {
|
|
3714
|
+
recordAuditEvent({ ...execution,
|
|
3341
3715
|
toolName,
|
|
3342
3716
|
toolInput,
|
|
3343
3717
|
decision: 'allow',
|
|
@@ -3351,8 +3725,8 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3351
3725
|
|
|
3352
3726
|
const agentIdentityLifecycleGate = evaluateAgentIdentityLifecycleGate(toolName, toolInput);
|
|
3353
3727
|
if (agentIdentityLifecycleGate) {
|
|
3354
|
-
recordStat(agentIdentityLifecycleGate.gate, 'block', null, { toolName, toolInput });
|
|
3355
|
-
const identityAuditRecord = recordAuditEvent({
|
|
3728
|
+
recordStat(agentIdentityLifecycleGate.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
3729
|
+
const identityAuditRecord = recordAuditEvent({ ...execution,
|
|
3356
3730
|
toolName,
|
|
3357
3731
|
toolInput,
|
|
3358
3732
|
decision: 'deny',
|
|
@@ -3365,10 +3739,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3365
3739
|
return agentIdentityLifecycleGate;
|
|
3366
3740
|
}
|
|
3367
3741
|
|
|
3368
|
-
const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput);
|
|
3742
|
+
const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput, execution);
|
|
3369
3743
|
if (pendingThreadResolutionGate) {
|
|
3370
|
-
recordStat(pendingThreadResolutionGate.gate, 'block', null, { toolName, toolInput });
|
|
3371
|
-
const auditRecord = recordAuditEvent({
|
|
3744
|
+
recordStat(pendingThreadResolutionGate.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
3745
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3372
3746
|
toolName,
|
|
3373
3747
|
toolInput,
|
|
3374
3748
|
decision: 'deny',
|
|
@@ -3377,14 +3751,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3377
3751
|
severity: pendingThreadResolutionGate.severity,
|
|
3378
3752
|
source: 'gates-engine',
|
|
3379
3753
|
});
|
|
3380
|
-
auditToFeedback(auditRecord);
|
|
3754
|
+
auditToFeedback(auditRecord, execution);
|
|
3381
3755
|
return pendingThreadResolutionGate;
|
|
3382
3756
|
}
|
|
3383
3757
|
|
|
3384
3758
|
const boostedRiskGuard = evaluateBoostedRiskTagGuard(toolName, toolInput);
|
|
3385
3759
|
if (boostedRiskGuard) {
|
|
3386
|
-
recordStat(boostedRiskGuard.gate, 'block', null, { toolName, toolInput });
|
|
3387
|
-
const auditRecord = recordAuditEvent({
|
|
3760
|
+
recordStat(boostedRiskGuard.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
3761
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3388
3762
|
toolName,
|
|
3389
3763
|
toolInput,
|
|
3390
3764
|
decision: 'deny',
|
|
@@ -3393,7 +3767,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3393
3767
|
severity: boostedRiskGuard.severity,
|
|
3394
3768
|
source: 'gates-engine',
|
|
3395
3769
|
});
|
|
3396
|
-
auditToFeedback(auditRecord);
|
|
3770
|
+
auditToFeedback(auditRecord, execution);
|
|
3397
3771
|
return boostedRiskGuard;
|
|
3398
3772
|
}
|
|
3399
3773
|
|
|
@@ -3402,9 +3776,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3402
3776
|
constraints,
|
|
3403
3777
|
toolName,
|
|
3404
3778
|
toolInput,
|
|
3779
|
+
execution,
|
|
3405
3780
|
);
|
|
3406
3781
|
if (catastrophicDeclarativeGate) {
|
|
3407
|
-
return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate);
|
|
3782
|
+
return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate, execution);
|
|
3408
3783
|
}
|
|
3409
3784
|
|
|
3410
3785
|
// Tier 1b: Planning and Trajectory (v1.26.0 - CodeRabbit Pattern).
|
|
@@ -3413,13 +3788,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3413
3788
|
if (isRuntimePlanGateEnabled()) {
|
|
3414
3789
|
const planGate = evaluatePlanGate(toolName, toolInput);
|
|
3415
3790
|
if (planGate) {
|
|
3416
|
-
recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
|
|
3791
|
+
recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
|
|
3417
3792
|
return planGate;
|
|
3418
3793
|
}
|
|
3419
3794
|
|
|
3420
3795
|
const trajectory = getTrajectoryScore();
|
|
3421
3796
|
if (trajectory.isDrifting) {
|
|
3422
|
-
recordStat('strategic-drift', 'block', null, { toolName, toolInput });
|
|
3797
|
+
recordStat('strategic-drift', 'block', null, { ...execution, toolName, toolInput });
|
|
3423
3798
|
return { decision: 'deny', gate: 'strategic-drift', message: trajectory.message, severity: 'high' };
|
|
3424
3799
|
}
|
|
3425
3800
|
}
|
|
@@ -3428,8 +3803,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3428
3803
|
const METRIC_SKIP_TOOLS = ['capture_feedback', 'feedback_stats', 'recall', 'feedback_summary', 'prevention_rules'];
|
|
3429
3804
|
const skipMetrics = METRIC_SKIP_TOOLS.includes(toolName);
|
|
3430
3805
|
|
|
3806
|
+
const sharedAffectedAsync = extractAffectedFiles(toolName, toolInput);
|
|
3431
3807
|
for (const gate of config.gates) {
|
|
3432
|
-
|
|
3808
|
+
if (!gateAppliesToProject(gate, execution.projectKey)) continue;
|
|
3809
|
+
const matchDetails = matchGate(gate, toolName, toolInput, { ...execution, affected: sharedAffectedAsync, governanceState, constraints });
|
|
3433
3810
|
if (!matchDetails.matched) continue;
|
|
3434
3811
|
|
|
3435
3812
|
// EvoSkill Hardening: check contextual 'when' clause
|
|
@@ -3458,7 +3835,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3458
3835
|
}
|
|
3459
3836
|
|
|
3460
3837
|
// Check unless condition
|
|
3461
|
-
if (gate.unless && isConditionSatisfied(gate.unless)) {
|
|
3838
|
+
if (gate.unless && isConditionSatisfied(gate.unless, execution)) {
|
|
3462
3839
|
continue;
|
|
3463
3840
|
}
|
|
3464
3841
|
|
|
@@ -3469,10 +3846,10 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3469
3846
|
});
|
|
3470
3847
|
|
|
3471
3848
|
if (gate.action === 'block') {
|
|
3472
|
-
const adminOverride = evaluateAdminOverride(gate, toolName, toolInput);
|
|
3849
|
+
const adminOverride = evaluateAdminOverride(gate, toolName, toolInput, execution);
|
|
3473
3850
|
if (adminOverride && adminOverride.authorized) {
|
|
3474
|
-
recordStat(gate.id, 'approve', gate, { toolName, toolInput });
|
|
3475
|
-
const auditRecord = recordAuditEvent({
|
|
3851
|
+
recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
|
|
3852
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3476
3853
|
toolName,
|
|
3477
3854
|
toolInput,
|
|
3478
3855
|
decision: 'allow',
|
|
@@ -3481,7 +3858,7 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3481
3858
|
severity: gate.severity,
|
|
3482
3859
|
source: 'gates-engine-admin-override',
|
|
3483
3860
|
});
|
|
3484
|
-
auditToFeedback(auditRecord);
|
|
3861
|
+
auditToFeedback(auditRecord, execution);
|
|
3485
3862
|
return {
|
|
3486
3863
|
decision: 'allow',
|
|
3487
3864
|
gate: gate.id,
|
|
@@ -3511,14 +3888,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3511
3888
|
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
3512
3889
|
const cappedResult = applyDailyBlockCap(denyResult);
|
|
3513
3890
|
if (cappedResult) {
|
|
3514
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
3515
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
3516
|
-
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);
|
|
3517
3894
|
return cappedResult;
|
|
3518
3895
|
}
|
|
3519
|
-
recordStat(gate.id, 'block', gate, { toolName, toolInput });
|
|
3520
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
3521
|
-
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);
|
|
3522
3899
|
return denyResult;
|
|
3523
3900
|
}
|
|
3524
3901
|
|
|
@@ -3529,38 +3906,38 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3529
3906
|
// Autonomous run: no human to approve. Fail CLOSED so the actions that
|
|
3530
3907
|
// most need sign-off cannot slip through unattended.
|
|
3531
3908
|
const failClosedMessage = `[autonomous run — no approver present, failing closed] ${message}`;
|
|
3532
|
-
recordStat(gate.id, 'block', gate, { toolName, toolInput });
|
|
3533
|
-
const failClosedAudit = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
|
|
3534
|
-
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);
|
|
3535
3912
|
return { decision: 'deny', gate: gate.id, message: failClosedMessage, severity: gate.severity, reasoning, requiresApproval: true, failedClosed: true };
|
|
3536
3913
|
}
|
|
3537
|
-
recordStat(gate.id, 'approve', gate, { toolName, toolInput });
|
|
3914
|
+
recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
|
|
3538
3915
|
const result = { decision: 'approve', gate: gate.id, message, severity: gate.severity, reasoning, requiresApproval: true };
|
|
3539
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3540
|
-
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);
|
|
3541
3918
|
return result;
|
|
3542
3919
|
}
|
|
3543
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
3920
|
+
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3544
3921
|
const result = { decision: 'warn', gate: gate.id, message: `[approval gate disabled] ${message}`, severity: gate.severity, reasoning };
|
|
3545
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3546
|
-
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);
|
|
3547
3924
|
return result;
|
|
3548
3925
|
}
|
|
3549
3926
|
|
|
3550
3927
|
if (gate.action === 'log') {
|
|
3551
|
-
recordStat(gate.id, 'log', gate, { toolName, toolInput });
|
|
3928
|
+
recordStat(gate.id, 'log', gate, { ...execution, toolName, toolInput });
|
|
3552
3929
|
const result = { decision: 'log', gate: gate.id, message, severity: gate.severity, reasoning, logged: true };
|
|
3553
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3554
|
-
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);
|
|
3555
3932
|
// 'log' action allows the tool call to proceed — do not return early, continue to next gate
|
|
3556
3933
|
continue;
|
|
3557
3934
|
}
|
|
3558
3935
|
|
|
3559
3936
|
if (gate.action === 'warn') {
|
|
3560
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
3937
|
+
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3561
3938
|
const result = { decision: 'warn', gate: gate.id, 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);
|
|
3939
|
+
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3940
|
+
auditToFeedback(auditRecord, execution);
|
|
3564
3941
|
return result;
|
|
3565
3942
|
}
|
|
3566
3943
|
}
|
|
@@ -3569,13 +3946,13 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3569
3946
|
const sentinelReport = skipAdvisoryGuards ? null : evaluateWorkflowSentinel(toolName, toolInput, {
|
|
3570
3947
|
governanceState,
|
|
3571
3948
|
});
|
|
3572
|
-
const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput);
|
|
3573
|
-
const memoryGuard = evaluateMemoryGuard(toolName, toolInput);
|
|
3949
|
+
const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput, execution);
|
|
3950
|
+
const memoryGuard = evaluateMemoryGuard(toolName, toolInput, execution);
|
|
3574
3951
|
if (memoryGuard) {
|
|
3575
3952
|
const enrichedMemoryGuard = enrichResultWithSentinel(memoryGuard, sentinelReport);
|
|
3576
|
-
recordStat(enrichedMemoryGuard.gate, 'block', null, { toolName, toolInput });
|
|
3577
|
-
recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard);
|
|
3578
|
-
const auditRecord = recordAuditEvent({
|
|
3953
|
+
recordStat(enrichedMemoryGuard.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
3954
|
+
recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, execution);
|
|
3955
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3579
3956
|
toolName,
|
|
3580
3957
|
toolInput,
|
|
3581
3958
|
decision: 'deny',
|
|
@@ -3584,15 +3961,15 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3584
3961
|
severity: enrichedMemoryGuard.severity,
|
|
3585
3962
|
source: 'gates-engine',
|
|
3586
3963
|
});
|
|
3587
|
-
auditToFeedback(auditRecord);
|
|
3964
|
+
auditToFeedback(auditRecord, execution);
|
|
3588
3965
|
return enrichedMemoryGuard;
|
|
3589
3966
|
}
|
|
3590
3967
|
|
|
3591
3968
|
if (sentinelReport && sentinelReport.decision !== 'allow') {
|
|
3592
3969
|
const sentinelResult = buildSentinelGateResult(sentinelReport);
|
|
3593
|
-
recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
|
|
3594
|
-
recordSentinelBlockDecision(sentinelDecision, sentinelResult);
|
|
3595
|
-
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,
|
|
3596
3973
|
toolName,
|
|
3597
3974
|
toolInput,
|
|
3598
3975
|
decision: sentinelResult.decision,
|
|
@@ -3601,14 +3978,14 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3601
3978
|
severity: sentinelResult.severity,
|
|
3602
3979
|
source: 'workflow-sentinel',
|
|
3603
3980
|
});
|
|
3604
|
-
auditToFeedback(auditRecord);
|
|
3981
|
+
auditToFeedback(auditRecord, execution);
|
|
3605
3982
|
return sentinelResult;
|
|
3606
3983
|
}
|
|
3607
3984
|
|
|
3608
3985
|
const brokerReceiptResultAsync = evaluateBrokerReceiptGate(toolName, toolInput);
|
|
3609
3986
|
if (brokerReceiptResultAsync && brokerReceiptResultAsync.decision === 'deny') {
|
|
3610
|
-
recordStat(brokerReceiptResultAsync.gate, 'block', null, { toolName, toolInput });
|
|
3611
|
-
const auditRecord = recordAuditEvent({
|
|
3987
|
+
recordStat(brokerReceiptResultAsync.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
3988
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3612
3989
|
toolName,
|
|
3613
3990
|
toolInput,
|
|
3614
3991
|
decision: 'deny',
|
|
@@ -3617,20 +3994,21 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath) {
|
|
|
3617
3994
|
severity: brokerReceiptResultAsync.severity,
|
|
3618
3995
|
source: 'broker-execution-receipts',
|
|
3619
3996
|
});
|
|
3620
|
-
auditToFeedback(auditRecord);
|
|
3997
|
+
auditToFeedback(auditRecord, execution);
|
|
3621
3998
|
return brokerReceiptResultAsync;
|
|
3622
3999
|
}
|
|
3623
4000
|
|
|
3624
4001
|
// Audit trail: record allow (no gate matched)
|
|
3625
|
-
recordAuditEvent({ toolName, toolInput, decision: 'allow', source: 'gates-engine' });
|
|
4002
|
+
recordAuditEvent({ ...execution, toolName, toolInput, decision: 'allow', source: 'gates-engine' });
|
|
3626
4003
|
return null;
|
|
3627
4004
|
}
|
|
3628
4005
|
|
|
3629
|
-
function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
4006
|
+
function evaluateGatesInner(toolName, toolInput, configPath, options = {}) {
|
|
4007
|
+
const execution = gateExecution(toolInput, options);
|
|
3630
4008
|
let config;
|
|
3631
4009
|
try {
|
|
3632
4010
|
let harnessPath;
|
|
3633
|
-
try {
|
|
4011
|
+
if (process.env.THUMBGATE_SANDBOX_EVAL !== '1') try {
|
|
3634
4012
|
const { selectHarness } = require('./harness-selector');
|
|
3635
4013
|
harnessPath = selectHarness(toolName, toolInput);
|
|
3636
4014
|
try {
|
|
@@ -3649,13 +4027,13 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3649
4027
|
severity: 'high',
|
|
3650
4028
|
message: burst.message,
|
|
3651
4029
|
receipt: 'threat_defense_interdicted=true:type=RateBurst:action=block',
|
|
3652
|
-
});
|
|
4030
|
+
}, execution);
|
|
3653
4031
|
}
|
|
3654
4032
|
}
|
|
3655
4033
|
}
|
|
3656
4034
|
} catch { /* optional */ }
|
|
3657
4035
|
} catch { /* harness-selector is optional */ }
|
|
3658
|
-
config = loadGatesConfig(configPath, harnessPath);
|
|
4036
|
+
config = loadGatesConfig(configPath, harnessPath, execution);
|
|
3659
4037
|
} catch {
|
|
3660
4038
|
// If config can't be loaded, pass through
|
|
3661
4039
|
return null;
|
|
@@ -3671,18 +4049,18 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3671
4049
|
constraints,
|
|
3672
4050
|
);
|
|
3673
4051
|
if (localOnlyRemoteSideEffectGate) {
|
|
3674
|
-
return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate);
|
|
4052
|
+
return recordStructuralGateBlock(toolName, toolInput, localOnlyRemoteSideEffectGate, execution);
|
|
3675
4053
|
}
|
|
3676
4054
|
const statefulHelperBypassGate = evaluateStatefulHelperBypassGate(toolName, toolInput);
|
|
3677
4055
|
if (statefulHelperBypassGate) {
|
|
3678
|
-
return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate);
|
|
4056
|
+
return recordStructuralGateBlock(toolName, toolInput, statefulHelperBypassGate, execution);
|
|
3679
4057
|
}
|
|
3680
4058
|
const stealthMemoryInjectionGate = evaluateStealthMemoryInjection(toolName, toolInput);
|
|
3681
4059
|
if (stealthMemoryInjectionGate) {
|
|
3682
|
-
return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate);
|
|
4060
|
+
return recordStructuralGateBlock(toolName, toolInput, stealthMemoryInjectionGate, execution);
|
|
3683
4061
|
}
|
|
3684
|
-
if (isBreakGlassSettingsRecoveryAction(toolName, toolInput)) {
|
|
3685
|
-
recordAuditEvent({
|
|
4062
|
+
if (isBreakGlassSettingsRecoveryAction(toolName, toolInput, execution)) {
|
|
4063
|
+
recordAuditEvent({ ...execution,
|
|
3686
4064
|
toolName,
|
|
3687
4065
|
toolInput,
|
|
3688
4066
|
decision: 'allow',
|
|
@@ -3696,8 +4074,8 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3696
4074
|
|
|
3697
4075
|
const agentIdentityLifecycleGate = evaluateAgentIdentityLifecycleGate(toolName, toolInput);
|
|
3698
4076
|
if (agentIdentityLifecycleGate) {
|
|
3699
|
-
recordStat(agentIdentityLifecycleGate.gate, 'block', null, { toolName, toolInput });
|
|
3700
|
-
const identityAuditRecord = recordAuditEvent({
|
|
4077
|
+
recordStat(agentIdentityLifecycleGate.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
4078
|
+
const identityAuditRecord = recordAuditEvent({ ...execution,
|
|
3701
4079
|
toolName,
|
|
3702
4080
|
toolInput,
|
|
3703
4081
|
decision: 'deny',
|
|
@@ -3710,10 +4088,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3710
4088
|
return agentIdentityLifecycleGate;
|
|
3711
4089
|
}
|
|
3712
4090
|
|
|
3713
|
-
const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput);
|
|
4091
|
+
const pendingThreadResolutionGate = evaluatePendingPrThreadResolutionGate(toolName, toolInput, execution);
|
|
3714
4092
|
if (pendingThreadResolutionGate) {
|
|
3715
|
-
recordStat(pendingThreadResolutionGate.gate, 'block', null, { toolName, toolInput });
|
|
3716
|
-
const auditRecord = recordAuditEvent({
|
|
4093
|
+
recordStat(pendingThreadResolutionGate.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
4094
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3717
4095
|
toolName,
|
|
3718
4096
|
toolInput,
|
|
3719
4097
|
decision: 'deny',
|
|
@@ -3722,14 +4100,14 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3722
4100
|
severity: pendingThreadResolutionGate.severity,
|
|
3723
4101
|
source: 'gates-engine',
|
|
3724
4102
|
});
|
|
3725
|
-
auditToFeedback(auditRecord);
|
|
4103
|
+
auditToFeedback(auditRecord, execution);
|
|
3726
4104
|
return pendingThreadResolutionGate;
|
|
3727
4105
|
}
|
|
3728
4106
|
|
|
3729
|
-
const boostedRiskGuard = evaluateBoostedRiskTagGuard(toolName, toolInput);
|
|
4107
|
+
const boostedRiskGuard = process.env.THUMBGATE_SANDBOX_EVAL === '1' ? null : evaluateBoostedRiskTagGuard(toolName, toolInput);
|
|
3730
4108
|
if (boostedRiskGuard) {
|
|
3731
|
-
recordStat(boostedRiskGuard.gate, 'block', null, { toolName, toolInput });
|
|
3732
|
-
const auditRecord = recordAuditEvent({
|
|
4109
|
+
recordStat(boostedRiskGuard.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
4110
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3733
4111
|
toolName,
|
|
3734
4112
|
toolInput,
|
|
3735
4113
|
decision: 'deny',
|
|
@@ -3738,7 +4116,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3738
4116
|
severity: boostedRiskGuard.severity,
|
|
3739
4117
|
source: 'gates-engine',
|
|
3740
4118
|
});
|
|
3741
|
-
auditToFeedback(auditRecord);
|
|
4119
|
+
auditToFeedback(auditRecord, execution);
|
|
3742
4120
|
return boostedRiskGuard;
|
|
3743
4121
|
}
|
|
3744
4122
|
|
|
@@ -3747,9 +4125,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3747
4125
|
constraints,
|
|
3748
4126
|
toolName,
|
|
3749
4127
|
toolInput,
|
|
4128
|
+
execution,
|
|
3750
4129
|
);
|
|
3751
4130
|
if (catastrophicDeclarativeGate) {
|
|
3752
|
-
return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate);
|
|
4131
|
+
return recordStructuralGateBlock(toolName, toolInput, catastrophicDeclarativeGate, execution);
|
|
3753
4132
|
}
|
|
3754
4133
|
|
|
3755
4134
|
// Tier 1b: Planning and Trajectory (v1.26.0 - CodeRabbit Pattern).
|
|
@@ -3758,19 +4137,20 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3758
4137
|
if (isRuntimePlanGateEnabled()) {
|
|
3759
4138
|
const planGate = evaluatePlanGate(toolName, toolInput);
|
|
3760
4139
|
if (planGate) {
|
|
3761
|
-
recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
|
|
4140
|
+
recordStat(planGate.gate, planGate.decision === 'deny' ? 'block' : 'warn', null, { ...execution, toolName, toolInput });
|
|
3762
4141
|
return planGate;
|
|
3763
4142
|
}
|
|
3764
4143
|
|
|
3765
4144
|
const trajectory = getTrajectoryScore();
|
|
3766
4145
|
if (trajectory.isDrifting) {
|
|
3767
|
-
recordStat('strategic-drift', 'block', null, { toolName, toolInput });
|
|
4146
|
+
recordStat('strategic-drift', 'block', null, { ...execution, toolName, toolInput });
|
|
3768
4147
|
return { decision: 'deny', gate: 'strategic-drift', message: trajectory.message, severity: 'high' };
|
|
3769
4148
|
}
|
|
3770
4149
|
}
|
|
3771
|
-
|
|
4150
|
+
const sharedAffected = extractAffectedFiles(toolName, toolInput);
|
|
3772
4151
|
for (const gate of config.gates) {
|
|
3773
|
-
|
|
4152
|
+
if (!gateAppliesToProject(gate, execution.projectKey)) continue;
|
|
4153
|
+
const matchDetails = matchGate(gate, toolName, toolInput, { ...execution, affected: sharedAffected, governanceState, constraints });
|
|
3774
4154
|
if (!matchDetails.matched) continue;
|
|
3775
4155
|
|
|
3776
4156
|
// EvoSkill Hardening: check contextual 'when' clause
|
|
@@ -3779,7 +4159,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3779
4159
|
}
|
|
3780
4160
|
|
|
3781
4161
|
// Check unless condition
|
|
3782
|
-
if (gate.unless && isConditionSatisfied(gate.unless)) {
|
|
4162
|
+
if (gate.unless && isConditionSatisfied(gate.unless, execution)) {
|
|
3783
4163
|
continue;
|
|
3784
4164
|
}
|
|
3785
4165
|
|
|
@@ -3787,10 +4167,10 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3787
4167
|
const reasoning = buildReasoning(gate, toolName, toolInput, matchDetails);
|
|
3788
4168
|
|
|
3789
4169
|
if (gate.action === 'block') {
|
|
3790
|
-
const adminOverride = evaluateAdminOverride(gate, toolName, toolInput);
|
|
4170
|
+
const adminOverride = evaluateAdminOverride(gate, toolName, toolInput, execution);
|
|
3791
4171
|
if (adminOverride && adminOverride.authorized) {
|
|
3792
|
-
recordStat(gate.id, 'approve', gate, { toolName, toolInput });
|
|
3793
|
-
const auditRecord = recordAuditEvent({
|
|
4172
|
+
recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
|
|
4173
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3794
4174
|
toolName,
|
|
3795
4175
|
toolInput,
|
|
3796
4176
|
decision: 'allow',
|
|
@@ -3799,7 +4179,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3799
4179
|
severity: gate.severity,
|
|
3800
4180
|
source: 'gates-engine-admin-override',
|
|
3801
4181
|
});
|
|
3802
|
-
auditToFeedback(auditRecord);
|
|
4182
|
+
auditToFeedback(auditRecord, execution);
|
|
3803
4183
|
return {
|
|
3804
4184
|
decision: 'allow',
|
|
3805
4185
|
gate: gate.id,
|
|
@@ -3829,14 +4209,14 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3829
4209
|
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
3830
4210
|
const cappedResult = applyDailyBlockCap(denyResult);
|
|
3831
4211
|
if (cappedResult) {
|
|
3832
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
3833
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
3834
|
-
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);
|
|
3835
4215
|
return cappedResult;
|
|
3836
4216
|
}
|
|
3837
|
-
recordStat(gate.id, 'block', gate, { toolName, toolInput });
|
|
3838
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
3839
|
-
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);
|
|
3840
4220
|
return denyResult;
|
|
3841
4221
|
}
|
|
3842
4222
|
|
|
@@ -3847,52 +4227,53 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3847
4227
|
// Autonomous run: no human to approve. Fail CLOSED so the actions that
|
|
3848
4228
|
// most need sign-off cannot slip through unattended.
|
|
3849
4229
|
const failClosedMessage = `[autonomous run — no approver present, failing closed] ${message}`;
|
|
3850
|
-
recordStat(gate.id, 'block', gate, { toolName, toolInput });
|
|
3851
|
-
const failClosedAudit = recordAuditEvent({ toolName, toolInput, decision: 'deny', gateId: gate.id, message: failClosedMessage, severity: gate.severity, source: 'gates-engine', autonomousFailClosed: true });
|
|
3852
|
-
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);
|
|
3853
4233
|
return { decision: 'deny', gate: gate.id, message: failClosedMessage, severity: gate.severity, reasoning, requiresApproval: true, failedClosed: true };
|
|
3854
4234
|
}
|
|
3855
|
-
recordStat(gate.id, 'approve', gate, { toolName, toolInput });
|
|
4235
|
+
recordStat(gate.id, 'approve', gate, { ...execution, toolName, toolInput });
|
|
3856
4236
|
const result = { decision: 'approve', gate: gate.id, message, severity: gate.severity, reasoning, requiresApproval: true };
|
|
3857
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'approve', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3858
|
-
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);
|
|
3859
4239
|
return result;
|
|
3860
4240
|
}
|
|
3861
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
4241
|
+
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3862
4242
|
const result = { decision: 'warn', gate: gate.id, message: `[approval gate disabled] ${message}`, severity: gate.severity, reasoning };
|
|
3863
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3864
|
-
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);
|
|
3865
4245
|
return result;
|
|
3866
4246
|
}
|
|
3867
4247
|
|
|
3868
4248
|
if (gate.action === 'log') {
|
|
3869
|
-
recordStat(gate.id, 'log', gate, { toolName, toolInput });
|
|
3870
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'log', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3871
|
-
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);
|
|
3872
4252
|
// 'log' action allows the tool call to proceed — continue to next gate
|
|
3873
4253
|
continue;
|
|
3874
4254
|
}
|
|
3875
4255
|
|
|
3876
4256
|
if (gate.action === 'warn') {
|
|
3877
|
-
recordStat(gate.id, 'warn', gate, { toolName, toolInput });
|
|
4257
|
+
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3878
4258
|
const result = { decision: 'warn', gate: gate.id, message, severity: gate.severity, reasoning };
|
|
3879
|
-
const auditRecord = recordAuditEvent({ toolName, toolInput, decision: 'warn', gateId: gate.id, message, severity: gate.severity, source: 'gates-engine' });
|
|
3880
|
-
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);
|
|
3881
4261
|
return result;
|
|
3882
4262
|
}
|
|
3883
4263
|
}
|
|
4264
|
+
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
|
|
3884
4265
|
|
|
3885
4266
|
const skipAdvisoryGuards = isSafeSecretStorageWrite(toolName, toolInput, process.cwd());
|
|
3886
4267
|
const sentinelReport = skipAdvisoryGuards ? null : evaluateWorkflowSentinel(toolName, toolInput, {
|
|
3887
4268
|
governanceState,
|
|
3888
4269
|
});
|
|
3889
|
-
const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput);
|
|
3890
|
-
const memoryGuard = evaluateMemoryGuard(toolName, toolInput);
|
|
4270
|
+
const sentinelDecision = recordSentinelDecision(sentinelReport, toolName, toolInput, execution);
|
|
4271
|
+
const memoryGuard = evaluateMemoryGuard(toolName, toolInput, execution);
|
|
3891
4272
|
if (memoryGuard) {
|
|
3892
4273
|
const enrichedMemoryGuard = enrichResultWithSentinel(memoryGuard, sentinelReport);
|
|
3893
|
-
recordStat(enrichedMemoryGuard.gate, 'block', null, { toolName, toolInput });
|
|
3894
|
-
recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard);
|
|
3895
|
-
const auditRecord = recordAuditEvent({
|
|
4274
|
+
recordStat(enrichedMemoryGuard.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
4275
|
+
recordMemoryGuardDecision(sentinelDecision, enrichedMemoryGuard, execution);
|
|
4276
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3896
4277
|
toolName,
|
|
3897
4278
|
toolInput,
|
|
3898
4279
|
decision: 'deny',
|
|
@@ -3901,15 +4282,15 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3901
4282
|
severity: enrichedMemoryGuard.severity,
|
|
3902
4283
|
source: 'gates-engine',
|
|
3903
4284
|
});
|
|
3904
|
-
auditToFeedback(auditRecord);
|
|
4285
|
+
auditToFeedback(auditRecord, execution);
|
|
3905
4286
|
return enrichedMemoryGuard;
|
|
3906
4287
|
}
|
|
3907
4288
|
|
|
3908
4289
|
if (sentinelReport && sentinelReport.decision !== 'allow') {
|
|
3909
4290
|
const sentinelResult = buildSentinelGateResult(sentinelReport);
|
|
3910
|
-
recordStat(sentinelResult.gate, sentinelResult.decision === 'deny' ? 'block' : 'warn', null, { toolName, toolInput });
|
|
3911
|
-
recordSentinelBlockDecision(sentinelDecision, sentinelResult);
|
|
3912
|
-
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,
|
|
3913
4294
|
toolName,
|
|
3914
4295
|
toolInput,
|
|
3915
4296
|
decision: sentinelResult.decision,
|
|
@@ -3918,7 +4299,7 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3918
4299
|
severity: sentinelResult.severity,
|
|
3919
4300
|
source: 'workflow-sentinel',
|
|
3920
4301
|
});
|
|
3921
|
-
auditToFeedback(auditRecord);
|
|
4302
|
+
auditToFeedback(auditRecord, execution);
|
|
3922
4303
|
return sentinelResult;
|
|
3923
4304
|
}
|
|
3924
4305
|
|
|
@@ -3926,8 +4307,8 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3926
4307
|
// for high-risk provider side effects (THUMBGATE_BROKER_RECEIPT_MODE=enforce).
|
|
3927
4308
|
const brokerReceiptResult = evaluateBrokerReceiptGate(toolName, toolInput);
|
|
3928
4309
|
if (brokerReceiptResult && brokerReceiptResult.decision === 'deny') {
|
|
3929
|
-
recordStat(brokerReceiptResult.gate, 'block', null, { toolName, toolInput });
|
|
3930
|
-
const auditRecord = recordAuditEvent({
|
|
4310
|
+
recordStat(brokerReceiptResult.gate, 'block', null, { ...execution, toolName, toolInput });
|
|
4311
|
+
const auditRecord = recordAuditEvent({ ...execution,
|
|
3931
4312
|
toolName,
|
|
3932
4313
|
toolInput,
|
|
3933
4314
|
decision: 'deny',
|
|
@@ -3936,12 +4317,12 @@ function evaluateGatesInner(toolName, toolInput, configPath) {
|
|
|
3936
4317
|
severity: brokerReceiptResult.severity,
|
|
3937
4318
|
source: 'broker-execution-receipts',
|
|
3938
4319
|
});
|
|
3939
|
-
auditToFeedback(auditRecord);
|
|
4320
|
+
auditToFeedback(auditRecord, execution);
|
|
3940
4321
|
return brokerReceiptResult;
|
|
3941
4322
|
}
|
|
3942
4323
|
|
|
3943
4324
|
// Audit trail: record allow
|
|
3944
|
-
recordAuditEvent({ toolName, toolInput, decision: 'allow', source: 'gates-engine' });
|
|
4325
|
+
recordAuditEvent({ ...execution, toolName, toolInput, decision: 'allow', source: 'gates-engine' });
|
|
3945
4326
|
return null;
|
|
3946
4327
|
}
|
|
3947
4328
|
|
|
@@ -4083,7 +4464,554 @@ function evaluateSecretGuard(input = {}) {
|
|
|
4083
4464
|
return result;
|
|
4084
4465
|
}
|
|
4085
4466
|
|
|
4086
|
-
|
|
4467
|
+
const SWARM_CLAIM_LOST_ACTION = 'swarm_claim_lost_exit_3';
|
|
4468
|
+
const SWARM_CLAIM_SCRIPT_PATTERN = /\bswarm-claim\.py\b/i;
|
|
4469
|
+
const SWARM_LOSS_GATE = 'swarm-claim-exit-3-write-after-loss';
|
|
4470
|
+
const TEAMS_REPLY_GATE = 'teams-single-reply-per-message';
|
|
4471
|
+
const AZ_PUBLISH_GATE = 'az-repos-pr-publish-requires-cross-review';
|
|
4472
|
+
const SWARM_LOSS_EDIT_TOOLS = new Set([
|
|
4473
|
+
'edit',
|
|
4474
|
+
'write',
|
|
4475
|
+
'multiedit',
|
|
4476
|
+
'notebookedit',
|
|
4477
|
+
'strreplace',
|
|
4478
|
+
'search_replace',
|
|
4479
|
+
'applypatch',
|
|
4480
|
+
'apply_patch',
|
|
4481
|
+
]);
|
|
4482
|
+
const SWARM_LOSS_SHELL_PATTERN = /\b(?:git(?:\s+-C\s+\S+)?\s+(?:commit|push)|but\s+(?:commit|push))\b/i;
|
|
4483
|
+
const AZ_PR_UPDATE_PATTERN = /\baz\s+repos\s+pr\s+update\b/i;
|
|
4484
|
+
const AZ_DRAFT_FLAG_PATTERN = /(?:^|\s)(--is-draft|--draft)(?:=|\s+)(\S+)/i;
|
|
4485
|
+
const AZ_PUBLISH_VALUES = new Set(['false', '0', 'no']);
|
|
4486
|
+
const TEAMS_POINT_STOPWORDS = new Set([
|
|
4487
|
+
'this', 'that', 'with', 'from', 'your', 'have', 'will', 'just', 'about',
|
|
4488
|
+
'they', 'them', 'were', 'been', 'into', 'over', 'same', 'send',
|
|
4489
|
+
]);
|
|
4490
|
+
const EXPLICIT_EXIT_KEYS = ['exitCode', 'exit_code', 'swarmClaimExitCode'];
|
|
4491
|
+
const SESSION_SCOPE_KEYS = ['session_id', 'sessionId', 'conversation_id', 'conversationId'];
|
|
4492
|
+
const AGENT_SCOPE_KEYS = ['agent_id', 'agentId'];
|
|
4493
|
+
|
|
4494
|
+
function commandText(toolInput) {
|
|
4495
|
+
if (!toolInput || typeof toolInput !== 'object') return '';
|
|
4496
|
+
if (typeof toolInput.command === 'string') return toolInput.command;
|
|
4497
|
+
if (typeof toolInput.cmd === 'string') return toolInput.cmd;
|
|
4498
|
+
return '';
|
|
4499
|
+
}
|
|
4500
|
+
|
|
4501
|
+
function firstScopeValue(source, keys) {
|
|
4502
|
+
if (!source || typeof source !== 'object') return '';
|
|
4503
|
+
for (const key of keys) {
|
|
4504
|
+
const value = source[key];
|
|
4505
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
4506
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
4507
|
+
}
|
|
4508
|
+
return '';
|
|
4509
|
+
}
|
|
4510
|
+
|
|
4511
|
+
function swarmLossScopeToken(source) {
|
|
4512
|
+
if (!source || typeof source !== 'object') return '';
|
|
4513
|
+
const session = firstScopeValue(source, SESSION_SCOPE_KEYS)
|
|
4514
|
+
|| firstScopeValue(source.tool_input, SESSION_SCOPE_KEYS)
|
|
4515
|
+
|| firstScopeValue(source.toolInput, SESSION_SCOPE_KEYS);
|
|
4516
|
+
if (session) return `session:${session}`;
|
|
4517
|
+
const agent = firstScopeValue(source, AGENT_SCOPE_KEYS);
|
|
4518
|
+
return agent ? `agent:${agent}` : '';
|
|
4519
|
+
}
|
|
4520
|
+
|
|
4521
|
+
function swarmLossActionId(scopeToken) {
|
|
4522
|
+
const token = String(scopeToken || '').trim();
|
|
4523
|
+
if (!token) return '';
|
|
4524
|
+
const hash = crypto.createHash('sha256').update(token).digest('hex').slice(0, 16);
|
|
4525
|
+
const prefix = token.replace(/[^A-Za-z0-9._:-]/g, '_').slice(0, 64);
|
|
4526
|
+
return `${SWARM_CLAIM_LOST_ACTION}:${prefix}:${hash}`;
|
|
4527
|
+
}
|
|
4528
|
+
|
|
4529
|
+
function repeatedMistakeView(input = {}) {
|
|
4530
|
+
const lossScopeToken = swarmLossScopeToken(input);
|
|
4531
|
+
const named = input.tool_name || input.toolName;
|
|
4532
|
+
if (named) {
|
|
4533
|
+
const toolInput = (input.tool_input && typeof input.tool_input === 'object' && input.tool_input)
|
|
4534
|
+
|| (input.toolInput && typeof input.toolInput === 'object' && input.toolInput)
|
|
4535
|
+
|| {};
|
|
4536
|
+
return {
|
|
4537
|
+
toolName: String(named),
|
|
4538
|
+
toolInput,
|
|
4539
|
+
command: commandText(toolInput),
|
|
4540
|
+
lossScopeToken,
|
|
4541
|
+
};
|
|
4542
|
+
}
|
|
4543
|
+
if (typeof input.command === 'string') {
|
|
4544
|
+
return {
|
|
4545
|
+
toolName: 'Bash',
|
|
4546
|
+
toolInput: { command: input.command },
|
|
4547
|
+
command: input.command,
|
|
4548
|
+
lossScopeToken,
|
|
4549
|
+
};
|
|
4550
|
+
}
|
|
4551
|
+
return { toolName: '', toolInput: {}, command: '', lossScopeToken };
|
|
4552
|
+
}
|
|
4553
|
+
|
|
4554
|
+
function isSwarmClaimCommand(command) {
|
|
4555
|
+
return SWARM_CLAIM_SCRIPT_PATTERN.test(String(command || ''));
|
|
4556
|
+
}
|
|
4557
|
+
|
|
4558
|
+
function swarmLossMessage(blocked) {
|
|
4559
|
+
return `Denied ${blocked}: swarm-claim.py exited 3. Stop editing, committing, and pushing.`;
|
|
4560
|
+
}
|
|
4561
|
+
|
|
4562
|
+
function denyRepeatedMistake(view, result) {
|
|
4563
|
+
try {
|
|
4564
|
+
return recordStructuralGateBlock(view.toolName, view.toolInput, result);
|
|
4565
|
+
} catch (_) {
|
|
4566
|
+
return result;
|
|
4567
|
+
}
|
|
4568
|
+
}
|
|
4569
|
+
|
|
4570
|
+
function isSwarmLossWrite(view) {
|
|
4571
|
+
const tool = String(view.toolName || '').toLowerCase();
|
|
4572
|
+
if (SWARM_LOSS_EDIT_TOOLS.has(tool)) return true;
|
|
4573
|
+
if (!view.command) return false;
|
|
4574
|
+
return SWARM_LOSS_SHELL_PATTERN.test(view.command);
|
|
4575
|
+
}
|
|
4576
|
+
|
|
4577
|
+
function blockedCommandLabel(view) {
|
|
4578
|
+
const match = String(view.command || '').match(SWARM_LOSS_SHELL_PATTERN);
|
|
4579
|
+
if (match) return match[0];
|
|
4580
|
+
return view.toolName || 'edit';
|
|
4581
|
+
}
|
|
4582
|
+
|
|
4583
|
+
function evaluateSwarmClaimLostWriteGate(view) {
|
|
4584
|
+
const actionId = swarmLossActionId(view.lossScopeToken);
|
|
4585
|
+
if (!actionId || !hasAction(actionId)) return null;
|
|
4586
|
+
if (isSwarmClaimCommand(view.command) && !SWARM_LOSS_SHELL_PATTERN.test(view.command)) return null;
|
|
4587
|
+
if (!isSwarmLossWrite(view)) return null;
|
|
4588
|
+
return denyRepeatedMistake(view, {
|
|
4589
|
+
decision: 'deny',
|
|
4590
|
+
gate: SWARM_LOSS_GATE,
|
|
4591
|
+
endTurn: true,
|
|
4592
|
+
severity: 'critical',
|
|
4593
|
+
message: swarmLossMessage(blockedCommandLabel(view)),
|
|
4594
|
+
});
|
|
4595
|
+
}
|
|
4596
|
+
|
|
4597
|
+
function numericExit(value) {
|
|
4598
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
4599
|
+
if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) return Number(value.trim());
|
|
4600
|
+
return undefined;
|
|
4601
|
+
}
|
|
4602
|
+
|
|
4603
|
+
function explicitExitPresent(source) {
|
|
4604
|
+
if (!source || typeof source !== 'object') return false;
|
|
4605
|
+
return EXPLICIT_EXIT_KEYS.some((key) => Object.prototype.hasOwnProperty.call(source, key));
|
|
4606
|
+
}
|
|
4607
|
+
|
|
4608
|
+
function readExplicitExit(source) {
|
|
4609
|
+
for (const key of EXPLICIT_EXIT_KEYS) {
|
|
4610
|
+
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
|
|
4611
|
+
return numericExit(source[key]);
|
|
4612
|
+
}
|
|
4613
|
+
return undefined;
|
|
4614
|
+
}
|
|
4615
|
+
|
|
4616
|
+
function firstExplicitExit(event) {
|
|
4617
|
+
const sources = [event];
|
|
4618
|
+
if (event && typeof event === 'object') {
|
|
4619
|
+
sources.push(event.tool_response, event.tool_output, event.toolOutput);
|
|
4620
|
+
}
|
|
4621
|
+
for (const source of sources) {
|
|
4622
|
+
if (!explicitExitPresent(source)) continue;
|
|
4623
|
+
return { present: true, code: readExplicitExit(source) };
|
|
4624
|
+
}
|
|
4625
|
+
return { present: false, code: undefined };
|
|
4626
|
+
}
|
|
4627
|
+
|
|
4628
|
+
function stdoutText(event) {
|
|
4629
|
+
if (!event || typeof event !== 'object') return '';
|
|
4630
|
+
const chunks = [];
|
|
4631
|
+
const push = (value) => {
|
|
4632
|
+
if (typeof value === 'string' && value) chunks.push(value);
|
|
4633
|
+
};
|
|
4634
|
+
push(event.output);
|
|
4635
|
+
push(event.stdout);
|
|
4636
|
+
push(event.tool_response);
|
|
4637
|
+
push(event.tool_output);
|
|
4638
|
+
const objects = [event.tool_response, event.tool_output, event.toolOutput];
|
|
4639
|
+
for (const obj of objects) {
|
|
4640
|
+
if (!obj || typeof obj !== 'object') continue;
|
|
4641
|
+
push(obj.stdout);
|
|
4642
|
+
push(obj.output);
|
|
4643
|
+
}
|
|
4644
|
+
return chunks.join('\n');
|
|
4645
|
+
}
|
|
4646
|
+
|
|
4647
|
+
function lastJsonObject(text) {
|
|
4648
|
+
if (typeof text !== 'string') return null;
|
|
4649
|
+
const slice = text.slice(-8000);
|
|
4650
|
+
const close = slice.lastIndexOf('}');
|
|
4651
|
+
if (close === -1) return null;
|
|
4652
|
+
for (let open = 0; open <= close; open += 1) {
|
|
4653
|
+
if (slice[open] !== '{') continue;
|
|
4654
|
+
try {
|
|
4655
|
+
const parsed = JSON.parse(slice.slice(open, close + 1));
|
|
4656
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
|
|
4657
|
+
} catch (_) {
|
|
4658
|
+
// Keep walking until the object that ends at the last close parses.
|
|
4659
|
+
}
|
|
4660
|
+
}
|
|
4661
|
+
return null;
|
|
4662
|
+
}
|
|
4663
|
+
|
|
4664
|
+
function eventCommand(event) {
|
|
4665
|
+
if (!event || typeof event !== 'object') return '';
|
|
4666
|
+
if (typeof event.command === 'string' && event.command.trim()) return event.command;
|
|
4667
|
+
return commandText(event.tool_input || event.toolInput);
|
|
4668
|
+
}
|
|
4669
|
+
|
|
4670
|
+
function failureReportedExit(event) {
|
|
4671
|
+
if (!event || typeof event !== 'object') return { present: false, code: undefined };
|
|
4672
|
+
if (event.is_interrupt === true) return { present: true, code: undefined };
|
|
4673
|
+
const error = typeof event.error === 'string' ? event.error : '';
|
|
4674
|
+
const match = error.match(/^\s*Exit code (-?\d+)\b/);
|
|
4675
|
+
if (!match) return { present: false, code: undefined };
|
|
4676
|
+
return { present: true, code: Number(match[1]) };
|
|
4677
|
+
}
|
|
4678
|
+
|
|
4679
|
+
function claimAgentName(event) {
|
|
4680
|
+
const errorText = event && typeof event.error === 'string' ? event.error : '';
|
|
4681
|
+
const parsed = lastJsonObject(`${stdoutText(event)}\n${errorText}`);
|
|
4682
|
+
if (parsed && typeof parsed.agent === 'string' && parsed.agent.trim()) return parsed.agent.trim();
|
|
4683
|
+
const flagged = String(eventCommand(event)).match(/--agent(?:=|\s+)(['"]?)([^'"\s]+)\1/);
|
|
4684
|
+
return flagged ? flagged[2] : '';
|
|
4685
|
+
}
|
|
4686
|
+
|
|
4687
|
+
function observeHookEventName(event) {
|
|
4688
|
+
const name = String((event && (event.hook_event_name || event.hookEventName)) || '');
|
|
4689
|
+
return name === 'PostToolUseFailure' ? 'PostToolUseFailure' : 'PostToolUse';
|
|
4690
|
+
}
|
|
4691
|
+
|
|
4692
|
+
function resolveObservedExit(event) {
|
|
4693
|
+
const explicit = firstExplicitExit(event);
|
|
4694
|
+
if (explicit.present) return explicit.code;
|
|
4695
|
+
const failed = failureReportedExit(event);
|
|
4696
|
+
if (failed.present) return failed.code;
|
|
4697
|
+
const response = event && (event.tool_response || event.tool_output || event.toolOutput);
|
|
4698
|
+
if (response && typeof response === 'object' && !Array.isArray(response)) {
|
|
4699
|
+
const direct = numericExit(response.exit);
|
|
4700
|
+
if (typeof direct === 'number') return direct;
|
|
4701
|
+
}
|
|
4702
|
+
const parsed = lastJsonObject(stdoutText(event));
|
|
4703
|
+
if (!parsed || !Object.prototype.hasOwnProperty.call(parsed, 'exit')) return undefined;
|
|
4704
|
+
return numericExit(parsed.exit);
|
|
4705
|
+
}
|
|
4706
|
+
|
|
4707
|
+
function observeSwarmClaimResult(event = {}) {
|
|
4708
|
+
const command = eventCommand(event);
|
|
4709
|
+
if (!isSwarmClaimCommand(command)) return null;
|
|
4710
|
+
if (resolveObservedExit(event) !== 3) return null;
|
|
4711
|
+
const actionId = swarmLossActionId(swarmLossScopeToken(event));
|
|
4712
|
+
if (actionId) {
|
|
4713
|
+
try {
|
|
4714
|
+
trackAction(actionId, {
|
|
4715
|
+
command: command.slice(0, 240),
|
|
4716
|
+
exitCode: 3,
|
|
4717
|
+
agent: claimAgentName(event),
|
|
4718
|
+
});
|
|
4719
|
+
} catch (_) {
|
|
4720
|
+
// The turn still ends. A failed write leaves the next edit unarmed.
|
|
4721
|
+
}
|
|
4722
|
+
}
|
|
4723
|
+
return {
|
|
4724
|
+
decision: 'deny',
|
|
4725
|
+
gate: SWARM_LOSS_GATE,
|
|
4726
|
+
endTurn: true,
|
|
4727
|
+
severity: 'critical',
|
|
4728
|
+
hookEventName: observeHookEventName(event),
|
|
4729
|
+
message: swarmLossMessage('swarm-claim.py'),
|
|
4730
|
+
};
|
|
4731
|
+
}
|
|
4732
|
+
|
|
4733
|
+
function formatObserveStop(result) {
|
|
4734
|
+
const reason = `[GATE:${result.gate}] ${result.message}`;
|
|
4735
|
+
return JSON.stringify({
|
|
4736
|
+
continue: false,
|
|
4737
|
+
stopReason: reason,
|
|
4738
|
+
hookSpecificOutput: {
|
|
4739
|
+
hookEventName: result.hookEventName || 'PostToolUse',
|
|
4740
|
+
permissionDecision: 'deny',
|
|
4741
|
+
permissionDecisionReason: reason,
|
|
4742
|
+
continue: false,
|
|
4743
|
+
},
|
|
4744
|
+
});
|
|
4745
|
+
}
|
|
4746
|
+
|
|
4747
|
+
function isTeamsSendTool(toolName) {
|
|
4748
|
+
const name = String(toolName || '').toLowerCase();
|
|
4749
|
+
if (!name.includes('teams')) return false;
|
|
4750
|
+
if (name.includes('gmail')) return false;
|
|
4751
|
+
return /send|reply|post_message/.test(name);
|
|
4752
|
+
}
|
|
4753
|
+
|
|
4754
|
+
function firstStringField(toolInput, keys) {
|
|
4755
|
+
for (const key of keys) {
|
|
4756
|
+
const value = toolInput[key];
|
|
4757
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
4758
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
4759
|
+
}
|
|
4760
|
+
return '';
|
|
4761
|
+
}
|
|
4762
|
+
|
|
4763
|
+
function teamsTarget(toolInput) {
|
|
4764
|
+
return firstStringField(toolInput, [
|
|
4765
|
+
'recipient', 'to', 'user', 'person', 'chat', 'channel', 'chat_id', 'chatId',
|
|
4766
|
+
]);
|
|
4767
|
+
}
|
|
4768
|
+
|
|
4769
|
+
function teamsMessageId(toolInput) {
|
|
4770
|
+
return firstStringField(toolInput, [
|
|
4771
|
+
'messageId', 'message_id', 'replyToId', 'reply_to_id', 'threadId',
|
|
4772
|
+
]);
|
|
4773
|
+
}
|
|
4774
|
+
|
|
4775
|
+
function teamsText(toolInput) {
|
|
4776
|
+
return firstStringField(toolInput, ['text', 'message', 'content', 'body']);
|
|
4777
|
+
}
|
|
4778
|
+
|
|
4779
|
+
function teamsPointKey(text) {
|
|
4780
|
+
const normalized = String(text || '')
|
|
4781
|
+
.toLowerCase()
|
|
4782
|
+
.replace(/https?:\/\/\S+/g, ' ')
|
|
4783
|
+
.replace(/\s+/g, ' ')
|
|
4784
|
+
.trim();
|
|
4785
|
+
const tokens = normalized
|
|
4786
|
+
.split(' ')
|
|
4787
|
+
.filter((token) => token.length >= 4 && !TEAMS_POINT_STOPWORDS.has(token));
|
|
4788
|
+
if (tokens.length > 0) return tokens.join(' ');
|
|
4789
|
+
if (normalized.length >= 12) return normalized;
|
|
4790
|
+
return '';
|
|
4791
|
+
}
|
|
4792
|
+
|
|
4793
|
+
function teamsReplyKeys(view) {
|
|
4794
|
+
const input = view.toolInput || {};
|
|
4795
|
+
const target = teamsTarget(input);
|
|
4796
|
+
const messageId = teamsMessageId(input);
|
|
4797
|
+
const point = teamsPointKey(teamsText(input));
|
|
4798
|
+
return {
|
|
4799
|
+
target,
|
|
4800
|
+
messageId,
|
|
4801
|
+
messageKey: messageId ? `teams_reply_msg:${messageId}` : '',
|
|
4802
|
+
pointKey: target && point ? `teams_reply_point:${target.toLowerCase()}:${point}` : '',
|
|
4803
|
+
};
|
|
4804
|
+
}
|
|
4805
|
+
|
|
4806
|
+
function teamsDeliveryFailed(event) {
|
|
4807
|
+
if (!event || typeof event !== 'object') return false;
|
|
4808
|
+
const name = String(event.hook_event_name || event.hookEventName || '');
|
|
4809
|
+
if (name === 'PostToolUseFailure') return true;
|
|
4810
|
+
if (event.is_interrupt === true) return true;
|
|
4811
|
+
if (typeof event.error === 'string' && event.error.trim()) return true;
|
|
4812
|
+
const explicit = firstExplicitExit(event);
|
|
4813
|
+
return explicit.present && explicit.code !== 0;
|
|
4814
|
+
}
|
|
4815
|
+
|
|
4816
|
+
function evaluateTeamsSingleReplyGate(view) {
|
|
4817
|
+
if (!isTeamsSendTool(view.toolName)) return null;
|
|
4818
|
+
const keys = teamsReplyKeys(view);
|
|
4819
|
+
if ((keys.messageKey && hasAction(keys.messageKey)) || (keys.pointKey && hasAction(keys.pointKey))) {
|
|
4820
|
+
return denyRepeatedMistake(view, {
|
|
4821
|
+
decision: 'deny',
|
|
4822
|
+
gate: TEAMS_REPLY_GATE,
|
|
4823
|
+
severity: 'critical',
|
|
4824
|
+
message: `Denied second Teams send (${view.toolName}) to ${keys.target || keys.messageId} on the same point.`,
|
|
4825
|
+
});
|
|
4826
|
+
}
|
|
4827
|
+
return null;
|
|
4828
|
+
}
|
|
4829
|
+
|
|
4830
|
+
function observeTeamsSendResult(event = {}) {
|
|
4831
|
+
const view = repeatedMistakeView(event);
|
|
4832
|
+
if (!isTeamsSendTool(view.toolName)) return null;
|
|
4833
|
+
if (teamsDeliveryFailed(event)) return null;
|
|
4834
|
+
const keys = teamsReplyKeys(view);
|
|
4835
|
+
if (!keys.messageKey && !keys.pointKey) return null;
|
|
4836
|
+
try {
|
|
4837
|
+
if (keys.messageKey) trackAction(keys.messageKey, { target: keys.target, confirmed: true });
|
|
4838
|
+
if (keys.pointKey) trackAction(keys.pointKey, { target: keys.target, confirmed: true });
|
|
4839
|
+
} catch (_) {
|
|
4840
|
+
// A missed receipt can be sent again. A false receipt cannot.
|
|
4841
|
+
}
|
|
4842
|
+
return null;
|
|
4843
|
+
}
|
|
4844
|
+
|
|
4845
|
+
function azDraftPublish(command) {
|
|
4846
|
+
if (!AZ_PR_UPDATE_PATTERN.test(String(command || ''))) return null;
|
|
4847
|
+
const match = String(command || '').match(AZ_DRAFT_FLAG_PATTERN);
|
|
4848
|
+
if (!match) return null;
|
|
4849
|
+
const value = match[2].replace(/^['"]|['"]$/g, '').toLowerCase();
|
|
4850
|
+
if (!AZ_PUBLISH_VALUES.has(value)) return null;
|
|
4851
|
+
return { flag: match[1], value };
|
|
4852
|
+
}
|
|
4853
|
+
|
|
4854
|
+
function azPrId(command) {
|
|
4855
|
+
const flagged = String(command || '').match(/(?:^|\s)--id(?:=|\s+)(\d+)/i);
|
|
4856
|
+
if (flagged) return flagged[1];
|
|
4857
|
+
const positional = String(command || '').match(/\baz\s+repos\s+pr\s+update\s+(\d+)\b/i);
|
|
4858
|
+
return positional ? positional[1] : '';
|
|
4859
|
+
}
|
|
4860
|
+
|
|
4861
|
+
function queryAz(args) {
|
|
4862
|
+
const result = spawnSync('az', args, {
|
|
4863
|
+
encoding: 'utf8',
|
|
4864
|
+
timeout: 8000,
|
|
4865
|
+
windowsHide: true,
|
|
4866
|
+
});
|
|
4867
|
+
if (!result || result.error || result.status !== 0 || !result.stdout) return null;
|
|
4868
|
+
try {
|
|
4869
|
+
return JSON.parse(result.stdout);
|
|
4870
|
+
} catch (_) {
|
|
4871
|
+
return null;
|
|
4872
|
+
}
|
|
4873
|
+
}
|
|
4874
|
+
|
|
4875
|
+
function organizationFromPr(pr) {
|
|
4876
|
+
const url = String((pr && (pr.url || pr.remoteUrl)) || '');
|
|
4877
|
+
const match = url.match(/https:\/\/dev\.azure\.com\/([A-Za-z0-9-]+)\//);
|
|
4878
|
+
return match ? match[1] : '';
|
|
4879
|
+
}
|
|
4880
|
+
|
|
4881
|
+
function personName(person) {
|
|
4882
|
+
if (!person || typeof person !== 'object') return '';
|
|
4883
|
+
return String(person.uniqueName || person.displayName || '').trim();
|
|
4884
|
+
}
|
|
4885
|
+
|
|
4886
|
+
function isSystemCommentType(commentType) {
|
|
4887
|
+
if (commentType === 2 || commentType === 3) return true;
|
|
4888
|
+
const text = String(commentType == null ? '' : commentType).trim().toLowerCase();
|
|
4889
|
+
return text === 'system' || text === '2' || text === '3';
|
|
4890
|
+
}
|
|
4891
|
+
|
|
4892
|
+
function isOtherPersonReviewComment(comment, creator) {
|
|
4893
|
+
if (!comment || typeof comment !== 'object') return false;
|
|
4894
|
+
if (isSystemCommentType(comment.commentType)) return false;
|
|
4895
|
+
if (!String(comment.content || '').trim()) return false;
|
|
4896
|
+
const author = personName(comment.author);
|
|
4897
|
+
if (!author) return false;
|
|
4898
|
+
if (creator && author.toLowerCase() === creator.toLowerCase()) return false;
|
|
4899
|
+
return true;
|
|
4900
|
+
}
|
|
4901
|
+
|
|
4902
|
+
function threadComments(threadsPayload) {
|
|
4903
|
+
if (!threadsPayload) return [];
|
|
4904
|
+
const threads = Array.isArray(threadsPayload)
|
|
4905
|
+
? threadsPayload
|
|
4906
|
+
: (Array.isArray(threadsPayload.value) ? threadsPayload.value : []);
|
|
4907
|
+
const comments = [];
|
|
4908
|
+
for (const thread of threads) {
|
|
4909
|
+
if (thread && Array.isArray(thread.comments)) comments.push(...thread.comments);
|
|
4910
|
+
}
|
|
4911
|
+
return comments;
|
|
4912
|
+
}
|
|
4913
|
+
|
|
4914
|
+
function hasOtherPersonReviewComment(pr, threadsPayload) {
|
|
4915
|
+
const creator = personName(pr && pr.createdBy);
|
|
4916
|
+
return threadComments(threadsPayload).some((comment) => isOtherPersonReviewComment(comment, creator));
|
|
4917
|
+
}
|
|
4918
|
+
|
|
4919
|
+
function queryAzCrossReview(prId) {
|
|
4920
|
+
const pr = queryAz(['repos', 'pr', 'show', '--id', String(prId), '--output', 'json']);
|
|
4921
|
+
if (!pr || typeof pr !== 'object') return false;
|
|
4922
|
+
const repository = pr.repository && typeof pr.repository === 'object' ? pr.repository : null;
|
|
4923
|
+
const project = repository && repository.project && repository.project.name;
|
|
4924
|
+
const repositoryId = repository && repository.id;
|
|
4925
|
+
if (!project || !repositoryId) return false;
|
|
4926
|
+
const args = [
|
|
4927
|
+
'devops', 'invoke',
|
|
4928
|
+
'--area', 'git',
|
|
4929
|
+
'--resource', 'pullRequestThreads',
|
|
4930
|
+
'--api-version', '7.1',
|
|
4931
|
+
'--http-method', 'GET',
|
|
4932
|
+
'--output', 'json',
|
|
4933
|
+
'--route-parameters',
|
|
4934
|
+
`project=${project}`,
|
|
4935
|
+
`repositoryId=${repositoryId}`,
|
|
4936
|
+
`pullRequestId=${prId}`,
|
|
4937
|
+
];
|
|
4938
|
+
const org = organizationFromPr(pr);
|
|
4939
|
+
if (org) args.push('--organization', `https://dev.azure.com/${org}`);
|
|
4940
|
+
const threads = queryAz(args);
|
|
4941
|
+
if (!threads) return false;
|
|
4942
|
+
return hasOtherPersonReviewComment(pr, threads);
|
|
4943
|
+
}
|
|
4944
|
+
|
|
4945
|
+
let crossReviewLookup = queryAzCrossReview;
|
|
4946
|
+
|
|
4947
|
+
function setCrossReviewLookup(fn) {
|
|
4948
|
+
crossReviewLookup = typeof fn === 'function' ? fn : queryAzCrossReview;
|
|
4949
|
+
}
|
|
4950
|
+
|
|
4951
|
+
function azDeny(view, message) {
|
|
4952
|
+
return denyRepeatedMistake(view, {
|
|
4953
|
+
decision: 'deny',
|
|
4954
|
+
gate: AZ_PUBLISH_GATE,
|
|
4955
|
+
severity: 'critical',
|
|
4956
|
+
message,
|
|
4957
|
+
});
|
|
4958
|
+
}
|
|
4959
|
+
|
|
4960
|
+
function evaluateAzReposPrPublishGate(view) {
|
|
4961
|
+
const publish = azDraftPublish(view.command);
|
|
4962
|
+
if (!publish) return null;
|
|
4963
|
+
const prId = azPrId(view.command);
|
|
4964
|
+
const shown = `${publish.flag} ${publish.value}`;
|
|
4965
|
+
if (!prId) {
|
|
4966
|
+
return azDeny(
|
|
4967
|
+
view,
|
|
4968
|
+
`Denied \`${String(view.command || '').trim()}\`: the pull request id could not be parsed, so a review comment from the other person is not proven.`
|
|
4969
|
+
);
|
|
4970
|
+
}
|
|
4971
|
+
let reviewed = false;
|
|
4972
|
+
try {
|
|
4973
|
+
reviewed = crossReviewLookup(prId, view.command) === true;
|
|
4974
|
+
} catch (_) {
|
|
4975
|
+
reviewed = false;
|
|
4976
|
+
}
|
|
4977
|
+
if (reviewed) return null;
|
|
4978
|
+
return azDeny(
|
|
4979
|
+
view,
|
|
4980
|
+
`Denied \`az repos pr update ${shown}\` on PR #${prId}: a review comment from the other person does not exist yet. psn-skills auto-merges a non-draft once checks pass.`
|
|
4981
|
+
);
|
|
4982
|
+
}
|
|
4983
|
+
|
|
4984
|
+
function evaluateMablFailureHonestyGate(view) {
|
|
4985
|
+
const { evaluateMablFailureHonesty } = require('./mabl-failure-honesty');
|
|
4986
|
+
const result = evaluateMablFailureHonesty(view);
|
|
4987
|
+
if (!result) return null;
|
|
4988
|
+
return denyRepeatedMistake(view, result);
|
|
4989
|
+
}
|
|
4990
|
+
|
|
4991
|
+
function evaluateRepeatedMistakeGates(input = {}) {
|
|
4992
|
+
const view = repeatedMistakeView(input);
|
|
4993
|
+
return evaluateSwarmClaimLostWriteGate(view)
|
|
4994
|
+
|| evaluateTeamsSingleReplyGate(view)
|
|
4995
|
+
|| evaluateAzReposPrPublishGate(view)
|
|
4996
|
+
|| evaluateMablFailureHonestyGate(view);
|
|
4997
|
+
}
|
|
4998
|
+
|
|
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);
|
|
4087
5015
|
const secretGuard = evaluateSecretGuard(input);
|
|
4088
5016
|
if (secretGuard) return { hardFloor: secretGuard, securityScan: null };
|
|
4089
5017
|
|
|
@@ -4095,8 +5023,21 @@ function evaluateUnconditionalHardFloor(input = {}, options = {}) {
|
|
|
4095
5023
|
const financialHardFloor = evaluateFinancialHardFloor(input, false, options);
|
|
4096
5024
|
if (financialHardFloor) return { hardFloor: financialHardFloor, securityScan };
|
|
4097
5025
|
|
|
5026
|
+
const selfProtect = evaluateSelfProtectHardFloor(input);
|
|
5027
|
+
if (selfProtect) return { hardFloor: selfProtect, securityScan };
|
|
5028
|
+
|
|
5029
|
+
const repeated = evaluateRepeatedMistakeGates(input);
|
|
5030
|
+
if (repeated) return { hardFloor: repeated, securityScan };
|
|
5031
|
+
|
|
5032
|
+
const view = repeatedMistakeView(input);
|
|
5033
|
+
const { evaluateTailscaleOctoberAccess } = require('./tailscale-october-access');
|
|
5034
|
+
const october = evaluateTailscaleOctoberAccess(view);
|
|
5035
|
+
if (october) return { hardFloor: denyRepeatedMistake(view, october), securityScan };
|
|
5036
|
+
|
|
5037
|
+
const { evaluateGitLabSdlcPrompts } = require('./gitlab-sdlc-prompts');
|
|
5038
|
+
const sdlc = evaluateGitLabSdlcPrompts(view);
|
|
4098
5039
|
return {
|
|
4099
|
-
hardFloor:
|
|
5040
|
+
hardFloor: sdlc ? denyRepeatedMistake(view, sdlc) : null,
|
|
4100
5041
|
securityScan,
|
|
4101
5042
|
};
|
|
4102
5043
|
}
|
|
@@ -4243,14 +5184,19 @@ function formatOutput(result, behavioralContext) {
|
|
|
4243
5184
|
const reminder = behavioralContext ? buildReminderOutput(behavioralContext) : {};
|
|
4244
5185
|
const reminderSuffix = behavioralContext ? `\n\nSystem reminder:\n${behavioralContext}` : '';
|
|
4245
5186
|
const proCta = result.gate === 'financial-control' ? '' : (buildBlockActionProCta() || '');
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
5187
|
+
const hookSpecificOutput = {
|
|
5188
|
+
hookEventName: 'PreToolUse',
|
|
5189
|
+
...reminder,
|
|
5190
|
+
permissionDecision: 'deny',
|
|
5191
|
+
permissionDecisionReason: `[GATE:${result.gate}] ${result.message}${reasoningSuffix}${reminderSuffix}${proCta}`,
|
|
5192
|
+
};
|
|
5193
|
+
const payload = { hookSpecificOutput };
|
|
5194
|
+
if (result.endTurn) {
|
|
5195
|
+
payload.continue = false;
|
|
5196
|
+
payload.stopReason = `[GATE:${result.gate}] ${result.message}`;
|
|
5197
|
+
hookSpecificOutput.continue = false;
|
|
5198
|
+
}
|
|
5199
|
+
return JSON.stringify(payload);
|
|
4254
5200
|
}
|
|
4255
5201
|
|
|
4256
5202
|
if (result.decision === 'approve') {
|
|
@@ -4392,7 +5338,7 @@ function buildRecentCorrectiveActionsContext(options = {}) {
|
|
|
4392
5338
|
* active governor. Without this, lessons stay in the DB and never get surfaced at
|
|
4393
5339
|
* decision time — so the agent repeats mistakes.
|
|
4394
5340
|
*/
|
|
4395
|
-
function buildRelevantLessonContext(toolName, toolInput) {
|
|
5341
|
+
function buildRelevantLessonContext(toolName, toolInput, options = {}) {
|
|
4396
5342
|
if (!toolName) return null;
|
|
4397
5343
|
|
|
4398
5344
|
const { retrieveRelevantLessons, calculateRetrievalEntropy } = loadOptionalModule("./lesson-retrieval", () => ({ retrieveRelevantLessons: () => [], calculateRetrievalEntropy: () => 0 }));
|
|
@@ -4402,7 +5348,11 @@ function buildRelevantLessonContext(toolName, toolInput) {
|
|
|
4402
5348
|
if (!actionContext) return null;
|
|
4403
5349
|
|
|
4404
5350
|
try {
|
|
4405
|
-
const lessons = retrieveRelevantLessons(toolName, actionContext, {
|
|
5351
|
+
const lessons = retrieveRelevantLessons(toolName, actionContext, {
|
|
5352
|
+
maxResults: 3,
|
|
5353
|
+
cwd: options.cwd || toolInput?.cwd,
|
|
5354
|
+
project: options.project,
|
|
5355
|
+
});
|
|
4406
5356
|
|
|
4407
5357
|
const entropy = calculateRetrievalEntropy(lessons);
|
|
4408
5358
|
if (entropy > KNOWLEDGE_ENTROPY_THRESHOLD) {
|
|
@@ -4420,7 +5370,7 @@ function buildRelevantLessonContext(toolName, toolInput) {
|
|
|
4420
5370
|
* even when they share no keywords with the current action. Wired into runAsync.
|
|
4421
5371
|
* Degrades to the lexical result automatically when no embedder is available.
|
|
4422
5372
|
*/
|
|
4423
|
-
async function buildRelevantLessonContextAsync(toolName, toolInput) {
|
|
5373
|
+
async function buildRelevantLessonContextAsync(toolName, toolInput, options = {}) {
|
|
4424
5374
|
if (!toolName) return null;
|
|
4425
5375
|
|
|
4426
5376
|
const { retrieveRelevantLessonsAsync, retrieveRelevantLessons, calculateRetrievalEntropy } = loadOptionalModule(
|
|
@@ -4432,9 +5382,14 @@ async function buildRelevantLessonContextAsync(toolName, toolInput) {
|
|
|
4432
5382
|
if (!actionContext) return null;
|
|
4433
5383
|
|
|
4434
5384
|
try {
|
|
5385
|
+
const retrievalOpts = {
|
|
5386
|
+
maxResults: 3,
|
|
5387
|
+
cwd: options.cwd || toolInput?.cwd,
|
|
5388
|
+
project: options.project,
|
|
5389
|
+
};
|
|
4435
5390
|
const lessons = retrieveRelevantLessonsAsync
|
|
4436
|
-
? await retrieveRelevantLessonsAsync(toolName, actionContext,
|
|
4437
|
-
: retrieveRelevantLessons(toolName, actionContext,
|
|
5391
|
+
? await retrieveRelevantLessonsAsync(toolName, actionContext, retrievalOpts)
|
|
5392
|
+
: retrieveRelevantLessons(toolName, actionContext, retrievalOpts);
|
|
4438
5393
|
|
|
4439
5394
|
// Knowledge Conflict Detection: if retrieved lessons have high sentiment entropy,
|
|
4440
5395
|
// it indicates conflicting past evidence. Warn by default; hard-block only in
|
|
@@ -4533,7 +5488,33 @@ function mergeContextStrings(...ctxs) {
|
|
|
4533
5488
|
return ctxs.filter((c) => typeof c === 'string' && c.length > 0).join('\n\n') || null;
|
|
4534
5489
|
}
|
|
4535
5490
|
|
|
4536
|
-
|
|
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);
|
|
4537
5518
|
const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
|
|
4538
5519
|
if (hardFloor) return formatOutput(hardFloor);
|
|
4539
5520
|
|
|
@@ -4575,12 +5556,14 @@ async function runAsync(input) {
|
|
|
4575
5556
|
if (financialAuthorization) return formatOutput(financialAuthorization);
|
|
4576
5557
|
|
|
4577
5558
|
const recentContext = buildRecentCorrectiveActionsContext();
|
|
4578
|
-
const
|
|
5559
|
+
const designContext = safeSecretStorageWrite ? null : buildDesignSelfCorrectionContext(toolName, toolInput);
|
|
5560
|
+
const combinedContext = combineWithSessionDedupe(input, lessonContext, recentContext, behavioralContext, designContext);
|
|
4579
5561
|
return formatOutput(posturedResult, combinedContext);
|
|
4580
5562
|
|
|
4581
5563
|
}
|
|
4582
5564
|
|
|
4583
|
-
function run(
|
|
5565
|
+
function run(rawInput) {
|
|
5566
|
+
const input = canonicalizeHookInput(rawInput);
|
|
4584
5567
|
const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
|
|
4585
5568
|
if (hardFloor) return formatOutput(hardFloor);
|
|
4586
5569
|
|
|
@@ -4622,11 +5605,34 @@ function run(input) {
|
|
|
4622
5605
|
if (financialAuthorization) return formatOutput(financialAuthorization);
|
|
4623
5606
|
|
|
4624
5607
|
const recentContext = buildRecentCorrectiveActionsContext();
|
|
4625
|
-
const
|
|
5608
|
+
const designContext = safeSecretStorageWrite ? null : buildDesignSelfCorrectionContext(toolName, toolInput);
|
|
5609
|
+
const combinedContext = combineWithSessionDedupe(input, lessonContext, recentContext, behavioralContext, designContext);
|
|
4626
5610
|
return formatOutput(posturedResult, combinedContext);
|
|
4627
5611
|
|
|
4628
5612
|
}
|
|
4629
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
|
+
|
|
4630
5636
|
|
|
4631
5637
|
// A command can be spelled many ways without changing what it does: `sudo git …`,
|
|
4632
5638
|
// `"git" …`, `/usr/bin/git …`, `GIT_DIR=… git …`, a chained `echo hi && git …`, or a git
|
|
@@ -4647,20 +5653,82 @@ function canonicalRetryInput(toolName, toolInput) {
|
|
|
4647
5653
|
return { ...toolInput, command: canonical, originalCommand: original };
|
|
4648
5654
|
}
|
|
4649
5655
|
|
|
4650
|
-
|
|
4651
|
-
|
|
5656
|
+
function oneShotPayloadNeedsControl(toolName, toolInput) {
|
|
5657
|
+
if (!toolInput || typeof toolInput !== 'object' || Array.isArray(toolInput)) return false;
|
|
5658
|
+
const name = String(toolName || '');
|
|
5659
|
+
const status = typeof toolInput.status === 'string' ? toolInput.status.trim().toLowerCase() : '';
|
|
5660
|
+
if ((name === 'record_task_outcome' || name === 'verify_claim') && (status === 'completed' || status === 'done')) {
|
|
5661
|
+
return true;
|
|
5662
|
+
}
|
|
5663
|
+
if (toolInput.modelSaysDone === true || toolInput.goalDone === true) return true;
|
|
5664
|
+
const flag = (value) => value === true || value === 1 || value === 'true';
|
|
5665
|
+
if (flag(toolInput.budgetExhausted) || flag(toolInput.uncapped) || flag(toolInput.irreversible) || flag(toolInput.approvalRequired)) {
|
|
5666
|
+
return true;
|
|
5667
|
+
}
|
|
5668
|
+
return Object.prototype.hasOwnProperty.call(toolInput, 'quotedUsd');
|
|
5669
|
+
}
|
|
5670
|
+
|
|
5671
|
+
function oneshotUnreadableDeny() {
|
|
5672
|
+
const message = 'ThumbGate could not read the OneShot control. The call is held. [oneshot-control]';
|
|
5673
|
+
return {
|
|
5674
|
+
decision: 'deny',
|
|
5675
|
+
gate: 'oneshot-control',
|
|
5676
|
+
ruleId: 'control_unreadable',
|
|
5677
|
+
reason: message,
|
|
5678
|
+
message,
|
|
5679
|
+
severity: 'high',
|
|
5680
|
+
};
|
|
5681
|
+
}
|
|
5682
|
+
|
|
5683
|
+
function applyOneShotPretool(toolName, toolInput) {
|
|
5684
|
+
let mod = null;
|
|
5685
|
+
try {
|
|
5686
|
+
mod = require('./action-receipts');
|
|
5687
|
+
} catch {
|
|
5688
|
+
mod = null;
|
|
5689
|
+
}
|
|
5690
|
+
const needs = mod && typeof mod.oneShotPayloadNeedsControl === 'function'
|
|
5691
|
+
? mod.oneShotPayloadNeedsControl(toolName, toolInput)
|
|
5692
|
+
: oneShotPayloadNeedsControl(toolName, toolInput);
|
|
5693
|
+
if (!needs) return null;
|
|
5694
|
+
if (!mod || typeof mod.evaluateOneShotPretool !== 'function') return oneshotUnreadableDeny();
|
|
5695
|
+
try {
|
|
5696
|
+
return mod.evaluateOneShotPretool(toolName, toolInput);
|
|
5697
|
+
} catch {
|
|
5698
|
+
return oneshotUnreadableDeny();
|
|
5699
|
+
}
|
|
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
|
+
}
|
|
5709
|
+
|
|
5710
|
+
async function evaluateGatesAsync(toolName, toolInput, configPath, options = {}) {
|
|
5711
|
+
const oneshot = applyOneShotPretool(toolName, toolInput);
|
|
5712
|
+
if (oneshot) return oneshot;
|
|
5713
|
+
const direct = await evaluateGatesAsyncInner(toolName, toolInput, configPath, options);
|
|
4652
5714
|
if (direct) return direct;
|
|
5715
|
+
const brandStandards = applyBrandStandardsHook(toolName, toolInput);
|
|
5716
|
+
if (brandStandards) return brandStandards;
|
|
4653
5717
|
const retry = canonicalRetryInput(toolName, toolInput);
|
|
4654
5718
|
if (!retry) return null;
|
|
4655
|
-
return evaluateGatesAsyncInner(toolName, retry, configPath);
|
|
5719
|
+
return evaluateGatesAsyncInner(toolName, retry, configPath, options);
|
|
4656
5720
|
}
|
|
4657
5721
|
|
|
4658
|
-
function evaluateGates(toolName, toolInput, configPath) {
|
|
4659
|
-
const
|
|
5722
|
+
function evaluateGates(toolName, toolInput, configPath, options = {}) {
|
|
5723
|
+
const oneshot = applyOneShotPretool(toolName, toolInput);
|
|
5724
|
+
if (oneshot) return oneshot;
|
|
5725
|
+
const direct = evaluateGatesInner(toolName, toolInput, configPath, options);
|
|
4660
5726
|
if (direct) return direct;
|
|
5727
|
+
const brandStandards = applyBrandStandardsHook(toolName, toolInput);
|
|
5728
|
+
if (brandStandards) return brandStandards;
|
|
4661
5729
|
const retry = canonicalRetryInput(toolName, toolInput);
|
|
4662
5730
|
if (!retry) return null;
|
|
4663
|
-
return evaluateGatesInner(toolName, retry, configPath);
|
|
5731
|
+
return evaluateGatesInner(toolName, retry, configPath, options);
|
|
4664
5732
|
}
|
|
4665
5733
|
|
|
4666
5734
|
// ---------------------------------------------------------------------------
|
|
@@ -5093,6 +6161,11 @@ module.exports = {
|
|
|
5093
6161
|
hasAction,
|
|
5094
6162
|
listSessionActions,
|
|
5095
6163
|
clearSessionActions,
|
|
6164
|
+
observeSwarmClaimResult,
|
|
6165
|
+
observeTeamsSendResult,
|
|
6166
|
+
evaluateRepeatedMistakeGates,
|
|
6167
|
+
setCrossReviewLookup,
|
|
6168
|
+
formatObserveStop,
|
|
5096
6169
|
loadClaimGates,
|
|
5097
6170
|
registerClaimGate,
|
|
5098
6171
|
normalizeGoalContract,
|
|
@@ -5112,6 +6185,7 @@ module.exports = {
|
|
|
5112
6185
|
DEFAULT_PROTECTED_FILE_GLOBS,
|
|
5113
6186
|
buildBehavioralContext,
|
|
5114
6187
|
buildRecentCorrectiveActionsContext,
|
|
6188
|
+
combineWithSessionDedupe,
|
|
5115
6189
|
buildRelevantLessonContext,
|
|
5116
6190
|
buildRelevantLessonContextAsync,
|
|
5117
6191
|
extractActionContext,
|
|
@@ -5167,3 +6241,15 @@ if (require.main === module) {
|
|
|
5167
6241
|
}
|
|
5168
6242
|
});
|
|
5169
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
|
+
}
|