Commit 11fcb07f authored by Jude Gao's avatar Jude Gao

[Plugin] next-dev: switch to plugin-level hooks + add test server

- Move hooks from SKILL.md frontmatter to hooks/hooks.json. Skill-scoped
  hooks are not reliably supported by Claude Code (anthropics/claude-code#17688);
  the plugin-level hooks gate on .claude/port for the same activation semantics.
- Self-disable when the dev server is unreachable: hooks delete .claude/port
  so a stale port file from a previous session doesn't burn the timeout
  every turn.
- Make dismiss-errors.mjs an unconditional escape hatch (drops the
  node_modules/turbopack-stub heuristics).
- Add a fake MCP server (test/start-test-server.mjs) plus testing guide for
  exercising the full hook flow without a real Next.js dev server.
- Drive-by: fix marketplace source paths for both next-dev and cache-components
  to include the .claude-plugin/ prefix so they actually resolve.
parent ba856927
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
"plugins": [ "plugins": [
{ {
"name": "cache-components", "name": "cache-components",
"source": "./plugins/cache-components", "source": "./.claude-plugin/plugins/cache-components",
"description": "Expert guidance for Next.js Cache Components and Partial Prerendering (PPR). Proactively activates in projects with cacheComponents enabled.", "description": "Expert guidance for Next.js Cache Components and Partial Prerendering (PPR). Proactively activates in projects with cacheComponents enabled.",
"version": "1.0.0", "version": "1.0.0",
"author": { "author": {
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
}, },
{ {
"name": "next-dev", "name": "next-dev",
"source": "./plugins/next-dev", "source": "./.claude-plugin/plugins/next-dev",
"description": "Experimental: real-time Turbopack compilation feedback for agents. Pauses compilation during edits, batches one compile at turn-end, blocks on errors. Requires unreleased MCP tools (pause_compilation/compile_and_resume/get_compilation_issues).", "description": "Experimental: real-time Turbopack compilation feedback for agents. Pauses compilation during edits, batches one compile at turn-end, blocks on errors. Requires unreleased MCP tools (pause_compilation/compile_and_resume/get_compilation_issues).",
"version": "0.1.0", "version": "0.1.0",
"author": { "author": {
......
...@@ -65,20 +65,20 @@ If activation fails, the port file is deleted and the hooks become silent no-ops ...@@ -65,20 +65,20 @@ If activation fails, the port file is deleted and the hooks become silent no-ops
## Architecture ## Architecture
Two skill-scoped hooks fire while the skill is active: Hooks are declared at **plugin level** in `hooks/hooks.json`, not in the SKILL.md frontmatter. Skill-scoped hooks are not currently supported by Claude Code (see [anthropics/claude-code#17688](https://github.com/anthropics/claude-code/issues/17688)). To get the same effect, both hooks gate on `.claude/port` and silently no-op when it's missing — so they only do real work after `/next-dev` activation has written the port file.
- **`UserPromptSubmit`** → `hooks/enter-manual-compile.mjs` - **`UserPromptSubmit`** → `hooks/enter-manual-compile.mjs`
Pings the dev server, then calls `pause_compilation`. Silent no-op if the port file is missing or the server is unreachable. Pings the dev server, then calls `pause_compilation`. Silent no-op if the port file is missing or the server is unreachable.
- **`Stop`** → `hooks/stop-compile-check.mjs` - **`Stop`** → `hooks/stop-compile-check.mjs`
Calls `compile_and_resume` (drains pending tasks in one batch), then `get_compilation_issues`. If issues are found, returns `decision: block` with the formatted errors. If `stop_hook_active` is `true`, exits 0 unconditionally to avoid infinite loops. Calls `compile_and_resume` (drains pending tasks in one batch), then `get_compilation_issues`. If issues are found, returns `decision: block` with the formatted errors. The hook does not short-circuit on `stop_hook_active`: if the agent can't fix an issue, it can dismiss everything currently reported via `dismiss-errors.mjs` and stop cleanly — the block message itself surfaces that command.
State files are project-local (`$CLAUDE_PROJECT_DIR/.claude/`): State files are project-local (`$CLAUDE_PROJECT_DIR/.claude/`):
- `.claude/port` — dev server port; existence is the activation flag - `.claude/port` — dev server port; existence is the activation flag and the gate for plugin hooks
- `.claude/dismissed-issues.json` — issue keys the agent has dismissed as non-actionable - `.claude/dismissed-issues.json` — issue keys the agent has dismissed
Hook scripts are plugin-local (`${CLAUDE_PLUGIN_ROOT}/hooks/`). Hook scripts live under `${CLAUDE_PLUGIN_ROOT}/hooks/` (referenced from `hooks/hooks.json`). Skill scripts live under `${CLAUDE_SKILL_DIR}/scripts/` (referenced from the skill body and from commands the hooks tell the agent to run).
## Files ## Files
...@@ -105,7 +105,7 @@ Hook scripts are plugin-local (`${CLAUDE_PLUGIN_ROOT}/hooks/`). ...@@ -105,7 +105,7 @@ Hook scripts are plugin-local (`${CLAUDE_PLUGIN_ROOT}/hooks/`).
Large projects often have compilation errors the agent can't fix — `node_modules` resolving server-only builtins (`child_process`, `dns`, `net`, `tls`) in client context, Turbopack empty-module stubs, etc. The agent can dismiss these: Large projects often have compilation errors the agent can't fix — `node_modules` resolving server-only builtins (`child_process`, `dns`, `net`, `tls`) in client context, Turbopack empty-module stubs, etc. The agent can dismiss these:
```bash ```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" node "${CLAUDE_SKILL_DIR}/scripts/dismiss-errors.mjs"
``` ```
Dismissals are keyed by `severity|filePath|title|startLine:startCol` (matches the server-side dedup key) and persist in `.claude/dismissed-issues.json` for the rest of the session. Activation clears them on the next session. Dismissals are keyed by `severity|filePath|title|startLine:startCol` (matches the server-side dedup key) and persist in `.claude/dismissed-issues.json` for the rest of the session. Activation clears them on the next session.
......
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* UserPromptSubmit hook (skill-scoped). At the start of each agent turn: * UserPromptSubmit hook (plugin-level, gated on .claude/port).
* At the start of each agent turn:
* 1. Checks the dev server is reachable (precondition gate) * 1. Checks the dev server is reachable (precondition gate)
* 2. Pauses compilation so intermediate edits don't trigger HMR * 2. Pauses compilation so intermediate edits don't trigger HMR
* *
* Silent no-op if the port file is missing or the server is unreachable. * ─────────────────────────────────────────────────────────────────────────
* If the server goes down mid-session, the agent simply loses compilation * Why we silently skip when the port file is missing
* feedback for that turn — the Stop hook exits 0 gracefully. * ─────────────────────────────────────────────────────────────────────────
* The port file is written by activate.mjs only after it verifies that the
* dev server exposes the required MCP tools. If the file is missing, one of
* these is true:
*
* (a) The user never ran `/next-dev <port>`. Nothing to do.
* (b) Activation ran but failed because the running Next.js version is too
* old to expose the required MCP tools (`get_compilation_issues`,
* `pause_compilation`, `compile_and_resume`). activate.mjs already
* printed a clear error at that point; re-surfacing it on every prompt
* would be noise.
*
* In either case the correct behaviour is a silent exit — we must not block
* the user's turn just because the skill isn't functional.
*
* ─────────────────────────────────────────────────────────────────────────
* The Webpack edge case (port file present, but hooks are no-ops)
* ─────────────────────────────────────────────────────────────────────────
* The MCP tools are registered unconditionally, but they only do real work
* when the dev server is running Turbopack. If the user ran `next dev
* --webpack`, activation still succeeds (the tools exist), so this hook
* runs. `pause_compilation` becomes a no-op, `get_compilation_issues`
* returns nothing, and the whole skill degrades silently to doing nothing.
* That's an acceptable failure mode — webpack users just don't get the
* compilation-feedback loop, and nothing is broken. We do not try to
* detect webpack here; the documentation (README + PR) calls out the
* Turbopack requirement explicitly.
* ─────────────────────────────────────────────────────────────────────────
*/ */
import { existsSync } from 'node:fs' import { existsSync, unlinkSync } from 'node:fs'
import { join } from 'node:path' import { join } from 'node:path'
import { getPort, ping, pauseCompilation } from './mcp-client.mjs' import { getPort, ping, pauseCompilation } from './mcp-client.mjs'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd() // CLAUDE_PROJECT_DIR is guaranteed to be set in hook subprocesses.
const portFile = join(projectDir, '.claude', 'port') // https://code.claude.com/docs/en/hooks#reference-scripts-by-path
const portFile = join(process.env.CLAUDE_PROJECT_DIR, '.claude', 'port')
if (!existsSync(portFile)) { if (!existsSync(portFile)) {
process.exit(0) process.exit(0)
} }
// Self-disable if the dev server is gone. The port file persists across
// sessions, but the dev server may not — without this, every turn would
// burn the hook's full timeout trying to reach a dead port. Deleting the
// port file makes subsequent turns instant no-ops; the user re-runs
// `/next-dev <port>` when they bring the server back up.
function selfDisable() {
try {
unlinkSync(portFile)
} catch {}
}
try { try {
const port = getPort() const port = getPort()
const reachable = await ping(port) const reachable = await ping(port)
if (!reachable) { if (!reachable) {
selfDisable()
process.exit(0) process.exit(0)
} }
await pauseCompilation(port) await pauseCompilation(port)
} catch { } catch {
// Server unreachable — silent no-op. Stop hook handles gracefully. selfDisable()
} }
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/enter-manual-compile.mjs\"",
"timeout": 10
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop-compile-check.mjs\"",
"timeout": 120
}
]
}
]
}
}
...@@ -6,7 +6,9 @@ ...@@ -6,7 +6,9 @@
import { readFileSync, writeFileSync, existsSync } from 'node:fs' import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { join } from 'node:path' import { join } from 'node:path'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd() // CLAUDE_PROJECT_DIR is guaranteed to be set in hook subprocesses.
// https://code.claude.com/docs/en/hooks#reference-scripts-by-path
const projectDir = process.env.CLAUDE_PROJECT_DIR
const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json') const dismissedFile = join(projectDir, '.claude', 'dismissed-issues.json')
export function getPort() { export function getPort() {
......
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Stop hook (skill-scoped). Runs a compilation pass, then blocks if there * Stop hook (plugin-level, gated on .claude/port).
* are compilation errors. The agent must fix them or dismiss them to proceed. * Runs a compilation pass, then blocks if there are compilation errors.
* The agent must fix them or dismiss them to proceed.
*
* ─────────────────────────────────────────────────────────────────────────
* Why we silently skip when the port file is missing
* ─────────────────────────────────────────────────────────────────────────
* Mirrors enter-manual-compile.mjs. No port file → either the skill was
* never activated, or activation failed because the Next.js version is too
* old to expose the required MCP tools. Blocking a stop on a non-functional
* skill would trap the agent with no way forward, so we exit 0.
*
* ─────────────────────────────────────────────────────────────────────────
* The Webpack edge case (port file present, but hooks are no-ops)
* ─────────────────────────────────────────────────────────────────────────
* If the dev server is running `next dev --webpack`, the MCP tools exist
* but do nothing: `compile_and_resume` is a no-op and `get_compilation_issues`
* returns an empty list. This hook will then exit 0 every time, which is
* the correct degradation — webpack users just lose the feedback loop.
* See enter-manual-compile.mjs for the full rationale.
*
* ─────────────────────────────────────────────────────────────────────────
* Why we do NOT short-circuit on `stop_hook_active`
* ─────────────────────────────────────────────────────────────────────────
* Repeated blocks are fine: the agent can always dismiss non-actionable
* issues via dismiss-errors.mjs and stop cleanly. The block message itself
* surfaces that escape hatch.
* ─────────────────────────────────────────────────────────────────────────
*/ */
import { existsSync } from 'node:fs' import { existsSync, unlinkSync } from 'node:fs'
import { join } from 'node:path' import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { import {
getPort, getPort,
ping,
getCompilationIssues, getCompilationIssues,
compileAndResume, compileAndResume,
filterDismissedIssues, filterDismissedIssues,
} from './mcp-client.mjs' } from './mcp-client.mjs'
const projectDir = process.env.CLAUDE_PROJECT_DIR || process.cwd() // CLAUDE_PROJECT_DIR is guaranteed to be set in hook subprocesses.
const portFile = join(projectDir, '.claude', 'port') // https://code.claude.com/docs/en/hooks#reference-scripts-by-path
const portFile = join(process.env.CLAUDE_PROJECT_DIR, '.claude', 'port')
// Resolve the dismiss-errors script to an absolute path at hook time.
// We can't print `${CLAUDE_SKILL_DIR}/...` in the block message because
// that's a skill-load-time template substitution, not a runtime env var —
// the agent's Bash tool invocation wouldn't expand it. Computing from
// import.meta.url is also self-contained (no reliance on CLAUDE_PLUGIN_ROOT
// being set in the agent's Bash subprocess).
const hookDir = dirname(fileURLToPath(import.meta.url))
const dismissScript = resolve(
hookDir,
'..',
'skills',
'next-dev',
'scripts',
'dismiss-errors.mjs'
)
// No port file = setup didn't complete or skill not fully active.
if (!existsSync(portFile)) { if (!existsSync(portFile)) {
process.exit(0) process.exit(0)
} }
// Self-disable if the dev server is gone. The port file persists across
// sessions but the dev server may not — see enter-manual-compile.mjs for
// the full rationale.
function selfDisable() {
try {
unlinkSync(portFile)
} catch {}
}
try { try {
const port = getPort() const port = getPort()
if (!(await ping(port))) {
selfDisable()
process.exit(0)
}
// Run a compilation pass before checking for errors. // Run a compilation pass before checking for errors.
// This processes all accumulated file changes in one batch. // This processes all accumulated file changes in one batch.
try { try {
...@@ -73,7 +131,9 @@ try { ...@@ -73,7 +131,9 @@ try {
} }
lines.push( lines.push(
`${issues.length} issue(s). Fix them or dismiss non-actionable ones with: node "./scripts/dismiss-errors.mjs"` `${issues.length} issue(s). Fix them. If they aren't fixable from your end (third-party code, bundler stubs, false positives), use the escape hatch to dismiss everything currently reported and stop:`,
` node "${dismissScript}"`,
`Dismissed issues stay hidden for the rest of the session.`
) )
const output = { const output = {
...@@ -83,6 +143,7 @@ try { ...@@ -83,6 +143,7 @@ try {
process.stdout.write(JSON.stringify(output)) process.stdout.write(JSON.stringify(output))
process.exit(0) process.exit(0)
} catch (err) { } catch (err) {
// Server unreachable — don't block the agent from stopping. // Server unreachable mid-call — self-disable and don't block the stop.
selfDisable()
process.exit(0) process.exit(0)
} }
...@@ -2,17 +2,6 @@ ...@@ -2,17 +2,6 @@
name: next-dev name: next-dev
description: "Connect to Next.js dev server for real-time compilation feedback on every edit" description: "Connect to Next.js dev server for real-time compilation feedback on every edit"
argument-hint: "[port]" argument-hint: "[port]"
hooks:
UserPromptSubmit:
- hooks:
- type: command
command: 'node "${CLAUDE_PLUGIN_ROOT}/hooks/enter-manual-compile.mjs"'
timeout: 10
Stop:
- hooks:
- type: command
command: 'node "${CLAUDE_PLUGIN_ROOT}/hooks/stop-compile-check.mjs"'
timeout: 120
--- ---
# Next Dev # Next Dev
...@@ -24,7 +13,7 @@ Connects to the Next.js dev server MCP endpoint for compilation feedback. ...@@ -24,7 +13,7 @@ Connects to the Next.js dev server MCP endpoint for compilation feedback.
## Setup ## Setup
```bash ```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/activate.mjs" $ARGUMENTS node "${CLAUDE_SKILL_DIR}/scripts/activate.mjs" $ARGUMENTS
``` ```
If it fails (non-zero exit), tell the user the error from stderr and offer to retry. Do not edit files until activation succeeds. If it fails (non-zero exit), tell the user the error from stderr and offer to retry. Do not edit files until activation succeeds.
...@@ -35,23 +24,23 @@ If it fails (non-zero exit), tell the user the error from stderr and offer to re ...@@ -35,23 +24,23 @@ If it fails (non-zero exit), tell the user the error from stderr and offer to re
## How it works ## How it works
Two hooks run while this skill is active: Activation writes the port number to `.claude/port`. Two plugin-level hooks gate on that file, so they no-op until `/next-dev` runs and silently re-engage on every session afterwards (no `/reload-plugins` needed):
- **UserPromptSubmit**: Checks the dev server is reachable, then pauses compilation for the turn. If the server is down, silently skips — you lose feedback for that turn but aren't blocked. - **UserPromptSubmit**: Checks the dev server is reachable, then pauses compilation for the turn. If the server is down, silently skips — you lose feedback for that turn but aren't blocked.
- **Stop**: Compiles all pending changes in one batch and exits manual mode (normal HMR resumes). **Blocks you from finishing if there are compilation errors.** Fix them before trying again. - **Stop**: Compiles all pending changes in one batch and exits manual mode (normal HMR resumes). **Blocks you from finishing if there are compilation errors.** Fix them before trying again.
## Noisy / non-actionable errors ## Escape hatch: dismissing errors
If the stop hook blocks you with errors that aren't yours (node_modules, Turbopack stubs, etc.), dismiss them: If the stop hook blocks you with errors you can't fix (third-party code, bundler stubs, false positives) and you'd rather move on, dismiss everything currently reported:
```bash ```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" node "${CLAUDE_SKILL_DIR}/scripts/dismiss-errors.mjs"
``` ```
Hides non-actionable errors from all future checks for the rest of the session. Dismissals reset on next activation. To clear manually: Hides every currently-reported error from future checks for the rest of the session. New errors from later edits will still surface. To clear manually:
```bash ```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" --reset node "${CLAUDE_SKILL_DIR}/scripts/dismiss-errors.mjs" --reset
``` ```
## On-demand error check ## On-demand error check
...@@ -59,7 +48,7 @@ node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" --reset ...@@ -59,7 +48,7 @@ node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/dismiss-errors.mjs" --reset
Check compilation errors mid-task without waiting for the stop hook: Check compilation errors mid-task without waiting for the stop hook:
```bash ```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/next-dev/scripts/get-errors.mjs" node "${CLAUDE_SKILL_DIR}/scripts/get-errors.mjs"
``` ```
Compiles pending changes and returns current errors (respects dismissals). Compiles pending changes and returns current errors (respects dismissals).
...@@ -90,11 +90,20 @@ try { ...@@ -90,11 +90,20 @@ try {
const listBody = parseSSE(await listRes.text()) const listBody = parseSSE(await listRes.text())
const tools = listBody?.result?.tools?.map((t) => t.name) || [] const tools = listBody?.result?.tools?.map((t) => t.name) || []
if (!tools.includes('get_compilation_issues')) { const required = [
'get_compilation_issues',
'pause_compilation',
'compile_and_resume',
]
const missing = required.filter((t) => !tools.includes(t))
if (missing.length > 0) {
fail( fail(
`MCP endpoint is reachable but missing "get_compilation_issues" tool.\n` + `MCP endpoint is reachable but missing required tools: ${missing.join(', ')}.\n` +
`Available tools: ${tools.join(', ')}\n` + `Available tools: ${tools.join(', ')}\n` +
`This requires Turbopack. Start the dev server with: pnpm dev --turbopack` `This skill requires a recent Next.js version that exposes these MCP tools, ` +
`running with Turbopack (the default in recent Next.js). Upgrade to the ` +
`latest Next.js and start the dev server with: pnpm dev`
) )
} }
...@@ -146,6 +155,6 @@ try { ...@@ -146,6 +155,6 @@ try {
} }
fail( fail(
`Cannot reach MCP endpoint at ${url}: ${err.message}\n` + `Cannot reach MCP endpoint at ${url}: ${err.message}\n` +
`Make sure the dev server is running: pnpm dev --turbopack -p ${port}` `Make sure the dev server is running: pnpm dev -p ${port}`
) )
} }
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Classifies compilation errors as actionable or non-actionable and dismisses * Escape hatch: dismisses every currently-reported compilation error so the
* the non-actionable ones. Dismissed errors are filtered from future checks * stop hook stops blocking. Dismissed errors are filtered from future checks
* (stop hook + get-errors) for the rest of the session. * (stop hook + get-errors) for the rest of the session.
* *
* Heuristics for non-actionable: * Use this when the agent can't fix the reported errors (third-party code,
* - File is in node_modules/ (third-party dependency, agent can't fix) * bundler stubs, false positives) and you'd rather move on than fight them.
* - Error references turbopack/empty.js (bundler stub for server-only modules)
* *
* Usage: node dismiss-errors.mjs [port] * Usage: node dismiss-errors.mjs [port]
* --reset Clear all dismissals * --reset Clear all dismissals
...@@ -49,27 +48,6 @@ function issueKey(issue) { ...@@ -49,27 +48,6 @@ function issueKey(issue) {
return `${severity}|${file}|${title}|${line}:${col}` return `${severity}|${file}|${title}|${line}:${col}`
} }
/**
* Classify an issue as non-actionable if the agent can't fix it.
*/
function isNonActionable(issue) {
const file = issue.filePath || ''
const description = issue.description || ''
const detail = issue.detail || ''
const title = issue.title || ''
const text = `${title} ${description} ${detail}`
// Third-party dependency — agent can't edit node_modules
if (file.includes('/node_modules/')) return 'node_modules'
// Turbopack empty module stub — bundler replaces server-only modules with
// an empty shim in client bundles, causing "export not found" errors.
// Not a real code issue; the source file is correct.
if (text.includes('turbopack/empty.js')) return 'turbopack-stub'
return null
}
async function mcpCall(port, id, method, params) { async function mcpCall(port, id, method, params) {
const url = getMcpUrl(port) const url = getMcpUrl(port)
...@@ -145,7 +123,7 @@ try { ...@@ -145,7 +123,7 @@ try {
const allIssues = result.issues || [] const allIssues = result.issues || []
if (allIssues.length === 0) { if (allIssues.length === 0) {
console.log('No compilation errors to classify.') console.log('No compilation errors to dismiss.')
process.exit(0) process.exit(0)
} }
...@@ -158,67 +136,19 @@ try { ...@@ -158,67 +136,19 @@ try {
} }
const dismissedSet = new Set(existingKeys) const dismissedSet = new Set(existingKeys)
const actionable = []
const dismissed = []
for (const issue of allIssues) { for (const issue of allIssues) {
const reason = isNonActionable(issue) dismissedSet.add(issueKey(issue))
if (reason) {
dismissed.push({ issue, reason })
dismissedSet.add(issueKey(issue))
} else {
actionable.push(issue)
}
} }
// Write merged dismissals writeFileSync(
if (dismissedSet.size > 0) { dismissedFile,
writeFileSync( JSON.stringify({ keys: [...dismissedSet] }),
dismissedFile, 'utf8'
JSON.stringify({ keys: [...dismissedSet] }), )
'utf8'
)
}
// Report dismissed
if (dismissed.length > 0) {
const byReason = {}
for (const { reason } of dismissed) {
byReason[reason] = (byReason[reason] || 0) + 1
}
const summary = Object.entries(byReason)
.map(([reason, count]) => `${count} ${reason}`)
.join(', ')
console.log(
`Dismissed ${dismissed.length} non-actionable error(s): ${summary}.`
)
}
// Report actionable
if (actionable.length === 0) {
console.log('No actionable errors remain.')
process.exit(0)
}
console.log(`\n${actionable.length} actionable error(s):\n`)
for (const issue of actionable) {
const severity = issue.severity || 'error'
const file = issue.filePath || 'unknown'
const title = issue.title || 'Unknown error'
let line = `[${severity}] ${file}: ${title}` console.log(
if (issue.description) line += ` — ${issue.description}` `Dismissed ${allIssues.length} error(s). They will be hidden from future checks this session. Run with --reset to clear.`
if (issue.source?.range) { )
const r = issue.source.range
line += ` (line ${r.start?.line ?? '?'}:${r.start?.column ?? '?'})`
}
console.log(line)
if (issue.detail) console.log(issue.detail.trim())
if (issue.codeFrame) console.log(issue.codeFrame)
console.log()
}
} catch (err) { } catch (err) {
console.error(`Cannot reach dev server on port ${port}: ${err.message}`) console.error(`Cannot reach dev server on port ${port}: ${err.message}`)
process.exit(1) process.exit(1)
......
# Local end-to-end testing
This directory has a fake MCP server you can use to exercise the plugin's full
hook flow without spinning up a real Next.js dev server. Useful when iterating
on the plugin itself.
## Run the fake server
```bash
node .claude-plugin/plugins/next-dev/test/start-test-server.mjs 4321
```
It listens on `http://localhost:<port>` and serves the same `/_next/mcp`
JSON-RPC surface that Next.js's real dev server exposes — just enough of it
to make `initialize`, `tools/list`, `pause_compilation`, `compile_and_resume`,
and `get_compilation_issues` work. By default it returns zero compilation
issues.
## Install the plugin from the local marketplace
In a separate Claude Code session, in any working directory:
```
/plugin marketplace add /absolute/path/to/next.js/.claude-plugin
/plugin install next-dev@nextjs
/next-dev 4321
```
> **Note:** point `marketplace add` at the `.claude-plugin/` directory (the
> one that contains `marketplace.json`), not the repo root. Source paths in
> `marketplace.json` resolve relative to whatever path you pass here, so
> pointing at the repo root makes `./plugins/next-dev` resolve to a non-existent
> `<repo>/plugins/next-dev`.
Activation should succeed (the fake server reports the three required tools
as available) and write `.claude/port`. From that point on the plugin's
`UserPromptSubmit` and `Stop` hooks fire on every turn and call into the fake
server.
> **Why plugin-level hooks?** Skill-frontmatter hooks are not currently
> reliably supported by Claude Code (see
> [anthropics/claude-code#17688](https://github.com/anthropics/claude-code/issues/17688)),
> so the hooks live in `hooks/hooks.json` and gate on the existence of
> `.claude/port` instead. Net result is the same: hooks no-op until
> `/next-dev` runs.
## Test the Stop-hook block flow
The fake server has a tiny control surface for injecting fake errors:
```bash
# Make the next Stop hook block
curl -X POST http://localhost:4321/control/issues \
-H 'content-type: application/json' \
-d '[{"severity":"error","filePath":"app/page.tsx","title":"Boom","description":"fake error"}]'
# Let the next Stop hook pass again
curl -X POST http://localhost:4321/control/clear
# Inspect current fake state
curl http://localhost:4321/control/state
```
Drive the plugin in Claude Code, toggle errors on, ask the agent to stop —
you should see the block message with the dismiss instructions.
## Test the dismiss escape hatch
`dismiss-errors.mjs` is an unconditional escape hatch: it dismisses every
currently-reported error so the Stop hook stops blocking. There's no heuristic.
1. Inject any fake error (see above) and ask the agent to stop — Stop hook
blocks.
2. Run the dismiss command from the block message. It dismisses the injected
error and writes `.claude/dismissed-issues.json`.
3. Ask the agent to stop again — Stop hook now passes.
4. Inject a *different* error and try again — it blocks again, because the
dismissal only covers the keys recorded at dismiss time.
5. To clear all dismissals: `node <dismiss-script> --reset`. Dismissals also
reset automatically on the next `/next-dev` activation.
## Test the dev-server-gone self-disable
The plugin self-disables (deletes `.claude/port`) when a hook can't reach the
dev server, so a stale port file from a previous session doesn't burn the
hook timeout on every turn.
1. Activate with `/next-dev 4321`, do a turn — hooks fire.
2. Kill the fake server (Ctrl-C the `start-test-server.mjs` process).
3. Do another turn. The next `UserPromptSubmit` hook will fail its ping and
delete `.claude/port`. Confirm: `ls /Users/judegao/workspace/empty/.claude/port`
should now be gone.
4. Subsequent turns are instant no-ops until the user re-runs `/next-dev`.
## Reload after editing
Hook scripts (`hooks/*.mjs`) are re-read on each invocation, so edits take
effect on the next prompt with no restart. Edits to `hooks/hooks.json`,
`SKILL.md`, or skill scripts require uninstalling and reinstalling the
plugin (or running `/reload-plugins`):
```
/plugin uninstall next-dev@nextjs
/plugin install next-dev@nextjs
```
#!/usr/bin/env node
/**
* Fake Next.js MCP server for end-to-end testing the next-dev plugin
* without spinning up a real Next.js dev server.
*
* Implements just enough of the JSON-RPC over POST /_next/mcp protocol
* to satisfy the plugin's hooks:
* - initialize / notifications/initialized
* - tools/list (returns the three required tool names)
* - tools/call: pause_compilation, compile_and_resume, get_compilation_issues
*
* Also exposes a tiny control surface so you can toggle the fake error
* state mid-session without restarting the server:
*
* # Inject fake errors (forces the Stop hook to block)
* curl -X POST http://localhost:<port>/control/issues \
* -H 'content-type: application/json' \
* -d '[{"severity":"error","filePath":"app/page.tsx","title":"Boom","description":"fake error"}]'
*
* # Clear errors (let the Stop hook pass)
* curl -X POST http://localhost:<port>/control/clear
*
* # Inspect current state
* curl http://localhost:<port>/control/state
*
* Usage:
* node test/start-test-server.mjs [port]
*/
import { createServer } from 'node:http'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const port = parseInt(process.argv[2] || process.env.PORT || '3000', 10)
// .../next.js/.claude-plugin/plugins/next-dev/test → .../next.js/.claude-plugin
// `marketplace add` must point at the directory that *contains* marketplace.json
// (i.e. .claude-plugin/), not the repo root. Source paths in marketplace.json
// resolve relative to whatever path you pass to `marketplace add`.
const marketplaceRoot = resolve(
dirname(fileURLToPath(import.meta.url)),
'..',
'..',
'..'
)
let fakeIssues = []
function sse(payload) {
return `data: ${JSON.stringify(payload)}\n\n`
}
function jsonRpcResult(id, result) {
return { jsonrpc: '2.0', id, result }
}
function toolResult(id, value) {
return jsonRpcResult(id, {
content: [{ type: 'text', text: JSON.stringify(value) }],
})
}
function readBody(req) {
return new Promise((resolve, reject) => {
let buf = ''
req.on('data', (chunk) => {
buf += chunk
})
req.on('end', () => resolve(buf))
req.on('error', reject)
})
}
const server = createServer(async (req, res) => {
try {
// Control surface — not part of the MCP protocol, just for tests.
if (req.method === 'POST' && req.url === '/control/issues') {
fakeIssues = JSON.parse(await readBody(req))
console.log(`[control] set ${fakeIssues.length} fake issue(s)`)
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ ok: true, count: fakeIssues.length }))
return
}
if (req.method === 'POST' && req.url === '/control/clear') {
fakeIssues = []
console.log('[control] cleared fake issues')
res.writeHead(200, { 'content-type': 'application/json' })
res.end('{"ok":true}')
return
}
if (req.method === 'GET' && req.url === '/control/state') {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ issues: fakeIssues }))
return
}
// MCP endpoint
if (req.method === 'POST' && req.url === '/_next/mcp') {
const raw = await readBody(req)
const msg = JSON.parse(raw)
console.log(
`[mcp] ${msg.method}${msg.params?.name ? ` (${msg.params.name})` : ''}`
)
// Notifications have no id and no response body.
if (msg.method === 'notifications/initialized') {
res.writeHead(202)
res.end()
return
}
let payload
if (msg.method === 'initialize') {
payload = jsonRpcResult(msg.id, {
protocolVersion: '2025-03-26',
capabilities: { tools: {} },
serverInfo: { name: 'fake-next-mcp', version: '0.0.0' },
})
} else if (msg.method === 'tools/list') {
payload = jsonRpcResult(msg.id, {
tools: [
{ name: 'get_compilation_issues', description: 'fake' },
{ name: 'pause_compilation', description: 'fake' },
{ name: 'compile_and_resume', description: 'fake' },
],
})
} else if (msg.method === 'tools/call') {
const name = msg.params?.name
if (name === 'pause_compilation') {
payload = toolResult(msg.id, { paused: true })
} else if (name === 'compile_and_resume') {
payload = toolResult(msg.id, { compiled: true })
} else if (name === 'get_compilation_issues') {
payload = toolResult(msg.id, { issues: fakeIssues })
} else {
payload = {
jsonrpc: '2.0',
id: msg.id,
error: { code: -32601, message: `unknown tool: ${name}` },
}
}
} else {
payload = {
jsonrpc: '2.0',
id: msg.id,
error: { code: -32601, message: `unknown method: ${msg.method}` },
}
}
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
})
res.end(sse(payload))
return
}
res.writeHead(404)
res.end('not found')
} catch (err) {
console.error('[error]', err)
res.writeHead(500)
res.end(err.message)
}
})
server.listen(port, () => {
console.log(`fake next-dev MCP server listening on http://localhost:${port}`)
console.log('')
console.log('In a Claude Code session:')
console.log(` /plugin marketplace add ${marketplaceRoot}`)
console.log(` /plugin install next-dev@nextjs`)
console.log(` /next-dev ${port}`)
console.log('')
console.log('Inject a fake error to test the Stop-hook block flow:')
console.log(
` curl -X POST http://localhost:${port}/control/issues -H 'content-type: application/json' \\`
)
console.log(
` -d '[{"severity":"error","filePath":"app/page.tsx","title":"Boom","description":"fake error"}]'`
)
console.log('')
console.log('Clear errors:')
console.log(` curl -X POST http://localhost:${port}/control/clear`)
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment