Skip to content

fix: replace Claude prompt hook with generated script - #493

Merged
mohanagy merged 1 commit into
nextfrom
fix/windows-claude-hook-script
Jun 3, 2026
Merged

mohanagy merged 1 commit into
nextfrom
fix/windows-claude-hook-script

Conversation

@mohanagy

@mohanagy mohanagy commented Jun 3, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • replace the Claude UserPromptSubmit inline node -e hook with a generated project-local .claude/madar-user-prompt-submit.cjs script
  • keep the prompt applicability logic the same while making the installed shell command short and Windows-safe
  • tighten uninstall and native-agent install verification so the generated script lifecycle is covered

Root cause

The previous minification-only fix was still shipping an installed UserPromptSubmit command around 8,857 characters long. That left it over the practical Windows shell budget, so the command could still be truncated and fail with unexpected EOF while looking for matching a quote.

Verification

  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run
  • npm pack --dry-run

Summary by CodeRabbit

  • Refactor
    • Claude hook installation now generates and manages a local hook script file within the project directory.
    • Enhanced installation verification to validate generated hook script artifacts.
    • Updated hook uninstallation to properly remove generated script files.

Move the Claude UserPromptSubmit hook out of an inline node -e command
and into a generated project-local .claude/madar-user-prompt-submit.cjs
script so Windows shell wrapping cannot truncate the command.

Also tighten Claude uninstall and native-agent install verification to
track the generated hook script lifecycle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR migrates Claude's UserPromptSubmit hook from an inlined base64-encoded Node command to a generated project-local .cjs script file, refactoring the hook generator and updating install/verification logic to work with the new file-based approach.

Changes

Claude prompt applicability hook script migration

Layer / File(s) Summary
Hook script generator refactor
src/runtime/task-applicability.ts
Replaces buildPromptApplicabilityHookCommand(...) with buildPromptApplicabilityHookScript(...) to generate a full JavaScript template that inlines HOOK_CONFIG, regexes, and classification logic, reads stdin JSON, and conditionally outputs payloads based on local-code applicability detection.
Install infrastructure for file-based hooks
src/infrastructure/install.ts
Exports hook script path and command constants, adds writeClaudePromptHookScript(...) to generate the script on disk using the new builder, updates settingsHook configuration to reference the script command, and calls the write helper before updating .claude/settings.json.
Verification of installed hook script
src/infrastructure/compare.ts
Imports hook script path constant, computes script file presence during native-agent install inspection, and adds a new artifact check that requires the generated script to exist whenever UserPromptSubmit hook is configured.
Test coverage for script-based hooks
tests/unit/compare-native-agent.test.ts, tests/unit/install-templates.test.ts, tests/unit/install.test.ts
Updates test helpers to accept project directory and load generated .cjs scripts for payload extraction; adds verification tests for script creation/removal, confirms hook commands reference the scripts, and validates that strict guidance rules are correctly embedded in generated script content.

Sequence Diagram

sequenceDiagram
  participant install as installClaudeHook
  participant write as writeClaudePromptHookScript
  participant build as buildPromptApplicabilityHookScript
  participant fs as File system
  participant settings as .claude/settings.json
  participant verify as inspectClaudeNativeAgentInstall

  install->>write: prepare hook script
  write->>build: generate script template
  build-->>write: JavaScript source string
  write->>fs: write .claude/madar-user-prompt-submit.cjs
  install->>settings: update UserPromptSubmit hook command
  verify->>fs: check if script exists
  verify->>settings: read UserPromptSubmit hook presence
  verify-->>verify: artifact check passes if script exists
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • mohanagy/madar#289: Introduces the prompt applicability gate that the main PR refactors into buildPromptApplicabilityHookScript and integrates into the install/verification workflow.
  • mohanagy/madar#352: Modifies Claude managed-hook detection and verification in compare.ts and install.ts, establishing the same verification patterns that the main PR extends with script artifact checks.
  • mohanagy/madar#491: Modifies the prompt-applicability hook generator in task-applicability.ts to change how Claude hook logic is embedded and generated.

Poem

🐰 A script escapes its shell-bound chains,
From minified base64 strains—
Now written clear upon the disk,
The hook flows free, no encoding risk!
The Claude learns its prompt's true role,
File-based guards protect the whole.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: replacing the Claude prompt hook with a generated script approach.
Description check ✅ Passed The description covers the summary, root cause, and verification steps. All key testing commands are documented, required checklist items are addressed.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/windows-claude-hook-script

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/infrastructure/compare.ts (1)

3163-3192: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate the UserPromptSubmit command, not just the script file.

Line 3164 only tells us that some Madar UserPromptSubmit entry exists. With the current ok: !hasUserPromptSubmitHook || existsSync(promptHookScriptPath) check, a stale or mutated hook command can still pass verification as long as .claude/madar-user-prompt-submit.cjs happens to exist. That makes inspectClaudeNativeAgentInstall() report the file-based migration as verified even when Claude is not actually executing the generated script, which then contaminates compare/benchmark readiness.

Please key this artifact check off the actual UserPromptSubmit command pointing at .claude/madar-user-prompt-submit.cjs, not only hook presence plus file existence.

