Repository navigation
Expand file tree
/
Copy pathposttooluse-dispatcher.js
More file actions
294 lines (266 loc) · 10.1 KB
/
Copy pathposttooluse-dispatcher.js
File metadata and controls
294 lines (266 loc) · 10.1 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
#!/usr/bin/env node
/**
* Consolidates PostToolUse hooks into one synchronous and one asynchronous
* entrypoint while preserving each hook's ID, matcher, profile, and output.
*/
'use strict';
const path = require('path');
const { StringDecoder } = require('string_decoder');
const { VALID_PROFILES, normalizeId, parseProfiles } = require('../lib/hook-flags');
const { runPostBash } = require('./bash-hook-dispatcher');
const { run: runQualityGate } = require('./quality-gate');
const { run: runDesignQualityCheck } = require('./design-quality-check');
const { run: runPostEditAccumulator } = require('./post-edit-accumulator');
const { run: runConsoleWarn } = require('./post-edit-console-warn');
const { run: runGovernanceCapture } = require('./governance-capture');
const { run: runSessionActivityTracker } = require('./session-activity-tracker');
const { run: runObserve } = require('./observe-runner');
const { run: runMetricsBridge } = require('./ecc-metrics-bridge');
const { run: runContextMonitor } = require('./ecc-context-monitor');
const MAX_STDIN = 1024 * 1024;
const SYNC_HOOKS = [
{ id: 'post:edit:design-quality-check', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/design-quality-check.js', run: runDesignQualityCheck },
{ id: 'post:edit:accumulator', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-accumulator.js', run: runPostEditAccumulator },
{ id: 'post:edit:console-warn', matcher: 'Edit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-console-warn.js', run: runConsoleWarn },
{ id: 'post:governance-capture', matcher: 'Bash|Write|Edit|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/governance-capture.js', run: runGovernanceCapture },
{ id: 'post:session-activity-tracker', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/session-activity-tracker.js', run: runSessionActivityTracker },
{ id: 'post:ecc-metrics-bridge', matcher: '*', profiles: 'minimal,standard,strict', script: 'scripts/hooks/ecc-metrics-bridge.js', run: runMetricsBridge },
{ id: 'post:ecc-context-monitor', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/ecc-context-monitor.js', run: runContextMonitor }
];
const ASYNC_HOOKS = [
{
id: 'post:bash:dispatcher',
matcher: 'Bash',
// main ran this phase unconditionally; sub-hooks gate themselves internally
profiles: 'minimal,standard,strict',
script: 'scripts/hooks/post-bash-dispatcher.js',
run(raw) {
const result = runPostBash(raw);
return { stdout: result.output, stderr: result.stderr, exitCode: result.exitCode };
}
},
{ id: 'post:quality-gate', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/quality-gate.js', run: runQualityGate },
{ id: 'post:observe:continuous-learning', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/observe-runner.js', run: runObserve }
];
function getPluginRoot(env = process.env) {
return env.CLAUDE_PLUGIN_ROOT || env.ECC_PLUGIN_ROOT || path.resolve(__dirname, '..', '..');
}
function matchesTool(matcher, toolName) {
return (
matcher === '*' ||
String(matcher || '')
.split('|')
.map(value => value.trim())
.filter(Boolean)
.includes(String(toolName || ''))
);
}
function isEnabled(hook, env) {
const disabled = new Set(
String(env.ECC_DISABLED_HOOKS || '')
.split(',')
.map(normalizeId)
.filter(Boolean)
);
const requestedProfile = String(env.ECC_HOOK_PROFILE || 'standard')
.trim()
.toLowerCase();
const profile = VALID_PROFILES.has(requestedProfile) ? requestedProfile : 'standard';
return !disabled.has(normalizeId(hook.id)) && parseProfiles(hook.profiles).includes(profile);
}
function extractToolName(raw) {
try {
return String(JSON.parse(raw)?.tool_name || '');
} catch {
return '';
}
}
function buildDryRunPreview(hook, raw) {
let target = '';
try {
const input = JSON.parse(raw)?.tool_input || {};
target = String(input.file_path || input.path || input.command || '');
} catch {
target = '';
}
const suffix = target ? ` target=${target}` : '';
return `[DryRun] Hook "${hook.id}" would execute: ${hook.script} (enabled=true, profiles=${hook.profiles})${suffix}\n`;
}
function normalizeResult(raw, output) {
if (typeof output === 'string' || Buffer.isBuffer(output)) {
const stdout = String(output);
return { stdout: stdout !== raw ? stdout : '', stderr: '', exitCode: 0 };
}
if (!output || typeof output !== 'object') {
return { stdout: '', stderr: '', exitCode: 0 };
}
let stdout = '';
if (Object.prototype.hasOwnProperty.call(output, 'stdout')) {
stdout = String(output.stdout ?? '');
} else if (Object.prototype.hasOwnProperty.call(output, 'output')) {
stdout = String(output.output ?? '');
} else if (Object.prototype.hasOwnProperty.call(output, 'additionalContext')) {
stdout = JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PostToolUse',
additionalContext: String(output.additionalContext ?? '')
}
});
}
return {
stdout: stdout !== raw ? stdout : '',
stderr: typeof output.stderr === 'string' ? output.stderr : '',
exitCode: Number.isInteger(output.exitCode) ? output.exitCode : 0
};
}
function appendLine(current, next) {
if (!next) return current;
return current + (String(next).endsWith('\n') ? String(next) : `${next}\n`);
}
function parseAdditionalContext(stdout) {
try {
const parsed = JSON.parse(stdout);
const output = parsed?.hookSpecificOutput;
if (output?.hookEventName !== 'PostToolUse') return null;
return typeof output.additionalContext === 'string' ? output.additionalContext : null;
} catch {
return null;
}
}
function mergeHookStdout(outputs) {
if (outputs.length === 0) return { stdout: '', warning: '' };
if (outputs.length === 1) return { stdout: outputs[0].stdout, warning: '' };
const contexts = outputs.map(output => parseAdditionalContext(output.stdout));
if (contexts.every(context => context !== null)) {
return {
stdout: JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PostToolUse',
additionalContext: contexts.join('\n')
}
}),
warning: ''
};
}
const kept = outputs[outputs.length - 1];
const dropped = outputs
.slice(0, -1)
.map(output => output.id)
.join(', ');
return {
stdout: kept.stdout,
warning: `[Hook] stdout from ${dropped} dropped in favor of ${kept.id}; raw stdout cannot be merged`
};
}
function runHooks(raw, hooks, options = {}) {
const env = options.env || process.env;
const toolName = options.toolName ?? extractToolName(raw);
const pluginRoot = getPluginRoot(env);
const outputs = [];
let stderr = '';
let exitCode = 0;
for (const hook of hooks) {
if (!matchesTool(hook.matcher, toolName) || !isEnabled(hook, env)) continue;
if (env.ECC_DRY_RUN === '1') {
stderr += buildDryRunPreview(hook, raw);
continue;
}
try {
const result = normalizeResult(
raw,
hook.run(raw, {
hookId: hook.id,
pluginRoot,
scriptPath: path.join(pluginRoot, hook.script || ''),
truncated: options.truncated === true,
maxStdin: MAX_STDIN
})
);
if (result.stdout) outputs.push({ id: hook.id, stdout: result.stdout });
stderr = appendLine(stderr, result.stderr);
if (result.exitCode !== 0) {
if (exitCode === 0) exitCode = result.exitCode;
stderr = appendLine(stderr, `[Hook] ${hook.id} exited with code ${result.exitCode}; continuing`);
}
} catch (error) {
stderr = appendLine(stderr, `[Hook] ${hook.id} failed: ${error.message}`);
}
}
const merged = mergeHookStdout(outputs);
if (merged.warning) stderr = appendLine(stderr, merged.warning);
return { stdout: merged.stdout, stderr, exitCode };
}
function readStdinRaw() {
return new Promise(resolve => {
const decoder = new StringDecoder('utf8');
let raw = '';
let bytesRead = 0;
let truncated = false;
let settled = false;
process.stdin.on('data', chunk => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
const remaining = Math.max(0, MAX_STDIN - bytesRead);
const accepted = buffer.subarray(0, remaining);
if (accepted.length > 0) {
raw += decoder.write(accepted);
bytesRead += accepted.length;
}
if (buffer.length > accepted.length) truncated = true;
});
const finish = () => {
if (settled) return;
settled = true;
if (!truncated) raw += decoder.end();
resolve({ raw, truncated });
};
process.stdin.once('end', finish);
process.stdin.once('error', finish);
});
}
function resolveMainStdout(raw, result, options = {}) {
if (result.stdout) return result.stdout;
if (options.truncated || result.exitCode !== 0 || !options.passthrough) return '';
return raw;
}
async function main() {
const mode = process.argv[2] === 'async' ? 'async' : 'sync';
const { raw, truncated } = await readStdinRaw();
const dispatcherId = `post:dispatcher:${mode}`;
const dispatcherEnabled = isEnabled(
{
id: dispatcherId,
profiles: 'minimal,standard,strict'
},
process.env
);
const hooks = dispatcherEnabled ? (mode === 'async' ? ASYNC_HOOKS : SYNC_HOOKS) : [];
const result = runHooks(raw, hooks, { truncated });
if (truncated) {
process.stderr.write(`[Hook] stdin exceeded ${MAX_STDIN} bytes for PostToolUse ${mode}; suppressing pass-through\n`);
}
if (result.stderr) process.stderr.write(result.stderr);
const stdout = resolveMainStdout(raw, result, {
passthrough: process.env.ECC_POSTTOOLUSE_PASSTHROUGH === '1',
truncated
});
if (stdout) process.stdout.write(stdout);
process.exitCode = result.exitCode;
}
function cli() {
main().catch(error => {
process.stderr.write(`[Hook] PostToolUse dispatcher failed: ${error.message}\n`);
process.exitCode = 0;
});
}
if (require.main === module) cli();
module.exports = {
ASYNC_HOOKS,
SYNC_HOOKS,
cli,
matchesTool,
main,
mergeHookStdout,
normalizeResult,
resolveMainStdout,
runHooks
};