-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgates-engine.js
More file actions
2353 lines (2084 loc) · 81.2 KB
/
gates-engine.js
File metadata and controls
2353 lines (2084 loc) · 81.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { execSync, execFileSync } = require('child_process');
const { loadOptionalModule } = require('./private-core-boundary');
const { isProTier, FREE_TIER_MAX_GATES } = require('./rate-limiter');
const {
DEFAULT_BASE_BRANCH,
evaluateOperationalIntegrity,
} = require('./operational-integrity');
const {
evaluateWorkflowSentinel,
} = require('./workflow-sentinel');
const {
recordDecisionEvaluation,
recordDecisionOutcome,
} = require('./decision-journal');
/**
* Computes the SHA-256 hash of an executable binary to prevent path-based bypasses.
* (Layer 5: Supply Chain / Layer 3: Execution)
*/
function computeExecutableHash(command) {
try {
if (!command) return null;
const firstWord = command.trim().split(/\s+/)[0];
if (!firstWord) return null;
// Resolve absolute path using 'which'
let fullPath;
try {
fullPath = execSync(`which ${firstWord}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch (e) {
// If 'which' fails, it might be an absolute path or a non-existent command
fullPath = path.isAbsolute(firstWord) ? firstWord : null;
}
if (!fullPath || !fs.existsSync(fullPath) || !fs.lstatSync(fullPath).isFile()) return null;
const buffer = fs.readFileSync(fullPath);
return crypto.createHash('sha256').update(buffer).digest('hex');
} catch (e) {
return null;
}
}
const {
scanHookInput,
buildSafeSummary,
redactText,
} = require('./secret-scanner');
const {
evaluateSecurityScan,
} = require('./security-scanner');
const { getAutoGatesPath } = require('./auto-promote-gates');
const { recordAuditEvent, auditToFeedback } = require('./audit-trail');
const DEFAULT_CONFIG_PATH = path.join(__dirname, '..', 'config', 'gates', 'default.json');
const DEFAULT_CLAIM_GATES_PATH = path.join(__dirname, '..', 'config', 'gates', 'claim-verification.json');
const STATE_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'gate-state.json');
const CONSTRAINTS_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'session-constraints.json');
const STATS_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'gate-stats.json');
const SESSION_ACTIONS_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'session-actions.json');
const CUSTOM_CLAIM_GATES_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'claim-verification.json');
const GOVERNANCE_STATE_PATH = path.join(process.env.HOME || '/tmp', '.thumbgate', 'governance-state.json');
const TTL_MS = 5 * 60 * 1000; // 5 minutes
const SESSION_ACTION_TTL_MS = 60 * 60 * 1000; // 1 hour
const PROTECTED_APPROVAL_TTL_MS = 60 * 60 * 1000; // 1 hour
const DEFAULT_PROTECTED_FILE_GLOBS = [
'AGENTS.md',
'CLAUDE.md',
'CLAUDE.local.md',
'GEMINI.md',
'README.md',
'.gitignore',
'.husky/**',
'.claude/**',
'skills/**',
'SKILL.md',
'config/gates/**',
];
const EDIT_LIKE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit']);
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;
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;
const BOOSTED_RISK_BLOCK_SCORE = 0.8;
const BOOSTED_RISK_MIN_EXAMPLES = 3;
const PR_THREAD_RESOLUTION_ACTION = 'pr_thread_resolution_verified_after_commit';
const PR_THREAD_RESOLUTION_CLAIM_PATTERN = '(?:thread|review|comment).*?(?:resolved|verified|checked|addressed|fixed)|(?:resolved|verified|checked|addressed|fixed).*?(?:thread|review|comment)';
const PR_THREAD_RESOLUTION_REQUIRED_ACTIONS = ['pr_threads_checked', 'thread_resolution_verified'];
// ---------------------------------------------------------------------------
// Config loading
// ---------------------------------------------------------------------------
function loadGatesConfig(configPath, harnessPath) {
const primaryPath = configPath || process.env.THUMBGATE_GATES_CONFIG || DEFAULT_CONFIG_PATH;
if (!fs.existsSync(primaryPath)) {
throw new Error(`Gates config not found: ${primaryPath}`);
}
const mergedConfig = { version: 1, gates: [] };
const loadOne = (p, isPrimary) => {
try {
const raw = fs.readFileSync(p, 'utf8');
const config = JSON.parse(raw);
if (!config || !Array.isArray(config.gates)) {
if (isPrimary) throw new Error('Invalid gates config: missing "gates" array');
return;
}
return config.gates;
} catch (e) {
if (isPrimary) throw e;
console.error(`Warning: failed to load gates from ${p}: ${e.message}`);
return [];
}
};
const primaryGates = loadOne(primaryPath, true).map(g => ({ ...g, layer: g.layer || 'Execution' }));
mergedConfig.gates.push(...primaryGates);
// Always preserve the full primary/default safety policy. Free tier limits apply
// only to auto-promoted add-on gates so core protections never disappear.
const autoConfigPath = getAutoGatesPath();
if (!configPath && fs.existsSync(autoConfigPath)) {
const autoGates = loadOne(autoConfigPath, false).map(g => ({ ...g, layer: g.layer || 'Execution' }));
const limitedAutoGates = isProTier()
? autoGates
: autoGates.slice(0, FREE_TIER_MAX_GATES);
mergedConfig.gates.push(...limitedAutoGates);
}
// Load workflow-specific harness gates (always additive, never replaces default).
// Resolved by harness-selector based on tool name + command context.
const resolvedHarness = harnessPath || process.env.THUMBGATE_HARNESS_CONFIG;
if (resolvedHarness && fs.existsSync(resolvedHarness)) {
const harnessGates = (loadOne(resolvedHarness, false) || [])
.map(g => ({ ...g, layer: g.layer || 'Execution', source: g.source || 'harness' }));
mergedConfig.gates.push(...harnessGates);
}
return mergedConfig;
}
// ---------------------------------------------------------------------------
// State and Constraints management
// ---------------------------------------------------------------------------
function loadJSON(filePath) {
if (!fs.existsSync(filePath)) return {};
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch {
return {};
}
}
function saveJSON(filePath, data) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n');
}
function loadState() { return loadJSON(module.exports.STATE_PATH); }
function saveState(state) { saveJSON(module.exports.STATE_PATH, state); }
function loadConstraints() { return loadJSON(module.exports.CONSTRAINTS_PATH); }
function saveConstraints(constraints) { saveJSON(module.exports.CONSTRAINTS_PATH, constraints); }
function normalizePosix(filePath) {
return String(filePath || '')
.replace(/\\/g, '/')
.replace(/^\.\//, '')
.replace(/^\/+/, '')
.trim();
}
function normalizeGlob(glob) {
return normalizePosix(glob).replace(/\/+$/, '');
}
function sanitizeGlobList(globs) {
if (!Array.isArray(globs)) return [];
return [...new Set(globs.map((glob) => normalizeGlob(glob)).filter(Boolean))];
}
function globToRegExp(glob) {
const normalized = normalizeGlob(glob);
let pattern = '^';
for (let i = 0; i < normalized.length; i++) {
const char = normalized[i];
const next = normalized[i + 1];
if (char === '*') {
if (next === '*') {
pattern += '.*';
i += 1;
} else {
pattern += '[^/]*';
}
continue;
}
if ('\\^$+?.()|{}[]'.includes(char)) {
pattern += `\\${char}`;
continue;
}
pattern += char;
}
pattern += '$';
return new RegExp(pattern);
}
function matchesGlob(filePath, glob) {
if (!glob) return false;
try {
return globToRegExp(glob).test(normalizePosix(filePath));
} catch {
return false;
}
}
function matchesAnyGlob(filePath, globs) {
return sanitizeGlobList(globs).some((glob) => matchesGlob(filePath, glob));
}
function clampTtlMs(value, fallbackMs) {
const fallback = Number.isFinite(fallbackMs) ? fallbackMs : PROTECTED_APPROVAL_TTL_MS;
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
return Math.min(Math.max(numeric, 60 * 1000), 24 * 60 * 60 * 1000);
}
function loadGovernanceState() {
const raw = loadJSON(module.exports.GOVERNANCE_STATE_PATH);
const state = {
taskScope: raw && raw.taskScope && typeof raw.taskScope === 'object' ? raw.taskScope : null,
protectedApprovals: Array.isArray(raw && raw.protectedApprovals) ? raw.protectedApprovals : [],
branchGovernance: raw && raw.branchGovernance && typeof raw.branchGovernance === 'object'
? raw.branchGovernance
: null,
};
const now = Date.now();
const activeApprovals = state.protectedApprovals.filter((entry) => {
if (!entry || typeof entry !== 'object') return false;
if (!entry.timestamp || !entry.expiresAt) return false;
return now < entry.expiresAt;
});
if (activeApprovals.length !== state.protectedApprovals.length) {
state.protectedApprovals = activeApprovals;
saveGovernanceState(state);
}
return state;
}
function saveGovernanceState(state) {
const next = {
taskScope: state && state.taskScope ? state.taskScope : null,
protectedApprovals: Array.isArray(state && state.protectedApprovals) ? state.protectedApprovals : [],
branchGovernance: state && state.branchGovernance ? state.branchGovernance : null,
};
saveJSON(module.exports.GOVERNANCE_STATE_PATH, next);
}
function setTaskScope(scopeInput = {}) {
if (scopeInput && scopeInput.clear === true) {
const currentState = loadGovernanceState();
const cleared = {
taskScope: null,
protectedApprovals: currentState.protectedApprovals,
branchGovernance: currentState.branchGovernance,
};
saveGovernanceState(cleared);
return null;
}
const allowedPaths = sanitizeGlobList(scopeInput.allowedPaths);
if (allowedPaths.length === 0) {
throw new Error('allowedPaths must be a non-empty array');
}
const protectedPaths = sanitizeGlobList(
Array.isArray(scopeInput.protectedPaths) && scopeInput.protectedPaths.length > 0
? scopeInput.protectedPaths
: DEFAULT_PROTECTED_FILE_GLOBS
);
const taskScope = {
taskId: String(scopeInput.taskId || '').trim() || null,
summary: String(scopeInput.summary || '').trim() || null,
allowedPaths,
protectedPaths,
localOnly: scopeInput.localOnly === true,
repoPath: String(scopeInput.repoPath || '').trim() || null,
createdAt: new Date().toISOString(),
timestamp: Date.now(),
};
const state = loadGovernanceState();
state.taskScope = taskScope;
saveGovernanceState(state);
if (taskScope.localOnly) {
setConstraint('local_only', true);
}
return taskScope;
}
function approveProtectedAction(input = {}) {
const pathGlobs = sanitizeGlobList(input.pathGlobs);
if (pathGlobs.length === 0) {
throw new Error('pathGlobs must be a non-empty array');
}
const reason = String(input.reason || '').trim();
if (!reason) {
throw new Error('reason is required');
}
const ttlMs = clampTtlMs(input.ttlMs, PROTECTED_APPROVAL_TTL_MS);
const now = Date.now();
const entry = {
id: `approval_${now}_${Math.random().toString(36).slice(2, 8)}`,
pathGlobs,
reason,
evidence: String(input.evidence || '').trim() || null,
taskId: String(input.taskId || '').trim() || null,
timestamp: now,
expiresAt: now + ttlMs,
};
const state = loadGovernanceState();
state.protectedApprovals.push(entry);
saveGovernanceState(state);
return entry;
}
function setBranchGovernance(input = {}) {
if (input && input.clear === true) {
const state = loadGovernanceState();
state.branchGovernance = null;
saveGovernanceState(state);
return null;
}
const branchName = String(input.branchName || '').trim() || null;
const baseBranch = String(input.baseBranch || '').trim() || DEFAULT_BASE_BRANCH;
const releaseSensitiveGlobs = sanitizeGlobList(
Array.isArray(input.releaseSensitiveGlobs) ? input.releaseSensitiveGlobs : []
);
const governance = {
branchName,
baseBranch,
prRequired: input.prRequired !== false,
prNumber: String(input.prNumber || '').trim() || null,
prUrl: String(input.prUrl || '').trim() || null,
queueRequired: input.queueRequired === true,
localOnly: input.localOnly === true,
releaseVersion: String(input.releaseVersion || '').trim() || null,
releaseEvidence: String(input.releaseEvidence || '').trim() || null,
releaseSensitiveGlobs,
timestamp: Date.now(),
createdAt: new Date().toISOString(),
};
const state = loadGovernanceState();
state.branchGovernance = governance;
saveGovernanceState(state);
if (governance.localOnly) {
setConstraint('local_only', true);
}
return governance;
}
function getScopeState() {
return loadGovernanceState();
}
function getBranchGovernanceState() {
return loadGovernanceState().branchGovernance;
}
function setConstraint(key, value) {
const constraints = loadConstraints();
constraints[key] = {
value,
timestamp: Date.now()
};
saveConstraints(constraints);
return constraints[key];
}
function isConditionSatisfied(conditionId) {
const state = loadState();
const entry = state[conditionId];
if (!entry) return false;
const age = Date.now() - entry.timestamp;
return age < TTL_MS;
}
function satisfyCondition(conditionId, evidence, structuredReasoning) {
const state = loadState();
const entry = {
timestamp: Date.now(),
evidence: evidence || '',
};
if (structuredReasoning && typeof structuredReasoning === 'object') {
entry.structuredReasoning = {
premise: structuredReasoning.premise || null,
evidence: structuredReasoning.evidence || null,
risk: structuredReasoning.risk || null,
conclusion: structuredReasoning.conclusion || null,
};
}
state[conditionId] = entry;
saveState(state);
return entry;
}
// ---------------------------------------------------------------------------
// Stats tracking
// ---------------------------------------------------------------------------
function loadStats() {
const stats = loadJSON(module.exports.STATS_PATH);
if (Object.keys(stats).length === 0) return { blocked: 0, warned: 0, passed: 0, byGate: {} };
return stats;
}
function saveStats(stats) { saveJSON(module.exports.STATS_PATH, stats); }
function recordStat(gateId, action, gate) {
const stats = loadStats();
if (action === 'block') stats.blocked = (stats.blocked || 0) + 1;
else if (action === 'warn') stats.warned = (stats.warned || 0) + 1;
else if (action === 'approve') stats.pendingApproval = (stats.pendingApproval || 0) + 1;
else if (action === 'log') stats.logged = (stats.logged || 0) + 1;
else stats.passed = (stats.passed || 0) + 1;
if (!stats.byGate) stats.byGate = {};
if (!stats.byGate[gateId]) stats.byGate[gateId] = { blocked: 0, warned: 0, pendingApproval: 0, logged: 0 };
if (action === 'block') stats.byGate[gateId].blocked += 1;
else if (action === 'warn') stats.byGate[gateId].warned += 1;
else if (action === 'approve') stats.byGate[gateId].pendingApproval = (stats.byGate[gateId].pendingApproval || 0) + 1;
else if (action === 'log') stats.byGate[gateId].logged = (stats.byGate[gateId].logged || 0) + 1;
saveStats(stats);
// Track lesson freshness when an auto-promoted gate fires
if (gate && gate.sourceLessonId) {
try {
const { recordTrigger } = require('./lesson-rotation');
const { initDB } = require('./lesson-db');
const db = initDB();
recordTrigger(db, gate.sourceLessonId);
db.close();
} catch (_) { /* lesson DB may not be available */ }
}
}
// ---------------------------------------------------------------------------
// Reasoning chain builder
// ---------------------------------------------------------------------------
function getHybridFeedbackModule() {
try {
return require('./hybrid-feedback-context');
} catch {
return null;
}
}
function safeExecFileLines(binary, args, cwd) {
try {
const output = execFileSync(binary, args, {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (!output) return [];
return output.split('\n').map((line) => line.trim()).filter(Boolean);
} catch {
return [];
}
}
function resolveRepoRoot(toolInput = {}) {
const candidates = [
toolInput.repoPath,
toolInput.cwd,
process.cwd(),
]
.filter(Boolean)
.map((value) => path.resolve(String(value)));
for (const cwd of candidates) {
try {
const root = execFileSync('git', ['rev-parse', '--show-toplevel'], {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (root) return root;
} catch {
continue;
}
}
return null;
}
function toRepoRelativePath(filePath, repoRoot) {
const value = String(filePath || '').trim();
if (!value) return '';
if (repoRoot && path.isAbsolute(value)) {
const relative = path.relative(repoRoot, value);
if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
return normalizePosix(relative);
}
}
return normalizePosix(value);
}
function collectInlineAffectedFiles(toolInput = {}, repoRoot) {
const collected = [];
const arrayFields = [
toolInput.changed_files,
toolInput.changedFiles,
toolInput.files,
toolInput.file_paths,
toolInput.filePaths,
toolInput.paths,
];
for (const field of arrayFields) {
if (!Array.isArray(field)) continue;
for (const entry of field) {
const normalized = toRepoRelativePath(entry, repoRoot);
if (normalized) collected.push(normalized);
}
}
const scalarFields = [
toolInput.file_path,
toolInput.filePath,
toolInput.path,
];
for (const field of scalarFields) {
const normalized = toRepoRelativePath(field, repoRoot);
if (normalized) collected.push(normalized);
}
return [...new Set(collected)];
}
function getUpstreamRef(repoRoot) {
const upstream = safeExecFileLines('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], repoRoot)[0];
if (upstream) return upstream;
const remoteHead = safeExecFileLines('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], repoRoot)[0];
if (remoteHead) return remoteHead.replace(/^refs\/remotes\//, '');
return null;
}
function getBranchDiffFiles(repoRoot) {
const upstream = getUpstreamRef(repoRoot);
if (upstream) {
return safeExecFileLines('git', ['diff', '--name-only', `${upstream}...HEAD`], repoRoot);
}
const headParent = safeExecFileLines('git', ['rev-parse', '--verify', 'HEAD~1'], repoRoot)[0];
if (headParent) {
return safeExecFileLines('git', ['diff', '--name-only', 'HEAD~1..HEAD'], repoRoot);
}
return safeExecFileLines('git', ['diff', '--name-only'], repoRoot);
}
function extractAffectedFiles(toolName, toolInput = {}) {
const repoRoot = resolveRepoRoot(toolInput);
const files = new Set(collectInlineAffectedFiles(toolInput, repoRoot));
const command = String(toolInput.command || '');
if (toolName === 'Bash' && repoRoot && command) {
if (/\bgit\s+commit\b/i.test(command)) {
for (const filePath of safeExecFileLines('git', ['diff', '--cached', '--name-only'], repoRoot)) {
files.add(normalizePosix(filePath));
}
}
if (/\bgit\s+add\b/i.test(command)) {
for (const filePath of safeExecFileLines('git', ['diff', '--name-only'], repoRoot)) {
files.add(normalizePosix(filePath));
}
for (const filePath of safeExecFileLines('git', ['ls-files', '--others', '--exclude-standard'], repoRoot)) {
files.add(normalizePosix(filePath));
}
}
if (/\bgit\s+push\b/i.test(command) || /\bgh\s+pr\s+(?:create|merge)\b/i.test(command)) {
for (const filePath of getBranchDiffFiles(repoRoot)) {
files.add(normalizePosix(filePath));
}
}
}
return {
repoRoot,
files: [...files].filter(Boolean),
};
}
function isHighRiskAction(toolName, toolInput = {}, affectedFiles = []) {
if (EDIT_LIKE_TOOLS.has(toolName)) return true;
if (toolName !== 'Bash') return false;
const command = String(toolInput.command || '');
// Original high-risk pattern (git writes, publishes, destructive ops)
if (HIGH_RISK_BASH_PATTERN.test(command)) return true;
// Broadened: any Bash command that modifies files or has side effects.
// Excludes pure read/analysis commands (node --test, cat, ls, echo, etc.)
// to avoid false positives on benign operations.
if (/\b(sed|awk|mv|cp|chmod|chown|truncate|tee|patch)\b/.test(command)) return true;
if (/\b(npm\s+(?:run|exec|install)|yarn|pnpm)\b/.test(command)) return true;
if (/\b(curl|wget)\b/.test(command)) return true;
return false;
}
function normalizeRiskToken(value) {
return String(value || '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}
function singularizeRiskToken(token) {
const value = String(token || '').trim();
if (value.length > 3 && value.endsWith('ies')) return `${value.slice(0, -3)}y`;
if (value.length > 3 && value.endsWith('s')) return value.slice(0, -1);
return value;
}
function riskTokenVariants(token) {
const normalized = singularizeRiskToken(token);
const variants = new Set([token, normalized]);
const synonyms = {
comment: ['comment', 'comments', 'review', 'reviews', 'reply', 'replies', 'thread', 'threads'],
thread: ['thread', 'threads', 'review', 'reviews', 'comment', 'comments'],
bot: ['bot', 'bots', 'automation', 'automated', 'assistant', 'claude', 'codex'],
pr: ['pr', 'pull', 'pullrequest', 'pullrequests'],
file: ['file', 'files', 'path', 'paths'],
test: ['test', 'tests', 'ci', 'coverage', 'verify', 'verification'],
};
for (const candidate of [token, normalized]) {
for (const item of synonyms[candidate] || []) {
variants.add(item);
variants.add(singularizeRiskToken(item));
}
}
return [...variants].filter(Boolean);
}
function normalizeRiskTagEntry(entry) {
if (!entry) return null;
if (typeof entry === 'string') {
return { tag: entry };
}
if (typeof entry !== 'object') return null;
const tag = entry.tag || entry.key || entry.name || entry.domain || entry.label || entry.id;
if (!tag) return null;
return {
tag: String(tag),
count: Number(entry.count ?? entry.examples ?? entry.exampleCount ?? entry.total ?? entry.samples),
failures: Number(entry.failures ?? entry.failureCount),
riskRate: Number(entry.riskRate ?? entry.rate ?? entry.failureRate ?? entry.score ?? entry.riskScore),
};
}
function collectBoostedRiskTags(toolInput = {}) {
const boostedRisk = toolInput.boostedRisk && typeof toolInput.boostedRisk === 'object'
? toolInput.boostedRisk
: {};
const sources = [
toolInput.highRiskTags,
toolInput.riskTags,
boostedRisk.highRiskTags,
boostedRisk.tags,
boostedRisk.highRiskDomains,
];
const tags = [];
for (const source of sources) {
if (Array.isArray(source)) {
tags.push(...source.map(normalizeRiskTagEntry).filter(Boolean));
}
}
return tags;
}
function isBoostedRiskHigh(toolInput = {}) {
const boostedRisk = toolInput.boostedRisk && typeof toolInput.boostedRisk === 'object'
? toolInput.boostedRisk
: {};
const level = String(boostedRisk.riskLevel || boostedRisk.level || boostedRisk.mode || '').toLowerCase();
if (/\b(?:high|critical|block|deny)\b/.test(level)) return true;
const riskScore = Number(boostedRisk.riskScore ?? boostedRisk.score ?? boostedRisk.riskRate ?? boostedRisk.failureRate ?? boostedRisk.baseRate);
if (Number.isFinite(riskScore) && riskScore >= BOOSTED_RISK_BLOCK_SCORE) return true;
const exampleCount = Number(boostedRisk.exampleCount ?? boostedRisk.count ?? boostedRisk.samples ?? boostedRisk.total);
const failureCount = Number(boostedRisk.failureCount ?? boostedRisk.failures);
if (
Number.isFinite(exampleCount) &&
exampleCount >= BOOSTED_RISK_MIN_EXAMPLES &&
Number.isFinite(failureCount) &&
failureCount / Math.max(exampleCount, 1) >= BOOSTED_RISK_BLOCK_SCORE
) {
return true;
}
return collectBoostedRiskTags(toolInput).some((entry) => {
if (Number.isFinite(entry.riskRate) && entry.riskRate >= BOOSTED_RISK_BLOCK_SCORE) return true;
if (Number.isFinite(entry.count) && entry.count >= BOOSTED_RISK_MIN_EXAMPLES && !Number.isFinite(entry.riskRate)) return true;
if (
Number.isFinite(entry.count) &&
entry.count >= BOOSTED_RISK_MIN_EXAMPLES &&
Number.isFinite(entry.failures) &&
entry.failures / Math.max(entry.count, 1) >= BOOSTED_RISK_BLOCK_SCORE
) {
return true;
}
return false;
});
}
function riskTagMatchesAction(tag, actionContext) {
const normalizedTag = normalizeRiskToken(tag);
const normalizedAction = normalizeRiskToken(actionContext);
if (!normalizedTag || !normalizedAction) return false;
const actionTokens = new Set(normalizedAction.split(/\s+/).filter(Boolean));
const tagTokens = normalizedTag.split(/\s+/).filter(Boolean);
return tagTokens.some((token) => riskTokenVariants(token).some((variant) => actionTokens.has(variant)));
}
function evaluateBoostedRiskTagGuard(toolName, toolInput = {}) {
const tags = collectBoostedRiskTags(toolInput);
if (tags.length === 0 || !isBoostedRiskHigh(toolInput)) return null;
const actionContext = extractActionContext(toolName, toolInput);
const matchedTag = tags.find((entry) => riskTagMatchesAction(entry.tag, actionContext));
if (!matchedTag) return null;
const matchText = toolInput.command || toolInput.file_path || toolInput.path || actionContext;
const message = `Boosted-risk history matched this action (${matchedTag.tag}). This pattern is denied by default until explicit evidence lowers the risk.`;
return {
decision: 'deny',
gate: 'boosted-risk-tag-default-deny',
message,
severity: 'critical',
reasoning: [
`High-risk tag "${matchedTag.tag}" matched "${String(matchText).slice(0, 120)}"`,
`Risk threshold: score >= ${BOOSTED_RISK_BLOCK_SCORE} or at least ${BOOSTED_RISK_MIN_EXAMPLES} examples`,
'Hook enforcement blocks this pre-tool call instead of relying on advisory recall',
],
};
}
function isGitCommitCommand(toolName, toolInput = {}) {
return toolName === 'Bash' && /\bgit\s+commit\b/i.test(String(toolInput.command || ''));
}
function isProtectedBranchName(branchName) {
return /^(?:main|master|develop|dev|trunk|release)$/i.test(String(branchName || '').trim());
}
function detectBranchName(toolInput = {}, repoRoot = null) {
const inline = toolInput.branchName || toolInput.currentBranch || toolInput.branch || toolInput.headRefName;
if (inline) return String(inline).trim();
if (!repoRoot) return '';
return safeExecFileLines('git', ['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot)[0] || '';
}
function hasPrBranchContext(toolInput = {}, repoRoot = null) {
if (toolInput.prNumber || toolInput.prUrl || toolInput.pullRequestNumber || toolInput.pullRequestUrl) {
return true;
}
const branchName = detectBranchName(toolInput, repoRoot);
return Boolean(branchName && !isProtectedBranchName(branchName));
}
function registerPrThreadResolutionClaimGate(toolName, toolInput = {}) {
if (!isGitCommitCommand(toolName, toolInput)) return null;
const repoRoot = resolveRepoRoot(toolInput);
if (!hasPrBranchContext(toolInput, repoRoot)) return null;
const branchName = detectBranchName(toolInput, repoRoot);
const claimGate = registerClaimGate(
PR_THREAD_RESOLUTION_CLAIM_PATTERN,
PR_THREAD_RESOLUTION_REQUIRED_ACTIONS,
'A PR-branch commit requires verified review-thread resolution before more tool calls or readiness claims.',
);
trackAction(PR_THREAD_RESOLUTION_ACTION, {
branchName: branchName || null,
repoRoot: repoRoot || null,
commandHash: crypto.createHash('sha256').update(String(toolInput.command || '')).digest('hex'),
});
return claimGate;
}
function isThreadResolutionSatisfied() {
return PR_THREAD_RESOLUTION_REQUIRED_ACTIONS.some((actionId) => (
hasAction(actionId) || isConditionSatisfied(actionId)
));
}
function isThreadResolutionEvidenceAction(toolName, toolInput = {}) {
if (isGitCommitCommand(toolName, toolInput)) return true;
if (['recall', 'search_lessons', 'verify_claim', 'satisfy_gate', 'track_action'].includes(toolName)) return true;
if (toolName !== 'Bash') return false;
const command = String(toolInput.command || '');
return /\b(?:gate-satisfy|satisfy_gate|track_action|gh\s+pr\s+(?:view|checks|status)|gh\s+api\b.*(?:reviewThreads|reviews|comments|threads)|git\s+(?:status|diff|show))\b/i.test(command);
}
function evaluatePendingPrThreadResolutionGate(toolName, toolInput = {}) {
if (!hasAction(PR_THREAD_RESOLUTION_ACTION)) return null;
if (isThreadResolutionSatisfied()) return null;
if (isThreadResolutionEvidenceAction(toolName, toolInput)) return null;
const message = 'A git commit was made on a PR branch. Verify review threads are resolved before the next tool call.';
return {
decision: 'deny',
gate: 'pr-thread-resolution-verified-required',
message,
severity: 'critical',
reasoning: [
`Tracked action ${PR_THREAD_RESOLUTION_ACTION} is pending`,
'Satisfy pr_threads_checked or thread_resolution_verified with evidence before continuing',
],
};
}
function getLocalOnlyScopeSources(governanceState = {}, constraints = {}) {
const sources = [];
if (governanceState.taskScope && governanceState.taskScope.localOnly) {
sources.push('task scope');
}
if (governanceState.branchGovernance && governanceState.branchGovernance.localOnly) {
sources.push('branch governance');
}
if (constraints.local_only && constraints.local_only.value === true) {
sources.push('local_only constraint');
}
return sources;
}
function isRemoteSideEffectCommand(toolName, toolInput = {}) {
if (toolName !== 'Bash') return false;
return REMOTE_SIDE_EFFECT_BASH_PATTERN.test(String(toolInput.command || ''));
}
function evaluateLocalOnlyRemoteSideEffectGate(toolName, toolInput = {}, governanceState = {}, constraints = {}) {
if (!isRemoteSideEffectCommand(toolName, toolInput)) return null;
const sources = getLocalOnlyScopeSources(governanceState, constraints);
if (sources.length === 0) return null;
const command = String(toolInput.command || '').trim();
return {
decision: 'deny',
gate: 'local-only-remote-side-effect',
message: 'Task scope is local-only; remote git, PR, release, and publish actions are blocked until the local-only scope is cleared or explicitly changed.',
severity: 'critical',
reasoning: [
`Local-only source: ${sources.join(', ')}`,
`Blocked command: ${command.slice(0, 160)}`,
'Remote side effects are denied before configurable gates so wrapped commands cannot bypass local-only work boundaries',
],
};
}
function recordStructuralGateBlock(toolName, toolInput, result) {
recordStat(result.gate, 'block');
const auditRecord = recordAuditEvent({
toolName,
toolInput,
decision: 'deny',
gateId: result.gate,
message: result.message,
severity: result.severity,
source: 'gates-engine',
});
auditToFeedback(auditRecord);
return result;
}
function isScopeEnforcedAction(toolName, toolInput = {}, affectedFiles = []) {
if (EDIT_LIKE_TOOLS.has(toolName) && affectedFiles.length > 0) return true;
if (toolName !== 'Bash') return false;
const command = String(toolInput.command || '');
if (!HIGH_RISK_BASH_PATTERN.test(command)) return false;
return affectedFiles.length > 0;
}
function shouldEnforceTaskScope(gate, governanceState, toolName, toolInput = {}, affectedFiles = []) {
if (gate.scopeMode === 'declared-only') {
return Boolean(governanceState && governanceState.taskScope) &&
EDIT_LIKE_TOOLS.has(toolName) &&
affectedFiles.length > 0;
}
return isScopeEnforcedAction(toolName, toolInput, affectedFiles);
}
function formatFileList(files, limit = 5) {
const items = Array.isArray(files) ? files.filter(Boolean) : [];
if (items.length === 0) return 'none';
if (items.length <= limit) return items.join(', ');
return `${items.slice(0, limit).join(', ')} (+${items.length - limit} more)`;
}
function buildTaskScopeViolation(taskScope, affectedFiles) {
if (!Array.isArray(affectedFiles) || affectedFiles.length === 0) return null;
if (!taskScope || !Array.isArray(taskScope.allowedPaths) || taskScope.allowedPaths.length === 0) {
return {
reasonCode: 'missing_task_scope',
outsideFiles: affectedFiles.slice(),
allowedPaths: [],
summary: null,
};
}
const outsideFiles = affectedFiles.filter((filePath) => !matchesAnyGlob(filePath, taskScope.allowedPaths));
if (outsideFiles.length === 0) return null;
return {
reasonCode: 'outside_declared_scope',
outsideFiles,
allowedPaths: taskScope.allowedPaths.slice(),
summary: taskScope.summary || null,
};
}
function buildProtectedApprovalViolation(protectedGlobs, approvals, affectedFiles) {
const normalizedProtected = sanitizeGlobList(protectedGlobs);
if (normalizedProtected.length === 0 || !Array.isArray(affectedFiles) || affectedFiles.length === 0) {
return null;
}
const protectedFiles = affectedFiles.filter((filePath) => matchesAnyGlob(filePath, normalizedProtected));
if (protectedFiles.length === 0) return null;
const activeApprovals = Array.isArray(approvals) ? approvals : [];
const missingApprovalFiles = protectedFiles.filter((filePath) => {
return !activeApprovals.some((entry) => matchesAnyGlob(filePath, entry.pathGlobs || []));
});
if (missingApprovalFiles.length === 0) return null;
return {
protectedFiles,
missingApprovalFiles,
protectedGlobs: normalizedProtected,
};
}
function buildBranchGovernanceViolation(governanceState, toolInput = {}, affectedFiles = [], repoRoot = null, requireReleaseReadiness = false) {
const command = String(toolInput.command || '').trim();
if (!command) return null;
const integrity = evaluateOperationalIntegrity({
repoPath: repoRoot || (governanceState && governanceState.taskScope && governanceState.taskScope.repoPath) || process.cwd(),
branchGovernance: governanceState ? governanceState.branchGovernance : null,
changedFiles: affectedFiles,
command,
requireVersionNotBehindBase: requireReleaseReadiness,
});
if (!integrity || integrity.blockers.length === 0) {
return null;
}
return {
blockers: integrity.blockers,
currentBranch: integrity.currentBranch,
baseBranch: integrity.baseBranch,
releaseSensitiveFiles: integrity.releaseSensitiveFiles,
packageVersion: integrity.packageVersion,
baseVersion: integrity.baseVersion,
};
}
function buildGateMessage(gate, matchDetails) {
if (matchDetails && matchDetails.taskScopeViolation) {
const violation = matchDetails.taskScopeViolation;
if (violation.reasonCode === 'missing_task_scope') {
return `No task scope is declared for this high-risk action. Affected files: ${formatFileList(violation.outsideFiles)}.`;
}
return `Action touches files outside the declared task scope: ${formatFileList(violation.outsideFiles)}. Allowed paths: ${formatFileList(violation.allowedPaths)}.`;
}
if (matchDetails && matchDetails.protectedApprovalViolation) {
const violation = matchDetails.protectedApprovalViolation;
return `Protected files require explicit approval before editing or publishing. Missing approval for: ${formatFileList(violation.missingApprovalFiles)}.`;
}
if (matchDetails && matchDetails.branchGovernanceViolation) {
const [firstBlocker] = matchDetails.branchGovernanceViolation.blockers || [];
if (firstBlocker && firstBlocker.message) {
return firstBlocker.message;
}
}
return gate.message;
}
/**
* Build a human-readable reasoning chain explaining WHY a gate decision was made.