🤖 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 `@src/infrastructure/compare.ts` around lines 3163 - 3192, The check currently
treats hasUserPromptSubmitHook as a boolean and only verifies file existence;
instead retrieve the actual hook entry (e.g., const userPromptHook =
findHookEntry(settingsPath, 'UserPromptSubmit')) and set the artifact's ok to
validate that either no hook exists or the hook's command/target explicitly
points to CLAUDE_PROMPT_HOOK_SCRIPT_RELATIVE_PATH (or endsWith
'madar-user-prompt-submit.cjs') AND the promptHookScriptPath exists; update the
artifact for CLAUDE_PROMPT_HOOK_SCRIPT_RELATIVE_PATH to use userPromptHook and
inspect its command/path rather than only checking !hasUserPromptSubmitHook ||
existsSync(promptHookScriptPath).
🧹 Nitpick comments (2)
tests/unit/install-templates.test.ts (1)

32-41: 💤 Low value

Consider a more defensive fallback when regex fails to match.

At line 40, if the matchPayload regex doesn't match, the function returns the entire hookScript content. This could lead to false positives in tests if the expected strings appear elsewhere in the script rather than in the extracted payload.

Consider returning an empty string or throwing an error for clarity:

    const hookScript = readFileSync(hookScriptPath, 'utf8')
    const matchPayload = hookScript.match(/const matchPayload = ("(?:\\.|[^"])*")/)
-   return matchPayload?.[1] ? JSON.parse(matchPayload[1]) : hookScript
+   if (!matchPayload?.[1]) {
+     return ''
+   }
+   return JSON.parse(matchPayload[1])

This makes test failures more obvious when the script format changes unexpectedly.

🤖 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 `@tests/unit/install-templates.test.ts` around lines 32 - 41, The current
branch that handles command === 'node .claude/madar-user-prompt-submit.cjs'
returns the full hookScript when the regex matchPayload fails, which can cause
false positives; change the fallback so that if matchPayload?.[1] is falsy you
return an empty string (or throw a clear error) instead of returning hookScript,
i.e. update the logic around matchPayload and the final return to return '' on
no match to make tests fail explicitly and avoid accidental matches.
tests/unit/install.test.ts (1)

647-647: 💤 Low value

Is this package.json necessary for the test?

Line 647 writes a package.json with type: 'module', but the hook script is a .cjs file (CommonJS). Node can execute .cjs files regardless of the package.json type field, and other tests in this file don't create a package.json.

Was this line intended for this test, or is it leftover from an earlier iteration?

🤖 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 `@tests/unit/install.test.ts` at line 647, The test calls
writeFileSync(join(projectDir, 'package.json'), JSON.stringify({ type: 'module'
}), 'utf8') which appears unnecessary for running a .cjs hook; remove that
writeFileSync call (or replace it with an explicit comment) so the test no
longer creates a package.json with "type": "module" unless there's a specific
test assertion that requires it; look for the writeFileSync usage around the
test setup with projectDir and remove or guard it to match other tests that
don't create a package.json.
🤖 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.

Outside diff comments:
In `@src/infrastructure/compare.ts`:
- Around line 3163-3192: The check currently treats hasUserPromptSubmitHook as a
boolean and only verifies file existence; instead retrieve the actual hook entry
(e.g., const userPromptHook = findHookEntry(settingsPath, 'UserPromptSubmit'))
and set the artifact's ok to validate that either no hook exists or the hook's
command/target explicitly points to CLAUDE_PROMPT_HOOK_SCRIPT_RELATIVE_PATH (or
endsWith 'madar-user-prompt-submit.cjs') AND the promptHookScriptPath exists;
update the artifact for CLAUDE_PROMPT_HOOK_SCRIPT_RELATIVE_PATH to use
userPromptHook and inspect its command/path rather than only checking
!hasUserPromptSubmitHook || existsSync(promptHookScriptPath).

---

Nitpick comments:
In `@tests/unit/install-templates.test.ts`:
- Around line 32-41: The current branch that handles command === 'node
.claude/madar-user-prompt-submit.cjs' returns the full hookScript when the regex
matchPayload fails, which can cause false positives; change the fallback so that
if matchPayload?.[1] is falsy you return an empty string (or throw a clear
error) instead of returning hookScript, i.e. update the logic around
matchPayload and the final return to return '' on no match to make tests fail
explicitly and avoid accidental matches.

In `@tests/unit/install.test.ts`:
- Line 647: The test calls writeFileSync(join(projectDir, 'package.json'),
JSON.stringify({ type: 'module' }), 'utf8') which appears unnecessary for
running a .cjs hook; remove that writeFileSync call (or replace it with an
explicit comment) so the test no longer creates a package.json with "type":
"module" unless there's a specific test assertion that requires it; look for the
writeFileSync usage around the test setup with projectDir and remove or guard it
to match other tests that don't create a package.json.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f83f8a4-a32e-4d23-ace4-b2021076810a

📥 Commits

Reviewing files that changed from the base of the PR and between 9f51a3f and d83c68a.

📒 Files selected for processing (6)
  • src/infrastructure/compare.ts
  • src/infrastructure/install.ts
  • src/runtime/task-applicability.ts
  • tests/unit/compare-native-agent.test.ts
  • tests/unit/install-templates.test.ts
  • tests/unit/install.test.ts

@mohanagy
mohanagy merged commit 236e900 into next Jun 3, 2026
7 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 3, 2026
8 tasks
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.

1 participant