Skip to content

refactor: data-driven hook dispatcher (v0.22.0) - #92

Merged
minarc merged 2 commits into
mainfrom
feat/hook-dispatcher-default-disabled
Jul 9, 2026
Merged

minarc merged 2 commits into
mainfrom
feat/hook-dispatcher-default-disabled

Conversation

@minarc

@minarc minarc commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

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 dispatcher
Most 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.json routes observation-only events through it.

  • 20 thin hook files removed; adding an observation-only hook is now a one-line registry entry + one hooks.json line.
  • Mappers keep the (input, ctx) buildData contract, so ctx-using hooks (e.g. SubagentStop's getTranscriptId) port unchanged.
  • Hooks needing runHook options or custom logic keep dedicated entrypoints: session_start, session_end, stop, on_signin_result, user_prompt_expansion_signin.
  • hook.js exits non-zero on an unknown event; a test locks the registry ↔ hooks.json contract.

2. chore: bump version to 0.22.0

Note on defaultEnabled

An earlier revision of this PR set defaultEnabled: false. It was reverted: telemetry already requires a valid license JWT for all egress (both upload paths in transfer.js skip 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: false would 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).
  • Dispatch smoke: PreToolUse path-hashing and SubagentStop ctx wiring both work through hook.js; unknown event exits 1.
  • claude plugin validate skillmeter ✔; no dangling references to deleted scripts.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Consolidated many Git hook handlers to route through a single shared runner for more consistent event processing.
    • Added centralized event-to-payload mapping for a wide set of hook types.
  • Bug Fixes
    • Added stricter validation to prevent missing/unknown hook event mappings and ensure correct payload shaping.
  • Documentation
    • Refreshed project structure documentation for the updated scripts layout.
  • Tests
    • Added regression coverage to verify hook routing matches available handlers and payload mapping expectations.
  • Chores
    • Bumped plugin version to 0.22.0.

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
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The PR centralizes hook execution through scripts/hook.js and scripts/lib/hook-registry.js, rewires hooks.json to use the shared dispatcher, removes the old per-event CLI scripts, updates the README structure notes, adds registry wiring tests, and bumps the plugin version.

Changes

Hook Dispatcher Unification

Layer / File(s) Summary
Hook registry mapper contract
skillmeter/scripts/lib/hook-registry.js
Defines mapper functions for the supported hook events, including tool-use, permission, subagent, task, worktree, compaction, config, and instruction events.
Shared dispatcher and hook routing
skillmeter/scripts/hook.js, skillmeter/hooks/hooks.json
Adds a generic hook entrypoint and updates hook commands to invoke it with an event name instead of per-event scripts.
Removal of dedicated per-event scripts
skillmeter/scripts/*.js
Deletes the old standalone hook CLI scripts that were replaced by the shared dispatcher and registry.
Tests, docs, and version bump
skillmeter/README.md, skillmeter/test/lib.test.js, skillmeter/.claude-plugin/plugin.json
Updates project-structure docs, adds registry/dispatch contract tests, and bumps the plugin manifest version.

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
Loading

Possibly related PRs

Suggested reviewers: jhunlee-dev

Poem

A bunny bounded through the script-filled grove,
Then found one dispatcher to gently strove.
The registry mapped each hop and squeak,
Old scripts went poof—just one command to seek.
With tests in place and version neat,
This burrow feels tidy, swift, and sweet.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main refactor to a data-driven hook dispatcher and includes the version bump.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/hook-dispatcher-default-disabled

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (4)
skillmeter/test/lib.test.js (1)

122-130: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: prefer a top-level require("path") instead of an inline import.

Line 124 requires path inline 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 win

Swallowed rejection hides failure context.

.catch(() => process.exit(1)) discards the error, so any runHook failure surfaces only as a bare exit code with no message — harder to diagnose in the field compared to the descriptive console.error used elsewhere in runHook/logger.js failure 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 win

Guard against prototype-inherited registry keys.

registry[event] on a plain object literal can resolve inherited Object.prototype members (constructor, toString, valueOf, hasOwnProperty) which are functions, so the typeof buildData !== "function" check won't catch them. If event is ever one of those names (manual invocation, future config typo/misconfiguration), e.g. constructor would run as Object(input, ctx), returning the raw, unfiltered input object as eventData — bypassing the whole point of the per-event field minimization the registry mappers exist for.

Currently unreachable given today's hooks.json wiring, 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 win

Dedupe TaskCreated/TaskCompleted mappers.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e3ef6b and 896f81f.

📒 Files selected for processing (26)
  • skillmeter/.claude-plugin/plugin.json
  • skillmeter/README.md
  • skillmeter/hooks/hooks.json
  • skillmeter/scripts/config_change.js
  • skillmeter/scripts/hook.js
  • skillmeter/scripts/instructions_loaded.js
  • skillmeter/scripts/lib/hook-registry.js
  • skillmeter/scripts/notification.js
  • skillmeter/scripts/permission_denied.js
  • skillmeter/scripts/permission_request.js
  • skillmeter/scripts/post_compact.js
  • skillmeter/scripts/post_tool_batch.js
  • skillmeter/scripts/post_tool_use.js
  • skillmeter/scripts/post_tool_use_failure.js
  • skillmeter/scripts/pre_compact.js
  • skillmeter/scripts/pre_tool_use.js
  • skillmeter/scripts/stop_failure.js
  • skillmeter/scripts/subagent_start.js
  • skillmeter/scripts/subagent_stop.js
  • skillmeter/scripts/task_completed.js
  • skillmeter/scripts/task_created.js
  • skillmeter/scripts/teammate_idle.js
  • skillmeter/scripts/user_prompt_submit.js
  • skillmeter/scripts/worktree_create.js
  • skillmeter/scripts/worktree_remove.js
  • skillmeter/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
@minarc
minarc force-pushed the feat/hook-dispatcher-default-disabled branch from 896f81f to a838bbb Compare July 9, 2026 07:01
@minarc minarc changed the title refactor: data-driven hook dispatcher + ship disabled by default (v0.22.0) refactor: data-driven hook dispatcher (v0.22.0) Jul 9, 2026
@minarc
minarc requested a review from TheStarkor July 9, 2026 07:08
@minarc
minarc merged commit d11b605 into main Jul 9, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants