fix(ci): reject duplicate hook events and report duplicate ID lines

This commit is contained in:
Yann Roberto committed 2026-11-17 11:26:43 +08:00
1 parent 8abdf329ec
commit 9de259d581
5 files changed
+110 -30

No files matched your search

+1
View File
@@ -34,6 +34,7 @@
"eslint": "10.13.0",
"express": "4.22.3",
"globals": "17.13.0",
"jsonc-parser": "3.3.1",
"markdownlint-cli": "0.49.1",
"typescript": "6.0.3"
},
+1
View File
@@ -595,6 +595,7 @@
"eslint": "10.13.0",
"express": "4.22.3",
"globals": "17.13.0",
"jsonc-parser": "3.3.1",
"markdownlint-cli": "0.49.1",
"typescript": "6.0.3"
},
+50 -28
View File
@@ -7,6 +7,7 @@ const fs = require('fs');
const path = require('path');
const vm = require('vm');
const Ajv = require('ajv');
const { visit } = require('jsonc-parser');
/**
* Resolve a module by its repo-relative path.
@@ -287,20 +288,56 @@ function isValidMatcherValue(value) {
return typeof value === 'string' || (typeof value === 'object' && value !== null);
}
// Inspect the source before JSON.parse discards earlier members with the same name.
function checkHookDuplicates(source, eventMap) {
const events = new Map();
const ids = new Map();
visit(source, {
onObjectProperty(key, _offset, _length, line, _column, getPath) {
const parent = getPath();
if (parent.length !== 1 || parent[0] !== eventMap) return;
if (events.has(key)) {
throw new Error(`line ${line + 1}: duplicate event key '${key}' (first on line ${events.get(key)})`);
}
events.set(key, line + 1);
},
onLiteralValue(value, _offset, _length, line, _column, getPath) {
const location = getPath();
const [container, event, index, field] = location;
if (location.length !== 4 || container !== eventMap || field !== 'id') return;
if (typeof event !== 'string' || typeof index !== 'number' || !isNonEmptyString(value)) return;
const matcher = `${event}[${index}]`;
if (ids.has(value)) {
throw new Error(`line ${line + 1}: ${matcher} has duplicate id '${value}' (already used by ${ids.get(value)})`);
}
ids.set(value, `${matcher} on line ${line + 1}`);
},
});
}
function readHookDocument(file, eventMap) {
const name = path.basename(file);
try {
const source = fs.readFileSync(file, 'utf-8');
checkHookDuplicates(source, eventMap);
return JSON.parse(source);
} catch (error) {
const label = error instanceof SyntaxError ? `Invalid JSON in ${name}` : name;
console.error(`ERROR: ${label}: ${error.message}`);
process.exit(1);
}
}
function readHooksFile() {
if (!fs.existsSync(HOOKS_FILE)) {
console.log('No hooks.json found, skipping validation');
process.exit(0);
}
let data;
try {
data = JSON.parse(fs.readFileSync(HOOKS_FILE, 'utf-8'));
} catch (e) {
console.error(`ERROR: Invalid JSON in hooks.json: ${e.message}`);
process.exit(1);
}
return data;
return readHookDocument(HOOKS_FILE, 'hooks');
}
/**
@@ -317,13 +354,7 @@ function loadMetadata(data, metadataPath) {
return null;
}
let metadata;
try {
metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));
} catch (e) {
console.error(`ERROR: Invalid JSON in ${METADATA_FILENAME}: ${e.message}`);
process.exit(1);
}
let metadata = readHookDocument(metadataPath, 'entries');
if (validateHarnessCompatibility(data)) {
process.exit(1);
@@ -368,24 +399,16 @@ function validateHookEntries(entries, label) {
}
/**
* Validate one matcher of the object format. `ids` tracks stable ids when the
* document requires them, and is null otherwise.
* Validate one matcher of the object format.
* @returns {boolean} true if errors were found
*/
function validateObjectMatcher(eventType, index, matcher, ids) {
function validateObjectMatcher(eventType, index, matcher, requiresStableIds) {
const matcherLabel = `${eventType}[${index}]`;
let hasErrors = false;
if (ids && !isNonEmptyString(matcher.id)) {
if (requiresStableIds && !isNonEmptyString(matcher.id)) {
console.error(`ERROR: ${matcherLabel} missing or invalid 'id' field`);
hasErrors = true;
} else if (ids && ids.has(matcher.id)) {
console.error(
`ERROR: ${matcherLabel} has duplicate id '${matcher.id}' (already used by ${ids.get(matcher.id)})`
);
hasErrors = true;
} else if (ids) {
ids.set(matcher.id, matcherLabel);
}
if (!('matcher' in matcher) && !EVENTS_WITHOUT_MATCHER.has(eventType)) {
@@ -411,7 +434,6 @@ function validateObjectMatcher(eventType, index, matcher, ids) {
* @returns {{ hasErrors: boolean, totalMatchers: number }}
*/
function validateObjectFormat(hooks, requiresStableIds) {
const ids = requiresStableIds ? new Map() : null;
let hasErrors = false;
let totalMatchers = 0;
@@ -435,7 +457,7 @@ function validateObjectFormat(hooks, requiresStableIds) {
hasErrors = true;
continue;
}
if (validateObjectMatcher(eventType, i, matcher, ids)) {
if (validateObjectMatcher(eventType, i, matcher, requiresStableIds)) {
hasErrors = true;
}
totalMatchers++;
+56 -1
View File
@@ -3014,6 +3014,32 @@ function runTests() {
cleanupTestDir(testDir);
})) passed++; else failed++;
for (const [file, eventMap] of [['hooks.json', 'hooks'], ['hooks.metadata.json', 'entries']]) {
if (test(`reports the second occurrence of a duplicate event in ${file}`, () => {
const testDir = createTestDir();
try {
const hooksFile = path.join(testDir, 'hooks.json');
writeJson(hooksFile, { hooks: { Stop: [] } });
// JSON.parse decodes both spellings as Stop and discards the first entry.
fs.writeFileSync(path.join(testDir, file), String.raw`{
"${eventMap}": {
"Stop": [],
"St\u006fp": []
}
}`);
const result = runValidatorWithDir('validate-hooks', 'HOOKS_FILE', hooksFile);
assert.strictEqual(result.code, 1, result.stdout);
assert.ok(result.stderr.includes(file), result.stderr);
assert.match(result.stderr, /duplicate/i);
assert.match(result.stderr, /Stop/);
assert.match(result.stderr, /(?:\bline\s+|:)4\b/i);
} finally {
cleanupTestDir(testDir);
}
})) passed++; else failed++;
}
if (test('rejects duplicate wrapped matcher ids across events', () => {
const testDir = createTestDir();
const hooksFile = path.join(testDir, 'hooks.json');
@@ -3030,7 +3056,7 @@ function runTests() {
hooks: [{ type: 'command', command: 'echo post' }]
}]
}
}));
}, null, 2));
const result = runValidatorWithDir('validate-hooks', 'HOOKS_FILE', hooksFile);
assert.strictEqual(result.code, 1, 'Should reject matcher ids reused by another event');
@@ -3042,9 +3068,38 @@ function runTests() {
result.stderr.includes('PreToolUse[0]') && result.stderr.includes('PostToolUse[0]'),
`Should report both matcher locations, got: ${result.stderr}`
);
assert.ok(result.stderr.includes('hooks.json'), result.stderr);
assert.match(result.stderr, /(?:\bline\s+|:)17\b/i);
cleanupTestDir(testDir);
})) passed++; else failed++;
if (test('reports the source line of a duplicate sidecar id across events', () => {
const testDir = createTestDir();
try {
const hooksFile = path.join(testDir, 'hooks.json');
const entry = { hooks: [{ type: 'command', command: 'echo ok' }] };
writeJson(hooksFile, { hooks: { Stop: [entry], UserPromptSubmit: [entry] } });
const { fingerprintHookEntry } = require('../../scripts/lib/hooks-config');
const metadata = JSON.stringify({ id: 'shared:matcher', fingerprint: fingerprintHookEntry(entry) });
fs.writeFileSync(path.join(testDir, 'hooks.metadata.json'), `{
"entries": {
"Stop": [${metadata}],
"UserPromptSubmit": [
${metadata}]
}
}`);
const result = runValidatorWithDir('validate-hooks', 'HOOKS_FILE', hooksFile);
assert.strictEqual(result.code, 1, result.stdout);
assert.ok(result.stderr.includes('hooks.metadata.json'), result.stderr);
assert.match(result.stderr, /duplicate/i);
assert.match(result.stderr, /shared:matcher/);
assert.match(result.stderr, /(?:\bline\s+|:)5\b/i);
} finally {
cleanupTestDir(testDir);
}
})) passed++; else failed++;
// ── Round 79: validate-commands.js warnings count suffix in output ──
console.log('\nRound 79: validate-commands.js (warnings count in output):');
+2 -1
View File
@@ -883,6 +883,7 @@ __metadata:
express: "npm:4.22.3"
globals: "npm:17.13.0"
js-yaml: "npm:5.5.0"
jsonc-parser: "npm:3.3.1"
markdownlint-cli: "npm:0.49.1"
sql.js: "npm:1.15.2"
typescript: "npm:6.0.3"
@@ -1589,7 +1590,7 @@ __metadata:
languageName: node
linkType: hard
"jsonc-parser@npm:~3.3.1":
"jsonc-parser@npm:3.3.1, jsonc-parser@npm:~3.3.1":
version: 3.3.1
resolution: "jsonc-parser@npm:3.3.1"
checksum: 10c0/269c3ae0a0e4f907a914bf334306c384aabb9929bd8c99f909275ebd5c2d3bc70b9bcd119ad794f339dec9f24b6a4ee9cd5a8ab2e6435e730ad4075388fc2ab6