Repository navigation
refactor: data-driven hook dispatcher (v0.22.0) - #92
Conversation
Most hooks were 6-13 line files that only picked a few fields off the input and called runHook. Replace them with a single generic entrypoint (scripts/hook.js <EventName>) plus a field-mapper table (lib/hook-registry.js); hooks.json routes observation-only events through it. Hooks that need runHook options or custom logic keep dedicated entrypoints (session_start, session_end, stop, on_signin_result, user_prompt_expansion_signin). - 20 thin hook files removed; adding an observation-only hook is now a one-line registry entry + a hooks.json line - registry mappers keep the (input, ctx) buildData contract, so ctx-using hooks (e.g. SubagentStop's getTranscriptId) port unchanged - hook.js exits non-zero on an unknown event name - test/lib.test.js locks the registry <-> hooks.json contract (no missing/orphan mappers, event name == argv) - README script tree updated Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KoEUHYQTz1Tx61FcteE979
WalkthroughThe PR centralizes hook execution through ChangesHook Dispatcher Unification
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant hooksjson as hooks.json
participant hookjs as hook.js
participant registry as hook-registry
participant logger as logger.js runHook
hooksjson->>hookjs: node hook.js EventName
hookjs->>registry: lookup EventName mapper
registry-->>hookjs: mapper function
hookjs->>logger: runHook(event, buildData)
logger-->>hookjs: promise resolve/reject
hookjs->>hookjs: exit 1 on rejection
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (4)
skillmeter/test/lib.test.js (1)
122-130: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMinor: prefer a top-level
require("path")instead of an inline import.Line 124 requires
pathinline inside the test body. Hoisting it to the top of the file alongside other requires is more idiomatic and consistent with the CommonJS import style used elsewhere.♻️ Suggested tweak
+const path = require("path"); + test("registry mappers return an object and can use ctx", () => { const registry = require("../scripts/lib/hook-registry"); - const ctx = { getTranscriptId: (p) => (p ? require("path").basename(p) : "") }; + const ctx = { getTranscriptId: (p) => (p ? path.basename(p) : "") };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@skillmeter/test/lib.test.js` around lines 122 - 130, Move the inline require("path") used in the test’s ctx.getTranscriptId helper to the top-level require section of the file so the CommonJS imports are consistent. Update the test body to reference the hoisted path symbol in the registry.SubagentStop and ctx setup, keeping the existing assertions unchanged.Source: Coding guidelines
skillmeter/scripts/hook.js (2)
19-19: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSwallowed rejection hides failure context.
.catch(() => process.exit(1))discards the error, so anyrunHookfailure surfaces only as a bare exit code with no message — harder to diagnose in the field compared to the descriptiveconsole.errorused elsewhere inrunHook/logger.jsfailure paths.🩹 Proposed fix
-runHook(event, buildData).catch(() => process.exit(1)); +runHook(event, buildData).catch((err) => { + process.stderr.write(`[skillmeter] hook.js: ${event} failed (${err && err.message})\n`); + process.exit(1); +});🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@skillmeter/scripts/hook.js` at line 19, The runHook failure path is swallowing the rejection, so the hook exits without any diagnostic context. Update the runHook(event, buildData) promise handling in hook.js to catch the error, report it through the same descriptive logging approach used in runHook/logger.js failure paths, and then exit with a nonzero status so the original failure message is preserved instead of being discarded.
12-17: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winGuard against prototype-inherited registry keys.
registry[event]on a plain object literal can resolve inheritedObject.prototypemembers (constructor,toString,valueOf,hasOwnProperty) which are functions, so thetypeof buildData !== "function"check won't catch them. Ifeventis ever one of those names (manual invocation, future config typo/misconfiguration), e.g.constructorwould run asObject(input, ctx), returning the raw, unfilteredinputobject aseventData— bypassing the whole point of the per-event field minimization the registry mappers exist for.Currently unreachable given today's
hooks.jsonwiring, but cheap to harden.🛡️ Proposed fix
const event = process.argv[2]; -const buildData = registry[event]; +const buildData = Object.prototype.hasOwnProperty.call(registry, event) + ? registry[event] + : undefined; if (typeof buildData !== "function") {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@skillmeter/scripts/hook.js` around lines 12 - 17, The hook lookup in registry[event] is vulnerable to inherited Object.prototype members being treated as valid handlers, so harden the event dispatch in hook.js by checking that the selected key is an own property of registry before using it. Update the logic around event and buildData to reject prototype-inherited names like constructor or toString, keeping the existing error path for invalid events and preserving the intended per-event mapper behavior.skillmeter/scripts/lib/hook-registry.js (1)
106-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDedupe
TaskCreated/TaskCompletedmappers.Both mappers have identical bodies (already noted in the comment that they intentionally share a schema). Extract a shared function to avoid future drift between the two.
♻️ Proposed refactor
+ // TaskCreated/TaskCompleted share a schema so the backend can compute task + // lifetime by subtracting timestamps on matching task_id. + ... - // TaskCreated/TaskCompleted share a schema so the backend can compute task - // lifetime by subtracting timestamps on matching task_id. - TaskCreated: (input) => ({ - task_id: input.task_id, - task_subject: input.task_subject, - task_description: input.task_description, - teammate_name: input.teammate_name, - team_name: input.team_name, - }), - - TaskCompleted: (input) => ({ - task_id: input.task_id, - task_subject: input.task_subject, - task_description: input.task_description, - teammate_name: input.teammate_name, - team_name: input.team_name, - }), + TaskCreated: taskLifecycleMapper, + TaskCompleted: taskLifecycleMapper,Define once near the top of the exports object (or above it):
const taskLifecycleMapper = (input) => ({ task_id: input.task_id, task_subject: input.task_subject, task_description: input.task_description, teammate_name: input.teammate_name, team_name: input.team_name, });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@skillmeter/scripts/lib/hook-registry.js` around lines 106 - 120, TaskCreated and TaskCompleted currently duplicate the same mapping logic in the hook registry, so extract a shared mapper and reuse it for both entries. Add a single helper such as taskLifecycleMapper near the exports object in hook-registry.js, then have both TaskCreated and TaskCompleted point to it so the shared schema lives in one place and won’t drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@skillmeter/scripts/hook.js`:
- Line 19: The runHook failure path is swallowing the rejection, so the hook
exits without any diagnostic context. Update the runHook(event, buildData)
promise handling in hook.js to catch the error, report it through the same
descriptive logging approach used in runHook/logger.js failure paths, and then
exit with a nonzero status so the original failure message is preserved instead
of being discarded.
- Around line 12-17: The hook lookup in registry[event] is vulnerable to
inherited Object.prototype members being treated as valid handlers, so harden
the event dispatch in hook.js by checking that the selected key is an own
property of registry before using it. Update the logic around event and
buildData to reject prototype-inherited names like constructor or toString,
keeping the existing error path for invalid events and preserving the intended
per-event mapper behavior.
In `@skillmeter/scripts/lib/hook-registry.js`:
- Around line 106-120: TaskCreated and TaskCompleted currently duplicate the
same mapping logic in the hook registry, so extract a shared mapper and reuse it
for both entries. Add a single helper such as taskLifecycleMapper near the
exports object in hook-registry.js, then have both TaskCreated and TaskCompleted
point to it so the shared schema lives in one place and won’t drift.
In `@skillmeter/test/lib.test.js`:
- Around line 122-130: Move the inline require("path") used in the test’s
ctx.getTranscriptId helper to the top-level require section of the file so the
CommonJS imports are consistent. Update the test body to reference the hoisted
path symbol in the registry.SubagentStop and ctx setup, keeping the existing
assertions unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 992eedf6-781e-41c7-a55d-527c306430b1
📒 Files selected for processing (26)
skillmeter/.claude-plugin/plugin.jsonskillmeter/README.mdskillmeter/hooks/hooks.jsonskillmeter/scripts/config_change.jsskillmeter/scripts/hook.jsskillmeter/scripts/instructions_loaded.jsskillmeter/scripts/lib/hook-registry.jsskillmeter/scripts/notification.jsskillmeter/scripts/permission_denied.jsskillmeter/scripts/permission_request.jsskillmeter/scripts/post_compact.jsskillmeter/scripts/post_tool_batch.jsskillmeter/scripts/post_tool_use.jsskillmeter/scripts/post_tool_use_failure.jsskillmeter/scripts/pre_compact.jsskillmeter/scripts/pre_tool_use.jsskillmeter/scripts/stop_failure.jsskillmeter/scripts/subagent_start.jsskillmeter/scripts/subagent_stop.jsskillmeter/scripts/task_completed.jsskillmeter/scripts/task_created.jsskillmeter/scripts/teammate_idle.jsskillmeter/scripts/user_prompt_submit.jsskillmeter/scripts/worktree_create.jsskillmeter/scripts/worktree_remove.jsskillmeter/test/lib.test.js
💤 Files with no reviewable changes (20)
- skillmeter/scripts/pre_tool_use.js
- skillmeter/scripts/teammate_idle.js
- skillmeter/scripts/post_tool_use.js
- skillmeter/scripts/instructions_loaded.js
- skillmeter/scripts/user_prompt_submit.js
- skillmeter/scripts/config_change.js
- skillmeter/scripts/worktree_remove.js
- skillmeter/scripts/permission_denied.js
- skillmeter/scripts/subagent_stop.js
- skillmeter/scripts/post_tool_batch.js
- skillmeter/scripts/stop_failure.js
- skillmeter/scripts/task_created.js
- skillmeter/scripts/worktree_create.js
- skillmeter/scripts/subagent_start.js
- skillmeter/scripts/permission_request.js
- skillmeter/scripts/task_completed.js
- skillmeter/scripts/notification.js
- skillmeter/scripts/post_compact.js
- skillmeter/scripts/pre_compact.js
- skillmeter/scripts/post_tool_use_failure.js
Version bump for the data-driven hook dispatcher refactor. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KoEUHYQTz1Tx61FcteE979
896f81f to
a838bbb
Compare
Follow-up to #91. A design-pattern refinement grounded in the current Claude Code plugin docs, plus a version bump.
Commits
1.
refactor: collapse ~20 thin hook scripts into a data-driven dispatcherMost hooks were 6–13 line files that only picked a few fields off the input and called
runHook. They're replaced by a single generic entrypoint (scripts/hook.js <EventName>) plus a field-mapper table (lib/hook-registry.js);hooks.jsonroutes observation-only events through it.(input, ctx)buildDatacontract, so ctx-using hooks (e.g.SubagentStop'sgetTranscriptId) port unchanged.runHookoptions or custom logic keep dedicated entrypoints:session_start,session_end,stop,on_signin_result,user_prompt_expansion_signin.hook.jsexits non-zero on an unknown event; a test locks the registry ↔ hooks.json contract.2.
chore: bump version to 0.22.0Note on
defaultEnabledAn earlier revision of this PR set
defaultEnabled: false. It was reverted: telemetry already requires a valid license JWT for all egress (both upload paths intransfer.jsskip when the token is missing/expired), so nothing leaves the machine until the user explicitly signs in via GitHub OAuth — a stronger, explicit consent gate than a plugin-enable toggle. Shipping enabled-by-default keeps onboarding frictionless: SessionStart shows the sign-in banner, guiding the user to activate.defaultEnabled: falsewould suppress that banner (the hook wouldn't run) and add a discovery step without adding any real privacy protection.Verification
node --test→ 51/51 pass (new registry↔hooks.json contract test).PreToolUsepath-hashing andSubagentStopctx wiring both work throughhook.js; unknown event exits 1.claude plugin validate skillmeter✔; no dangling references to deleted scripts.🤖 Generated with Claude Code
Summary by CodeRabbit
0.22.0.