Skip to content

Commit 0b0b66c

Browse files
authored
feat: agent compression, inspection logic, governance hooks (anomalyco#491, anomalyco#485, anomalyco#482) (anomalyco#688)
Implements three roadmap features: - Agent description compression (anomalyco#491): New `agent-compress` module with catalog/summary/full compression modes and lazy-loading. Reduces ~26k token agent descriptions to ~2-3k catalog entries for context efficiency. - Inspection logic (anomalyco#485): New `inspection` module that detects recurring failure patterns in skill_runs. Groups by skill + normalized failure reason, generates structured reports with suggested remediation actions. Configurable threshold (default: 3 failures). - Governance event capture hook (anomalyco#482): PreToolUse/PostToolUse hook that detects secrets, policy violations, approval-required commands, and elevated privilege usage. Gated behind ECC_GOVERNANCE_CAPTURE=1 flag. Writes to governance_events table via JSON-line stderr output. 59 new tests (16 + 16 + 27), all passing.
1 parent 28de7cc commit 0b0b66c

7 files changed

Lines changed: 1563 additions & 0 deletions

File tree

‎hooks/hooks.json‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,17 @@
7474
}
7575
],
7676
"description": "Optional InsAIts AI security monitor for Bash/Edit/Write flows. Enable with ECC_ENABLE_INSAITS=1. Requires: pip install insa-its"
77+
},
78+
{
79+
"matcher": "Bash|Write|Edit|MultiEdit",
80+
"hooks": [
81+
{
82+
"type": "command",
83+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/hooks/run-with-flags.js\" \"pre:governance-capture\" \"scripts/hooks/governance-capture.js\" \"standard,strict\"",
84+
"timeout": 10
85+
}
86+
],
87+
"description": "Capture governance events (secrets, policy violations, approval requests). Enable with ECC_GOVERNANCE_CAPTURE=1"
7788
}
7889
],
7990
"PreCompact": [
@@ -165,6 +176,17 @@
165176
],
166177
"description": "Warn about console.log statements after edits"
167178
},
179+
{
180+
"matcher": "Bash|Write|Edit|MultiEdit",
181+
"hooks": [
182+
{
183+
"type": "command",
184+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/hooks/run-with-flags.js\" \"post:governance-capture\" \"scripts/hooks/governance-capture.js\" \"standard,strict\"",
185+
"timeout": 10
186+
}
187+
],
188+
"description": "Capture governance events from tool outputs. Enable with ECC_GOVERNANCE_CAPTURE=1"
189+
},
168190
{
169191
"matcher": "*",
170192
"hooks": [
Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Governance Event Capture Hook
4+
*
5+
* PreToolUse/PostToolUse hook that detects governance-relevant events
6+
* and writes them to the governance_events table in the state store.
7+
*
8+
* Captured event types:
9+
* - secret_detected: Hardcoded secrets in tool input/output
10+
* - policy_violation: Actions that violate configured policies
11+
* - security_finding: Security-relevant tool invocations
12+
* - approval_requested: Operations requiring explicit approval
13+
*
14+
* Enable: Set ECC_GOVERNANCE_CAPTURE=1
15+
* Configure session: Set ECC_SESSION_ID for session correlation
16+
*/
17+
18+
'use strict';
19+
20+
const crypto = require('crypto');
21+
22+
const MAX_STDIN = 1024 * 1024;
23+
24+
// Patterns that indicate potential hardcoded secrets
25+
const SECRET_PATTERNS = [
26+
{ name: 'aws_key', pattern: /(?:AKIA|ASIA)[A-Z0-9]{16}/i },
27+
{ name: 'generic_secret', pattern: /(?:secret|password|token|api[_-]?key)\s*[:=]\s*["'][^"']{8,}/i },
28+
{ name: 'private_key', pattern: /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/ },
29+
{ name: 'jwt', pattern: /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
30+
{ name: 'github_token', pattern: /gh[pousr]_[A-Za-z0-9_]{36,}/ },
31+
];
32+
33+
// Tool names that represent security-relevant operations
34+
const SECURITY_RELEVANT_TOOLS = new Set([
35+
'Bash', // Could execute arbitrary commands
36+
]);
37+
38+
// Commands that require governance approval
39+
const APPROVAL_COMMANDS = [
40+
/git\s+push\s+.*--force/,
41+
/git\s+reset\s+--hard/,
42+
/rm\s+-rf?\s/,
43+
/DROP\s+(?:TABLE|DATABASE)/i,
44+
/DELETE\s+FROM\s+\w+\s*(?:;|$)/i,
45+
];
46+
47+
// File patterns that indicate policy-sensitive paths
48+
const SENSITIVE_PATHS = [
49+
/\.env(?:\.|$)/,
50+
/credentials/i,
51+
/secrets?\./i,
52+
/\.pem$/,
53+
/\.key$/,
54+
/id_rsa/,
55+
];
56+
57+
/**
58+
* Generate a unique event ID.
59+
*/
60+
function generateEventId() {
61+
return `gov-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
62+
}
63+
64+
/**
65+
* Scan text content for hardcoded secrets.
66+
* Returns array of { name, match } for each detected secret.
67+
*/
68+
function detectSecrets(text) {
69+
if (!text || typeof text !== 'string') return [];
70+
71+
const findings = [];
72+
for (const { name, pattern } of SECRET_PATTERNS) {
73+
if (pattern.test(text)) {
74+
findings.push({ name });
75+
}
76+
}
77+
return findings;
78+
}
79+
80+
/**
81+
* Check if a command requires governance approval.
82+
*/
83+
function detectApprovalRequired(command) {
84+
if (!command || typeof command !== 'string') return [];
85+
86+
const findings = [];
87+
for (const pattern of APPROVAL_COMMANDS) {
88+
if (pattern.test(command)) {
89+
findings.push({ pattern: pattern.source });
90+
}
91+
}
92+
return findings;
93+
}
94+
95+
/**
96+
* Check if a file path is policy-sensitive.
97+
*/
98+
function detectSensitivePath(filePath) {
99+
if (!filePath || typeof filePath !== 'string') return false;
100+
101+
return SENSITIVE_PATHS.some(pattern => pattern.test(filePath));
102+
}
103+
104+
/**
105+
* Analyze a hook input payload and return governance events to capture.
106+
*
107+
* @param {Object} input - Parsed hook input (tool_name, tool_input, tool_output)
108+
* @param {Object} [context] - Additional context (sessionId, hookPhase)
109+
* @returns {Array<Object>} Array of governance event objects
110+
*/
111+
function analyzeForGovernanceEvents(input, context = {}) {
112+
const events = [];
113+
const toolName = input.tool_name || '';
114+
const toolInput = input.tool_input || {};
115+
const toolOutput = typeof input.tool_output === 'string' ? input.tool_output : '';
116+
const sessionId = context.sessionId || null;
117+
const hookPhase = context.hookPhase || 'unknown';
118+
119+
// 1. Secret detection in tool input content
120+
const inputText = typeof toolInput === 'object'
121+
? JSON.stringify(toolInput)
122+
: String(toolInput);
123+
124+
const inputSecrets = detectSecrets(inputText);
125+
const outputSecrets = detectSecrets(toolOutput);
126+
const allSecrets = [...inputSecrets, ...outputSecrets];
127+
128+
if (allSecrets.length > 0) {
129+
events.push({
130+
id: generateEventId(),
131+
sessionId,
132+
eventType: 'secret_detected',
133+
payload: {
134+
toolName,
135+
hookPhase,
136+
secretTypes: allSecrets.map(s => s.name),
137+
location: inputSecrets.length > 0 ? 'input' : 'output',
138+
severity: 'critical',
139+
},
140+
resolvedAt: null,
141+
resolution: null,
142+
});
143+
}
144+
145+
// 2. Approval-required commands (Bash only)
146+
if (toolName === 'Bash') {
147+
const command = toolInput.command || '';
148+
const approvalFindings = detectApprovalRequired(command);
149+
150+
if (approvalFindings.length > 0) {
151+
events.push({
152+
id: generateEventId(),
153+
sessionId,
154+
eventType: 'approval_requested',
155+
payload: {
156+
toolName,
157+
hookPhase,
158+
command: command.slice(0, 200),
159+
matchedPatterns: approvalFindings.map(f => f.pattern),
160+
severity: 'high',
161+
},
162+
resolvedAt: null,
163+
resolution: null,
164+
});
165+
}
166+
}
167+
168+
// 3. Policy violation: writing to sensitive paths
169+
const filePath = toolInput.file_path || toolInput.path || '';
170+
if (filePath && detectSensitivePath(filePath)) {
171+
events.push({
172+
id: generateEventId(),
173+
sessionId,
174+
eventType: 'policy_violation',
175+
payload: {
176+
toolName,
177+
hookPhase,
178+
filePath: filePath.slice(0, 200),
179+
reason: 'sensitive_file_access',
180+
severity: 'warning',
181+
},
182+
resolvedAt: null,
183+
resolution: null,
184+
});
185+
}
186+
187+
// 4. Security-relevant tool usage tracking
188+
if (SECURITY_RELEVANT_TOOLS.has(toolName) && hookPhase === 'post') {
189+
const command = toolInput.command || '';
190+
const hasElevated = /sudo\s/.test(command) || /chmod\s/.test(command) || /chown\s/.test(command);
191+
192+
if (hasElevated) {
193+
events.push({
194+
id: generateEventId(),
195+
sessionId,
196+
eventType: 'security_finding',
197+
payload: {
198+
toolName,
199+
hookPhase,
200+
command: command.slice(0, 200),
201+
reason: 'elevated_privilege_command',
202+
severity: 'medium',
203+
},
204+
resolvedAt: null,
205+
resolution: null,
206+
});
207+
}
208+
}
209+
210+
return events;
211+
}
212+
213+
/**
214+
* Core hook logic — exported so run-with-flags.js can call directly.
215+
*
216+
* @param {string} rawInput - Raw JSON string from stdin
217+
* @returns {string} The original input (pass-through)
218+
*/
219+
function run(rawInput) {
220+
// Gate on feature flag
221+
if (String(process.env.ECC_GOVERNANCE_CAPTURE || '').toLowerCase() !== '1') {
222+
return rawInput;
223+
}
224+
225+
try {
226+
const input = JSON.parse(rawInput);
227+
const sessionId = process.env.ECC_SESSION_ID || null;
228+
const hookPhase = process.env.CLAUDE_HOOK_EVENT_NAME || 'unknown';
229+
230+
const events = analyzeForGovernanceEvents(input, {
231+
sessionId,
232+
hookPhase: hookPhase.startsWith('Pre') ? 'pre' : 'post',
233+
});
234+
235+
if (events.length > 0) {
236+
// Write events to stderr as JSON-lines for the caller to capture.
237+
// The state store write is async and handled by a separate process
238+
// to avoid blocking the hook pipeline.
239+
for (const event of events) {
240+
process.stderr.write(
241+
`[governance] ${JSON.stringify(event)}\n`
242+
);
243+
}
244+
}
245+
} catch {
246+
// Silently ignore parse errors — never block the tool pipeline.
247+
}
248+
249+
return rawInput;
250+
}
251+
252+
// ── stdin entry point ────────────────────────────────
253+
if (require.main === module) {
254+
let raw = '';
255+
process.stdin.setEncoding('utf8');
256+
process.stdin.on('data', chunk => {
257+
if (raw.length < MAX_STDIN) {
258+
const remaining = MAX_STDIN - raw.length;
259+
raw += chunk.substring(0, remaining);
260+
}
261+
});
262+
263+
process.stdin.on('end', () => {
264+
const result = run(raw);
265+
process.stdout.write(result);
266+
});
267+
}
268+
269+
module.exports = {
270+
APPROVAL_COMMANDS,
271+
SECRET_PATTERNS,
272+
SECURITY_RELEVANT_TOOLS,
273+
SENSITIVE_PATHS,
274+
analyzeForGovernanceEvents,
275+
detectApprovalRequired,
276+
detectSecrets,
277+
detectSensitivePath,
278+
generateEventId,
279+
run,
280+
};

0 commit comments

Comments
 (0)