diff --git a/README.md b/README.md index e8e8592..e5da0d1 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ facts, so the build fails when a claim stops being true. | `agentic-patterns` | Agentic Patterns in Spring AI: Routing, Orchestrator-Workers, Evaluator-Optimizer and Parallelization | Anthropic's five workflows as plain `ChatClient` code, tested offline with a scripted `ChatModel` that records every prompt, with failure modes and a calls-and-stages cost table | | `mcp-sdk-plain` | Write an MCP Server with the Plain MCP Java SDK (No Spring): stdio and Streamable HTTP | tools, a resource and a resource template on the framework-free SDK, a fat jar over stdio and Streamable HTTP, wire-level transcripts, and a Spring AI client connecting to it | | `koog` | Koog: JetBrains' Kotlin AI Agent Framework on the JVM, Your First Agent with Tools in Java | a tool-calling agent, a strategy graph with a plain-Java node before the model, and the Spring Boot starter, tested against a scripted OpenAI-compatible endpoint, with tool-error, bad-argument, iteration-cap and Kotlin-BOM failure modes | +| `claude-code-spring` | Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ | a Spring Boot 4.2 orders service with a complete committed Claude Code setup: `CLAUDE.md`, a path-scoped rule, two skills, four hooks (command guard, protected files, tests after edit, a Stop gate) run against real hook JSON, project-scoped `.mcp.json` generated by the real `claude mcp` CLI, and tests that lint the setup | ## Versions (verified on Maven Central, 2026-10-11) @@ -37,6 +38,8 @@ facts, so the build fails when a claim stops being true. | Spring Boot / Spring AI (client example) | 4.1.2 / 2.0.2 | `mcp-sdk-plain/examples/spring-ai-client` only, a standalone project | | Koog `koog-agents-jvm` | 1.3.0 | verified on Maven Central 2026-11-11; `koog` module only. `koog-spring-boot-starter` is 1.3.0-beta and brings Spring Boot 3.5.14, which is why this module uses Spring Boot 3.5.16 and not the 4.x of the others | | Kotlin `kotlin-stdlib` | 2.3.10 | the Spring Boot 3.5.16 BOM pins 1.9.25 and would win; the `koog` pom imports the Kotlin BOMs first | +| Spring Boot (`claude-code-spring`) | 4.2.0 | GA 2026-11-19, verified on Maven Central 2026-11-21; `claude-code-spring` only | +| Claude Code CLI | 2.1.330 | `claude mcp` run for `claude-code-spring/output/08`; the model-side behaviour is documented, not executed | | JDK | 25 LTS | | | JUnit | 6.1.3 | | diff --git a/claude-code-spring/.claude/hooks/GuardBash.java b/claude-code-spring/.claude/hooks/GuardBash.java new file mode 100644 index 0000000..d5acc4d --- /dev/null +++ b/claude-code-spring/.claude/hooks/GuardBash.java @@ -0,0 +1,15 @@ +// The same deny rules as guard-bash.sh, written as a JDK 25 compact source file (JEP 512, final in 25). +// Run by the hook as: java ${CLAUDE_PROJECT_DIR}/.claude/hooks/GuardBash.java +// It exists to measure what a JVM hook costs next to bash + jq. It does not parse JSON properly. +void main() throws Exception { + String in = new String(System.in.readAllBytes()); + var m = java.util.regex.Pattern.compile("\"command\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").matcher(in); + String cmd = m.find() ? m.group(1) : ""; + String reason = null; + if (cmd.contains("mvn deploy") || cmd.contains("mvn release:")) reason = "Publishing artifacts is a human decision."; + else if (cmd.contains("git push --force") || cmd.contains("git push -f")) reason = "Force-pushing is blocked in this project."; + else if (cmd.contains("rm -rf")) reason = "rm -rf is blocked."; + if (reason != null) { + System.out.println("{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"" + reason + "\"}}"); + } +} diff --git a/claude-code-spring/.claude/hooks/guard-bash.sh b/claude-code-spring/.claude/hooks/guard-bash.sh new file mode 100755 index 0000000..16fb90c --- /dev/null +++ b/claude-code-spring/.claude/hooks/guard-bash.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# PreToolUse hook for the Bash tool. Reads the hook JSON on stdin (needs jq). +# Denies a few commands by returning a permissionDecision, which Claude sees as the reason. +COMMAND=$(jq -r '.tool_input.command // empty') + +deny() { + jq -n --arg reason "$1" '{ + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: $reason + } + }' + exit 0 +} + +case "$COMMAND" in + *"mvn deploy"*|*"mvn release:"*) deny "Publishing artifacts is a human decision. Run mvn verify instead." ;; + *"git push --force"*|*"git push -f"*) deny "Force-pushing is blocked in this project." ;; + *"rm -rf"*) deny "rm -rf is blocked. Delete specific files instead." ;; + *"| sh"*|*"| bash"*) deny "Piping downloaded text into a shell is blocked." ;; +esac +exit 0 diff --git a/claude-code-spring/.claude/hooks/protect-files.sh b/claude-code-spring/.claude/hooks/protect-files.sh new file mode 100755 index 0000000..3dc35fb --- /dev/null +++ b/claude-code-spring/.claude/hooks/protect-files.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# PreToolUse hook for Edit|Write|MultiEdit. Exit code 2 blocks the call and sends stderr to Claude. +INPUT=$(cat) +TOOL=$(echo "$INPUT" | jq -r '.tool_name // empty') +FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') + +# Production config is never edited by the agent. +case "$FILE" in + *application-prod.*|*/.env|*/.env.*) + echo "Blocked: $FILE is production configuration. Ask the user to change it." >&2 + exit 2 ;; +esac + +# An applied Flyway migration is immutable. Creating a new V file is fine, changing an existing one is not. +case "$FILE" in + */db/migration/V*.sql) + if [ "$TOOL" != "Write" ] || [ -e "$FILE" ]; then + echo "Blocked: $FILE is an existing Flyway migration. Add a new V__*.sql file instead." >&2 + exit 2 + fi ;; +esac +exit 0 diff --git a/claude-code-spring/.claude/hooks/stop-gate.sh b/claude-code-spring/.claude/hooks/stop-gate.sh new file mode 100755 index 0000000..149bc30 --- /dev/null +++ b/claude-code-spring/.claude/hooks/stop-gate.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Stop hook. Refuses to let Claude finish while the full suite is red. +INPUT=$(cat) +if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then + exit 0 # we already pushed Claude back once this turn; let it stop and report +fi + +ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}" +cd "$ROOT" || exit 0 +OUT=$(mvn -B -q test 2>&1) +if [ $? -ne 0 ]; then + SUMMARY=$(echo "$OUT" | awk '/^\[ERROR\] (Failures|Errors):/{p=1} p{print} p&&/^\[ERROR\] Tests run:/{exit}' | head -20) + [ -z "$SUMMARY" ] && SUMMARY=$(echo "$OUT" | grep -E '^\[ERROR\]' | grep -v -E 'Help 1|re-run Maven|For more information|full stack trace|See .*surefire|MojoFailure|^\[ERROR\] *$' | head -8) + [ -z "$SUMMARY" ] && SUMMARY=$(echo "$OUT" | tail -8) + jq -n --arg r "The test suite is red. Fix it before finishing: +$SUMMARY" '{decision: "block", reason: $r}' +fi +exit 0 diff --git a/claude-code-spring/.claude/hooks/test-after-edit.sh b/claude-code-spring/.claude/hooks/test-after-edit.sh new file mode 100755 index 0000000..56c3f7f --- /dev/null +++ b/claude-code-spring/.claude/hooks/test-after-edit.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# PostToolUse hook for Edit|Write|MultiEdit. Runs the test class that matches the edited Java file. +# Green: silent, exit 0. Red: failure lines on stderr and exit 2, which Claude Code shows to Claude. +INPUT=$(cat) +FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') +case "$FILE" in *.java) ;; *) exit 0 ;; esac + +BASE=$(basename "$FILE" .java) +case "$BASE" in + *Test) TESTCLASS="$BASE" ;; + *) TESTCLASS="${BASE}Test" ;; +esac + +ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}" +cd "$ROOT" || exit 0 +if ! find src/test -name "${TESTCLASS}.java" | grep -q .; then + exit 0 # no matching test class: nothing to run +fi + +OUT=$(mvn -B -q test -Dtest="$TESTCLASS" -Dsurefire.failIfNoSpecifiedTests=false 2>&1) +STATUS=$? +if [ $STATUS -ne 0 ]; then + echo "Tests failed after editing $(basename "$FILE") ($TESTCLASS):" >&2 + # Surefire's "Failures:" block carries the assertion messages (expected/actual); prefer it. + FOUND=$(echo "$OUT" | awk '/^\[ERROR\] (Failures|Errors):/{p=1} p{print} p&&/^\[ERROR\] Tests run:/{exit}' | head -20) + [ -z "$FOUND" ] && FOUND=$(echo "$OUT" | grep -E '^\[ERROR\]' | grep -v -E 'Help 1|re-run Maven|For more information|full stack trace|See .*surefire|MojoFailure|^\[ERROR\] *$' | head -15) + if [ -n "$FOUND" ]; then echo "$FOUND" >&2; else echo "$OUT" | tail -15 >&2; fi + exit 2 +fi +exit 0 diff --git a/claude-code-spring/.claude/rules/testing.md b/claude-code-spring/.claude/rules/testing.md new file mode 100644 index 0000000..87a208c --- /dev/null +++ b/claude-code-spring/.claude/rules/testing.md @@ -0,0 +1,10 @@ +--- +paths: + - "src/test/**/*.java" +--- + +# Test rules +- JUnit 6 and AssertJ. Static-import `assertThat`. +- Name tests as sentences: `tenUnitsGetTenPercentOff`, not `testDiscount`. +- Unit-test services without Spring. Use `@SpringBootTest` only for controller wiring. +- One behaviour per test. No logic (loops, ifs) inside a test. diff --git a/claude-code-spring/.claude/settings.json b/claude-code-spring/.claude/settings.json new file mode 100644 index 0000000..fed4835 --- /dev/null +++ b/claude-code-spring/.claude/settings.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "permissions": { + "allow": [ + "Bash(mvn -B -q test *)", + "Bash(mvn -B -q test)", + "Bash(mvn -B verify)", + "Bash(git status)", + "Bash(git diff *)" + ], + "deny": [ + "Read(./.env)", + "Read(./.env.*)", + "Read(./src/main/resources/application-prod.properties)" + ] + }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-bash.sh", "timeout": 10 } + ] + }, + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh", "timeout": 10 } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/test-after-edit.sh", + "timeout": 180, + "statusMessage": "Running the matching test class..." + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-gate.sh", "timeout": 300 } + ] + } + ] + } +} diff --git a/claude-code-spring/.claude/skills/new-endpoint/SKILL.md b/claude-code-spring/.claude/skills/new-endpoint/SKILL.md new file mode 100644 index 0000000..4da434e --- /dev/null +++ b/claude-code-spring/.claude/skills/new-endpoint/SKILL.md @@ -0,0 +1,16 @@ +--- +name: new-endpoint +description: Adds a REST endpoint to the orders service the way this project does it (controller, service, tests). Use when asked to add or extend an endpoint. +argument-hint: "[what the endpoint should do]" +allowed-tools: Bash(mvn *) +--- + +Add an endpoint for: $ARGUMENTS + +Follow these steps in order. + +1. Read `OrderController` and `OrderService` first and copy their style. +2. Put business logic in `OrderService`, a unit test in `OrderServiceTest` first (red), then the code (green). +3. Add the controller method and a MockMvc case in `OrderControllerTest`. +4. Run `mvn -B -q test`. Do not report done until it is green. +5. Reply with the new route, the status codes it returns, and the test names you added. diff --git a/claude-code-spring/.claude/skills/review-diff/SKILL.md b/claude-code-spring/.claude/skills/review-diff/SKILL.md new file mode 100644 index 0000000..d0675aa --- /dev/null +++ b/claude-code-spring/.claude/skills/review-diff/SKILL.md @@ -0,0 +1,18 @@ +--- +name: review-diff +description: Reviews the uncommitted changes for bugs, missing tests and Spring Boot 4 import mistakes. Use before committing. +disable-model-invocation: true +allowed-tools: Bash(git diff *) Bash(git status *) +--- + +## Changes under review + +!`git diff HEAD` + +## What to check +1. Behaviour changes without a matching test. +2. Boot 3 imports that no longer exist in Boot 4 (see CLAUDE.md). +3. `double` used for money, field injection, entities returned from controllers. +4. Edits to files under `db/migration` that already exist. + +Report findings as a list: file, line, problem, suggested fix. If there are none, say so in one line. diff --git a/claude-code-spring/.gitignore b/claude-code-spring/.gitignore new file mode 100644 index 0000000..435b316 --- /dev/null +++ b/claude-code-spring/.gitignore @@ -0,0 +1,5 @@ +target/ +.idea/ +*.iml +CLAUDE.local.md +.claude/settings.local.json diff --git a/claude-code-spring/.mcp.json b/claude-code-spring/.mcp.json new file mode 100644 index 0000000..b83144b --- /dev/null +++ b/claude-code-spring/.mcp.json @@ -0,0 +1,29 @@ +{ + "mcpServers": { + "gitea": { + "type": "stdio", + "command": "gitea-mcp", + "args": [ + "-t", + "stdio" + ], + "env": { + "GITEA_HOST": "https://ankurm.com/git.app", + "GITEA_ACCESS_TOKEN": "${GITEA_TOKEN}" + } + }, + "db": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "@bytebase/dbhub@2.1.0", + "--transport", + "stdio", + "--dsn", + "${DB_URL}" + ], + "env": {} + } + } +} \ No newline at end of file diff --git a/claude-code-spring/CLAUDE.md b/claude-code-spring/CLAUDE.md new file mode 100644 index 0000000..178f39a --- /dev/null +++ b/claude-code-spring/CLAUDE.md @@ -0,0 +1,33 @@ +# Orders service (Spring Boot 4.2, Java 25, Maven) + +REST service for orders. Package root: `com.ankurm.claudecode.orders`. + +## Commands +- Run all tests: `mvn -B -q test` +- Run one test class: `mvn -B -q test -Dtest=OrderServiceTest -Dsurefire.failIfNoSpecifiedTests=false` +- Start the app: `mvn -B spring-boot:run` +- Never run `mvn deploy`, `mvn release:*` or `git push --force`. A hook blocks them. + +## Spring Boot 4 rules (older habits and examples still use the Boot 3 names, so these matter) +- Jackson 3: import `tools.jackson.databind.*`. Do not import `com.fasterxml.jackson.databind.*`. +- MockMvc tests: `@AutoConfigureMockMvc` lives in `org.springframework.boot.webmvc.test.autoconfigure`. + The old `org.springframework.boot.test.autoconfigure.web.servlet` package does not exist in Boot 4. +- Web starter is `spring-boot-starter-webmvc`, test starter is `spring-boot-starter-webmvc-test`. +- Constructor injection only. No field `@Autowired` in `src/main`. + +## Code conventions +- Money is `BigDecimal` with an explicit `RoundingMode`. Never `double`. +- DTOs are records. Entities are not returned from controllers. +- Errors: throw `IllegalArgumentException` for bad input; the controller maps it to 400. + +## Database +- Flyway migrations live in `src/main/resources/db/migration`. An applied migration is immutable: + add `V__description.sql`, never edit an existing file. A hook blocks edits to them. +- `application-prod.properties` is off limits. Ask the user. + +## Definition of done +1. `mvn -B -q test` is green. +2. New behaviour has a test in the matching `*Test` class. +3. Summarise what changed in three lines or fewer. + +See @README.md for how to run the app and the sample requests. diff --git a/claude-code-spring/README.md b/claude-code-spring/README.md new file mode 100644 index 0000000..6b2b4f1 --- /dev/null +++ b/claude-code-spring/README.md @@ -0,0 +1,47 @@ +# claude-code-spring + +Companion code for *Claude Code for Java and Spring Boot Developers: CLAUDE.md, Skills, Hooks, MCP and IntelliJ* +on [ankurm.com](https://ankurm.com). It is a small Spring Boot 4.2 orders service with a complete, committed +Claude Code setup around it, plus the tests and scripts that check that setup. + +Open a terminal **in this folder** and run `claude` there: Claude Code reads `.claude/`, `CLAUDE.md` and +`.mcp.json` from the directory you start it in. + +## Run + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn -B spring-boot:run +curl -s -X POST localhost:8080/orders -H 'Content-Type: application/json' \ + -d '{"customer":"asha","quantity":10,"unitPrice":10.00}' +curl -s localhost:8080/orders/1 +``` + +Ten or more units earn a 10 percent discount, so the first call returns a total of `90.00`. + +## What is where + +| Path | Claude Code feature | +|---|---| +| `CLAUDE.md` | Project instructions loaded every session | +| `.claude/rules/testing.md` | Rule scoped by `paths:` to `src/test/**/*.java` | +| `.claude/skills/new-endpoint/`, `.claude/skills/review-diff/` | Skills (`/new-endpoint`, `/review-diff`) | +| `.claude/settings.json` | Permissions and hook registration (shared with the team) | +| `.claude/hooks/*.sh`, `GuardBash.java` | Hook scripts | +| `.mcp.json` | Project-scoped MCP servers, generated by `claude mcp add --scope project` | + +## Tests and transcripts + +| Command | Writes | +|---|---| +| `mvn -B -q test` | `output/01-config-lint.txt`, `output/02-conventions.txt` | +| `scripts/hook-tour.sh` | `output/03` to `output/06` (the four hooks, fed real hook JSON) | +| `scripts/hook-latency.sh` | `output/07-hook-latency.txt` (indicative, changes every run) | +| `scripts/mcp-tour.sh` | `output/08-mcp-cli.txt` (real `claude mcp` output, in a throwaway directory) | +| `scripts/run-all.sh` | all of the above | + +Claude Code itself is not run here: it needs a signed-in account and a model. The hooks are run with the same +JSON on stdin that the documentation describes, and everything about what Claude Code *does* with a hook's exit +code or JSON comes from its documentation, not from a run. + +Verified with Spring Boot 4.2.0, Claude Code 2.1.330, JDK 25 (Temurin 25.0.5.1), JUnit 6.1.3, `jq` 1.7. diff --git a/claude-code-spring/output/01-config-lint.txt b/claude-code-spring/output/01-config-lint.txt new file mode 100644 index 0000000..3af7356 --- /dev/null +++ b/claude-code-spring/output/01-config-lint.txt @@ -0,0 +1,13 @@ +CLAUDE.md lines: 33 (guidance: under 200) +CLAUDE.md import @README.md exists: true +settings.json hook events: [PreToolUse, PostToolUse, Stop] + PreToolUse matcher=Bash ./.claude/hooks/guard-bash.sh executable=true timeout=10 + PreToolUse matcher=Edit|Write|MultiEdit ./.claude/hooks/protect-files.sh executable=true timeout=10 + PostToolUse matcher=Edit|Write|MultiEdit ./.claude/hooks/test-after-edit.sh executable=true timeout=180 + Stop matcher=(none, matches everything) ./.claude/hooks/stop-gate.sh executable=true timeout=300 +permissions.deny: [Read(./.env), Read(./.env.*), Read(./src/main/resources/application-prod.properties)] +skill new-endpoint: keys=[name, description, argument-hint, allowed-tools] +skill review-diff: keys=[name, description, disable-model-invocation, allowed-tools] +mcp server gitea: type=stdio command=gitea-mcp +mcp server db: type=stdio command=npx +secrets in .mcp.json: false diff --git a/claude-code-spring/output/02-conventions.txt b/claude-code-spring/output/02-conventions.txt new file mode 100644 index 0000000..94507c6 --- /dev/null +++ b/claude-code-spring/output/02-conventions.txt @@ -0,0 +1,2 @@ +java files scanned: 9 +violations: 0 diff --git a/claude-code-spring/output/03-guard-bash.txt b/claude-code-spring/output/03-guard-bash.txt new file mode 100644 index 0000000..d8bf0d8 --- /dev/null +++ b/claude-code-spring/output/03-guard-bash.txt @@ -0,0 +1,32 @@ +# guard-bash.sh: PreToolUse on Bash + +## mvn -B -q test +input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"mvn -B -q test"}} +stdout: (empty) +stderr: (empty) +exit : 0 + +## mvn deploy -DskipTests +input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"mvn deploy -DskipTests"}} +stdout: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Publishing artifacts is a human decision. Run mvn verify instead."}} +stderr: (empty) +exit : 0 + +## git push --force origin main +input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git push --force origin main"}} +stdout: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Force-pushing is blocked in this project."}} +stderr: (empty) +exit : 0 + +## rm -rf target +input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm -rf target"}} +stdout: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"rm -rf is blocked. Delete specific files instead."}} +stderr: (empty) +exit : 0 + +## curl -s https://example.com/install | sh +input : {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"curl -s https://example.com/install | sh"}} +stdout: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Piping downloaded text into a shell is blocked."}} +stderr: (empty) +exit : 0 + diff --git a/claude-code-spring/output/04-protect-files.txt b/claude-code-spring/output/04-protect-files.txt new file mode 100644 index 0000000..f9c71ea --- /dev/null +++ b/claude-code-spring/output/04-protect-files.txt @@ -0,0 +1,32 @@ +# protect-files.sh: PreToolUse on Edit|Write|MultiEdit + +## Edit an ordinary Java file +input : {"hook_event_name":"PreToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/java/com/ankurm/claudecode/orders/OrderService.java"}} +stdout: (empty) +stderr: (empty) +exit : 0 + +## Edit production config +input : {"hook_event_name":"PreToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/resources/application-prod.properties"}} +stdout: (empty) +stderr: Blocked: /src/main/resources/application-prod.properties is production configuration. Ask the user to change it. +exit : 2 + +## Edit an existing migration +input : {"hook_event_name":"PreToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/resources/db/migration/V1__create_orders.sql"}} +stdout: (empty) +stderr: Blocked: /src/main/resources/db/migration/V1__create_orders.sql is an existing Flyway migration. Add a new V__*.sql file instead. +exit : 2 + +## Write over an existing migration +input : {"hook_event_name":"PreToolUse","tool_name":"Write","tool_input":{"file_path":"/src/main/resources/db/migration/V1__create_orders.sql"}} +stdout: (empty) +stderr: Blocked: /src/main/resources/db/migration/V1__create_orders.sql is an existing Flyway migration. Add a new V__*.sql file instead. +exit : 2 + +## Write a new migration +input : {"hook_event_name":"PreToolUse","tool_name":"Write","tool_input":{"file_path":"/src/main/resources/db/migration/V2__add_status.sql"}} +stdout: (empty) +stderr: (empty) +exit : 0 + diff --git a/claude-code-spring/output/05-test-after-edit.txt b/claude-code-spring/output/05-test-after-edit.txt new file mode 100644 index 0000000..3f80fdd --- /dev/null +++ b/claude-code-spring/output/05-test-after-edit.txt @@ -0,0 +1,37 @@ +# test-after-edit.sh: PostToolUse on Edit|Write (run in a throwaway copy) + +## Edited OrderService.java, code is correct +input : {"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/java/com/ankurm/claudecode/orders/OrderService.java"},"tool_response":{"success":true}} +stdout: (empty) +stderr: (empty) +exit : 0 + +## Edited README.md (not Java) +input : {"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"/README.md"},"tool_response":{"success":true}} +stdout: (empty) +stderr: (empty) +exit : 0 + +## Edited OrderService.java after changing >= to > in total() +changed: 40: if (order.quantity() > BULK_THRESHOLD) { +input : {"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/java/com/ankurm/claudecode/orders/OrderService.java"},"tool_response":{"success":true}} +stdout: (empty) +stderr: Tests failed after editing OrderService.java (OrderServiceTest): +stderr: [ERROR] Failures: +stderr: [ERROR] OrderServiceTest.tenUnitsGetTenPercentOff:23 +stderr: expected: 90.00 +stderr: but was: 100.00 +stderr: [ERROR] Tests run: 4, Failures: 1, Errors: 0, Skipped: 0 +exit : 2 + +## Edited OrderService.java into a compile error +input : {"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"/src/main/java/com/ankurm/claudecode/orders/OrderService.java"},"tool_response":{"success":true}} +stdout: (empty) +stderr: Tests failed after editing OrderService.java (OrderServiceTest): +stderr: [ERROR] COMPILATION ERROR : +stderr: [ERROR] /src/main/java/com/ankurm/claudecode/orders/OrderService.java:[39,28] illegal start of expression +stderr: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.14.0:compile (default-compile) on project claude-code-spring: Compilation failure +stderr: [ERROR] /src/main/java/com/ankurm/claudecode/orders/OrderService.java:[39,28] illegal start of expression +stderr: [ERROR] Re-run Maven using the -X switch to enable full debug logging. +exit : 2 + diff --git a/claude-code-spring/output/06-stop-gate.txt b/claude-code-spring/output/06-stop-gate.txt new file mode 100644 index 0000000..3863bfa --- /dev/null +++ b/claude-code-spring/output/06-stop-gate.txt @@ -0,0 +1,20 @@ +# stop-gate.sh: Stop (run in a throwaway copy) + +## Suite green, stop_hook_active=false +input : {"hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"Done."} +stdout: (empty) +stderr: (empty) +exit : 0 + +## Suite red (>= changed to >), stop_hook_active=false +input : {"hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"Done."} +stdout: {"decision":"block","reason":"The test suite is red. Fix it before finishing:\n[ERROR] Failures: \n[ERROR] OrderControllerTest.createThenFetch:27 JSON path \"$.total\" expected:<90.0> but was:<100.0>\n[ERROR] OrderServiceTest.tenUnitsGetTenPercentOff:23 \nexpected: 90.00\n but was: 100.00\n[ERROR] Tests run: 9, Failures: 2, Errors: 0, Skipped: 0"} +stderr: (empty) +exit : 0 + +## Suite still red, stop_hook_active=true (Claude was already pushed back once) +input : {"hook_event_name":"Stop","stop_hook_active":true,"last_assistant_message":"Done."} +stdout: (empty) +stderr: (empty) +exit : 0 + diff --git a/claude-code-spring/output/07-hook-latency.txt b/claude-code-spring/output/07-hook-latency.txt new file mode 100644 index 0000000..bd4bc17 --- /dev/null +++ b/claude-code-spring/output/07-hook-latency.txt @@ -0,0 +1,8 @@ +java: openjdk version "25.0.5.1" 2026-11-17 LTS +jq : jq-1.7 +guard-bash.sh (bash + jq) 7 ms per call (average of 20) +java GuardBash.java (source launcher) 608 ms per call (average of 20) + +both produce the same decision: +deny +deny diff --git a/claude-code-spring/output/08-mcp-cli.txt b/claude-code-spring/output/08-mcp-cli.txt new file mode 100644 index 0000000..59cbd94 --- /dev/null +++ b/claude-code-spring/output/08-mcp-cli.txt @@ -0,0 +1,86 @@ +claude --version: 2.1.330 (Claude Code) + +$ claude mcp add --scope project --transport stdio gitea --env GITEA_HOST=https://ankurm.com/git.app --env GITEA_ACCESS_TOKEN=${GITEA_TOKEN} -- gitea-mcp -t stdio +Added stdio MCP server gitea with command: gitea-mcp -t stdio to project config +File modified: /project/.mcp.json + +$ claude mcp add --scope project --transport stdio db -- npx -y @bytebase/dbhub@2.1.0 --transport stdio --dsn ${DB_URL} +Added stdio MCP server db with command: npx -y @bytebase/dbhub@2.1.0 --transport stdio --dsn ${DB_URL} to project config +File modified: /project/.mcp.json + +$ cat .mcp.json +{ + "mcpServers": { + "gitea": { + "type": "stdio", + "command": "gitea-mcp", + "args": [ + "-t", + "stdio" + ], + "env": { + "GITEA_HOST": "https://ankurm.com/git.app", + "GITEA_ACCESS_TOKEN": "${GITEA_TOKEN}" + } + }, + "db": { + "type": "stdio", + "command": "npx", + "args": [ + "-y", + "@bytebase/dbhub@2.1.0", + "--transport", + "stdio", + "--dsn", + "${DB_URL}" + ], + "env": {} + } + } +} + +committed .mcp.json identical to the generated one: yes + +$ claude mcp list (GITEA_TOKEN and DB_URL unset) +Checking MCP server health… +gitea: gitea-mcp -t stdio - ⏸ Pending approval (run `claude` to approve) +db: npx -y @bytebase/dbhub@2.1.0 --transport stdio --dsn ${DB_URL} - ⏸ Pending approval (run `claude` to approve) +MCP config diagnostics ‼ +For help configuring MCP servers, see: https://code.claude.com/docs/en/mcp +[Has warnings] Project config (shared via .mcp.json) +Location: /project/.mcp.json + ├ [Warning] [gitea] mcpServers.gitea: Missing environment variables: GITEA_TOKEN + └ [Warning] [db] mcpServers.db: Missing environment variables: DB_URL + +$ claude mcp get gitea +gitea: + Scope: Project config (shared via .mcp.json) + Status: ⏸ Pending approval (run `claude` to approve) + Type: stdio + Command: gitea-mcp + Args: -t stdio + Environment: + GITEA_HOST=https://ankurm.com/git.app + GITEA_ACCESS_TOKEN=${GITEA_TOKEN} +To remove this server, run: claude mcp remove gitea -s project + +$ GITEA_TOKEN=x DB_URL=x claude mcp list +Checking MCP server health… +gitea: gitea-mcp -t stdio - ⏸ Pending approval (run `claude` to approve) +db: npx -y @bytebase/dbhub@2.1.0 --transport stdio --dsn ${DB_URL} - ⏸ Pending approval (run `claude` to approve) + +--- a hand-written entry that has a url but no "type" +$ claude mcp list +No MCP servers configured. Use `claude mcp add` to add a server. +MCP config diagnostics ‼ +For help configuring MCP servers, see: https://code.claude.com/docs/en/mcp +[Has warnings] Project config (shared via .mcp.json) +Location: /bad/.mcp.json + └ [Warning] [remote] mcpServers.remote: Skipped — MCP server "remote" has a "url" but no "type"; add "type": "http" (or "sse" / "ws") to this entry + +--- scope precedence: the same server name in user and local scope +Added HTTP MCP server docs with URL: https://user-scope.invalid/mcp to user config +Added HTTP MCP server docs with URL: https://local-scope.invalid/mcp to local config +$ claude mcp get docs (Scope and URL lines only) + Scope: Local config (private to you in this project) + URL: https://local-scope.invalid/mcp diff --git a/claude-code-spring/pom.xml b/claude-code-spring/pom.xml new file mode 100644 index 0000000..151f943 --- /dev/null +++ b/claude-code-spring/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + + com.ankurm.agents + java-ai-agents + 1.0.0 + + + claude-code-spring + Claude Code on a Spring Boot 4 project: CLAUDE.md, rules, skills, hooks, MCP + + + + 4.2.0 + + + + + + org.springframework.boot + spring-boot-dependencies + ${boot42.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + diff --git a/claude-code-spring/scripts/hook-latency.sh b/claude-code-spring/scripts/hook-latency.sh new file mode 100755 index 0000000..4111d5c --- /dev/null +++ b/claude-code-spring/scripts/hook-latency.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Times the same PreToolUse deny rule written as bash + jq and as a JDK 25 compact source file. +# Indicative only: the numbers change with the machine and with what else is running. +MODULE="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$MODULE/output/07-hook-latency.txt" +JSON='{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"mvn deploy"}}' +N=20 +time_ms() { # time_ms