The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(hooks): enforce loader-documented keys in shipped hooks configs (#3163)
Affaan Mustafa34de45f210e8
diff --git a/hooks/README.md b/hooks/README.mdindex 620ef981f..06df4413b 100644--- a/hooks/README.md+++ b/hooks/README.md@@ -19,7 +19,7 @@ User request → Claude picks a tool → PreToolUse hook runs → Tool executesMemory persistence lifecycle definitions live in `hooks/memory-persistence/`.The executable hook graph remains `hooks/hooks.json`; the memory persistence directory is the stable contract for SessionStart, PreCompact, observation, activity tracking, and SessionEnd behavior.-Stable hook IDs and descriptions live in `hooks/hooks.metadata.json`, aligned by event and index with `hooks/hooks.json`. Claude Code validates a plugin's `hooks.json` against its own schema and reports any other key (`$schema`, `id`, `description`) as unknown at load time, so `hooks.json` carries only what the harness accepts. ECC's installer, validator, and dashboard merge the sidecar back in through `scripts/lib/hooks-config.js`; `node scripts/ci/validate-hooks.js` fails if the two files drift apart.+Stable hook IDs and descriptions live in `hooks/hooks.metadata.json`, aligned by event and index with `hooks/hooks.json`. Claude Code validates a plugin's `hooks.json` against its own schema and reports any other key (`$schema`, `id`, `description`) as unknown at load time, so `hooks.json` carries only what the harness accepts. ECC's installer, validator, and dashboard merge the sidecar back in through `scripts/lib/hooks-config.js`; `node scripts/ci/validate-hooks.js` fails if the two files drift apart, and `node scripts/ci/check-hooks-schema-keys.js` fails if `hooks.json` or `hooks/codex-hooks.json` carry any key outside their loader's documented set.Each sidecar entry also carries a `fingerprint` of the matcher entry it describes (matcher plus hook commands), so reordering `hooks.json` without reordering the sidecar, or editing a command without updating the sidecar, is caught rather than silently swapping IDs. When reordering hooks, move the matching sidecar entries first. Then run `node scripts/ci/validate-hooks.js --update-fingerprints` to refresh changed commands and commit both files. The updater rejects known fingerprints at different positions and writes only after validation succeeds.diff --git a/package.json b/package.jsonindex 87487a914..839f94081 100644--- a/package.json+++ b/package.json@@ -479,7 +479,7 @@"orchestrate:status": "node scripts/orchestration-status.js","orchestrate:worker": "bash scripts/orchestrate-codex-worker.sh","orchestrate:tmux": "node scripts/orchestrate-worktrees.js",- "test": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check && node tests/run-all.js",+ "test": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check && node tests/run-all.js","coverage": "c8 --all --include=\"scripts/**/*.js\" --include=\"scripts/**/*.mjs\" --check-coverage --lines 80 --functions 80 --branches 79 --statements 80 --reporter=text --reporter=lcov node tests/run-all.js","build:opencode": "node scripts/build-opencode.js","prepack": "npm run build:opencode",diff --git a/scripts/ci/check-hooks-schema-keys.js b/scripts/ci/check-hooks-schema-keys.jsnew file mode 100755index 000000000..2b6f3f66d--- /dev/null+++ b/scripts/ci/check-hooks-schema-keys.js@@ -0,0 +1,139 @@+#!/usr/bin/env node+/**+ * Fail when a shipped hooks config carries keys outside its loader's+ * documented set.+ *+ * Claude Code validates a plugin's hooks.json against its own schema at load+ * time and prints "unknown keys ... ignored" for anything else (issues #3138+ * and #3114). The documented set for Claude Code is:+ * root: hooks+ * group: matcher, hooks+ * handler: the keys defined by schemas/hooks.schema.json hook item types+ * plus statusMessage (recognized by the loader, absent from the+ * local schema).+ * Stable ids and descriptions for Claude hooks live in hooks.metadata.json,+ * merged back by scripts/lib/hooks-config.js, so hooks.json must not carry+ * them.+ *+ * hooks/codex-hooks.json is checked against the Codex loader's documented+ * set, which tests/plugin-manifest.test.js pins as:+ * root: description, hooks (Codex accepts description, rejects $schema)+ * group: matcher, hooks, id, description (id pinned for traceability)+ * handler: type, command, timeout (Codex executes command handlers only)+ */++const fs = require('fs');+const path = require('path');++const HOOKS_FILE = path.join(__dirname, '../../hooks/hooks.json');+const CODEX_HOOKS_FILE = path.join(__dirname, '../../hooks/codex-hooks.json');++const LOADER_KEY_SETS = [+ {+ label: 'Claude Code',+ file: HOOKS_FILE,+ rootKeys: ['hooks'],+ groupKeys: ['matcher', 'hooks'],+ handlerKeys: [+ 'type', 'command', 'timeout', 'statusMessage', 'async',+ 'url', 'headers', 'allowedEnvVars', 'prompt', 'model',+ ],+ },+ {+ label: 'Codex',+ file: CODEX_HOOKS_FILE,+ rootKeys: ['description', 'hooks'],+ groupKeys: ['matcher', 'hooks', 'id', 'description'],+ handlerKeys: ['type', 'command', 'timeout'],+ },+];++/**+ * Collect every key outside the documented set for one parsed hooks config.+ *+ * @param {object} data - Parsed hooks config.+ * @param {object} keySet - Entry from LOADER_KEY_SETS.+ * @returns {string[]} human-readable findings+ */+function findUnknownKeys(data, keySet) {+ const findings = [];+ const fileLabel = path.basename(keySet.file);++ for (const key of Object.keys(data)) {+ if (!keySet.rootKeys.includes(key)) {+ findings.push(`${fileLabel}: root key "${key}" is not in the ${keySet.label} documented set`);+ }+ }++ const events = data.hooks && typeof data.hooks === 'object' && !Array.isArray(data.hooks)+ ? data.hooks+ : {};+ for (const [eventType, groups] of Object.entries(events)) {+ if (!Array.isArray(groups)) continue;+ groups.forEach((group, groupIndex) => {+ if (!group || typeof group !== 'object' || Array.isArray(group)) return;+ for (const key of Object.keys(group)) {+ if (!keySet.groupKeys.includes(key)) {+ findings.push(+ `${fileLabel}: ${eventType}[${groupIndex}] key "${key}" is not in the ${keySet.label} documented set`+ );+ }+ }+ if (!Array.isArray(group.hooks)) return;+ group.hooks.forEach((handler, handlerIndex) => {+ if (!handler || typeof handler !== 'object' || Array.isArray(handler)) return;+ for (const key of Object.keys(handler)) {+ if (!keySet.handlerKeys.includes(key)) {+ findings.push(+ `${fileLabel}: ${eventType}[${groupIndex}].hooks[${handlerIndex}] key "${key}" `+ + `is not in the ${keySet.label} documented set`+ );+ }+ }+ });+ });+ }++ return findings;+}++function checkHooksSchemaKeys() {+ const findings = [];+ let checked = 0;++ for (const keySet of LOADER_KEY_SETS) {+ if (!fs.existsSync(keySet.file)) {+ console.log(`No ${path.basename(keySet.file)} found, skipping ${keySet.label} key check`);+ continue;+ }+ let data;+ try {+ data = JSON.parse(fs.readFileSync(keySet.file, 'utf-8'));+ } catch (e) {+ console.error(`ERROR: Invalid JSON in ${keySet.file}: ${e.message}`);+ findings.push('invalid JSON');+ continue;+ }+ if (!data || typeof data !== 'object' || Array.isArray(data)) {+ console.error(`ERROR: ${keySet.file} must contain a JSON object`);+ findings.push('not an object');+ continue;+ }+ checked += 1;+ findings.push(...findUnknownKeys(data, keySet));+ }++ if (findings.length > 0) {+ for (const finding of findings) {+ if (!finding.startsWith('invalid') && finding !== 'not an object') {+ console.error(`ERROR: ${finding}`);+ }+ }+ console.error(`\n${findings.length} key(s) outside the documented loader set`);+ process.exit(1);+ }++ console.log(`Checked ${checked} hooks config(s): all keys within the documented loader sets`);+}++checkHooksSchemaKeys();diff --git a/tests/ci/validators.test.js b/tests/ci/validators.test.jsindex 8f0a92eab..dcfe341f7 100644--- a/tests/ci/validators.test.js+++ b/tests/ci/validators.test.js@@ -445,6 +445,110 @@ function runTests() {assert.ok(result.stdout.includes('Validated'), 'Should output validation count');})) passed++; else failed++;+ // ==========================================+ // check-hooks-schema-keys.js+ // ==========================================+ console.log('\ncheck-hooks-schema-keys.js:');++ if (test('passes on real project hooks configs', () => {+ const result = runValidator('check-hooks-schema-keys');+ assert.strictEqual(result.code, 0, `Should pass, got stderr: ${result.stderr}`);+ assert.ok(result.stdout.includes('Checked 2 hooks config(s)'), 'Should report both configs checked');+ })) passed++; else failed++;++ if (test('exits 0 when hooks.json does not exist', () => {+ const result = runValidatorWithDir('check-hooks-schema-keys', 'HOOKS_FILE', '/nonexistent/hooks.json');+ assert.strictEqual(result.code, 0, 'Should skip when no hooks.json');+ assert.ok(result.stdout.includes('skipping'), 'Should say skipping');+ })) passed++; else failed++;++ if (test('fails on root $schema key', () => {+ const testDir = createTestDir();+ const hooksFile = path.join(testDir, 'hooks.json');+ fs.writeFileSync(hooksFile, JSON.stringify({+ $schema: '../schemas/hooks.schema.json',+ hooks: {}+ }));++ const result = runValidatorWithDir('check-hooks-schema-keys', 'HOOKS_FILE', hooksFile);+ assert.strictEqual(result.code, 1, 'Should fail on root $schema');+ assert.ok(result.stderr.includes('"$schema"'), 'Should name the offending key');+ cleanupTestDir(testDir);+ })) passed++; else failed++;++ if (test('fails on group id and description keys', () => {+ const testDir = createTestDir();+ const hooksFile = path.join(testDir, 'hooks.json');+ fs.writeFileSync(hooksFile, JSON.stringify({+ hooks: {+ PreToolUse: [{+ id: 'test:group',+ description: 'metadata that belongs in the sidecar',+ matcher: 'Bash',+ hooks: [{ type: 'command', command: 'echo hi' }]+ }]+ }+ }));++ const result = runValidatorWithDir('check-hooks-schema-keys', 'HOOKS_FILE', hooksFile);+ assert.strictEqual(result.code, 1, 'Should fail on group id/description');+ assert.ok(result.stderr.includes('"id"'), 'Should name id');+ assert.ok(result.stderr.includes('"description"'), 'Should name description');+ cleanupTestDir(testDir);+ })) passed++; else failed++;++ if (test('fails on unknown handler key', () => {+ const testDir = createTestDir();+ const hooksFile = path.join(testDir, 'hooks.json');+ fs.writeFileSync(hooksFile, JSON.stringify({+ hooks: {+ Stop: [{ hooks: [{ type: 'command', command: 'echo hi', label: 'not a loader key' }] }]+ }+ }));++ const result = runValidatorWithDir('check-hooks-schema-keys', 'HOOKS_FILE', hooksFile);+ assert.strictEqual(result.code, 1, 'Should fail on unknown handler key');+ assert.ok(result.stderr.includes('"label"'), 'Should name the offending handler key');+ cleanupTestDir(testDir);+ })) passed++; else failed++;++ if (test('fails on codex-hooks.json root $schema key', () => {+ const testDir = createTestDir();+ const hooksFile = path.join(testDir, 'codex-hooks.json');+ fs.writeFileSync(hooksFile, JSON.stringify({+ $schema: '../schemas/hooks.schema.json',+ description: 'codex projection',+ hooks: {+ SessionStart: [{ id: 'session:start', matcher: '.*', hooks: [{ type: 'command', command: 'echo hi' }] }]+ }+ }));++ const result = runValidatorWithDir('check-hooks-schema-keys', 'CODEX_HOOKS_FILE', hooksFile);+ assert.strictEqual(result.code, 1, 'Should fail on codex root $schema');+ assert.ok(result.stderr.includes('"$schema"'), 'Should name the offending key');+ cleanupTestDir(testDir);+ })) passed++; else failed++;++ if (test('accepts codex documented keys including group id and root description', () => {+ const testDir = createTestDir();+ const hooksFile = path.join(testDir, 'codex-hooks.json');+ fs.writeFileSync(hooksFile, JSON.stringify({+ description: 'codex projection',+ hooks: {+ SessionStart: [{+ id: 'session:start',+ description: 'pinned by plugin-manifest test',+ matcher: '.*',+ hooks: [{ type: 'command', command: 'echo hi', timeout: 5 }]+ }]+ }+ }));++ const result = runValidatorWithDir('check-hooks-schema-keys', 'CODEX_HOOKS_FILE', hooksFile);+ assert.strictEqual(result.code, 0, `Should pass, got stderr: ${result.stderr}`);+ cleanupTestDir(testDir);+ })) passed++; else failed++;+// ==========================================// catalog.js// ==========================================