Add claude-code-spring module: CLAUDE.md, a path-scoped rule, two skills, four hooks run against real hook JSON, project .mcp.json from the claude mcp CLI, and tests that lint the setup on Spring Boot 4.2.0
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b86yyhhudsSLnwNUFY
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
a620d91d0a
commit
3aa20a1dce
@@ -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 |
|
| `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 |
|
| `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 |
|
| `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)
|
## 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 |
|
| 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 |
|
| 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 |
|
| 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 | |
|
| JDK | 25 LTS | |
|
||||||
| JUnit | 6.1.3 | |
|
| JUnit | 6.1.3 | |
|
||||||
|
|
||||||
|
|||||||
@@ -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 + "\"}}");
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -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
|
||||||
+22
@@ -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<n> 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<next>__*.sql file instead." >&2
|
||||||
|
exit 2
|
||||||
|
fi ;;
|
||||||
|
esac
|
||||||
|
exit 0
|
||||||
+18
@@ -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
|
||||||
+30
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
target/
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
CLAUDE.local.md
|
||||||
|
.claude/settings.local.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/[email protected]",
|
||||||
|
"--transport",
|
||||||
|
"stdio",
|
||||||
|
"--dsn",
|
||||||
|
"${DB_URL}"
|
||||||
|
],
|
||||||
|
"env": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<next>__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.
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
java files scanned: 9
|
||||||
|
violations: 0
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -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":"<project>/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":"<project>/src/main/resources/application-prod.properties"}}
|
||||||
|
stdout: (empty)
|
||||||
|
stderr: Blocked: <project>/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":"<project>/src/main/resources/db/migration/V1__create_orders.sql"}}
|
||||||
|
stdout: (empty)
|
||||||
|
stderr: Blocked: <project>/src/main/resources/db/migration/V1__create_orders.sql is an existing Flyway migration. Add a new V<next>__*.sql file instead.
|
||||||
|
exit : 2
|
||||||
|
|
||||||
|
## Write over an existing migration
|
||||||
|
input : {"hook_event_name":"PreToolUse","tool_name":"Write","tool_input":{"file_path":"<project>/src/main/resources/db/migration/V1__create_orders.sql"}}
|
||||||
|
stdout: (empty)
|
||||||
|
stderr: Blocked: <project>/src/main/resources/db/migration/V1__create_orders.sql is an existing Flyway migration. Add a new V<next>__*.sql file instead.
|
||||||
|
exit : 2
|
||||||
|
|
||||||
|
## Write a new migration
|
||||||
|
input : {"hook_event_name":"PreToolUse","tool_name":"Write","tool_input":{"file_path":"<project>/src/main/resources/db/migration/V2__add_status.sql"}}
|
||||||
|
stdout: (empty)
|
||||||
|
stderr: (empty)
|
||||||
|
exit : 0
|
||||||
|
|
||||||
@@ -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":"<project>/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":"<project>/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":"<project>/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":"<project>/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] <project>/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] <project>/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
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -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: <tmp>/project/.mcp.json
|
||||||
|
|
||||||
|
$ claude mcp add --scope project --transport stdio db -- npx -y @bytebase/[email protected] --transport stdio --dsn ${DB_URL}
|
||||||
|
Added stdio MCP server db with command: npx -y @bytebase/[email protected] --transport stdio --dsn ${DB_URL} to project config
|
||||||
|
File modified: <tmp>/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/[email protected]",
|
||||||
|
"--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/[email protected] --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: <tmp>/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/[email protected] --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: <tmp>/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
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.ankurm.agents</groupId>
|
||||||
|
<artifactId>java-ai-agents</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>claude-code-spring</artifactId>
|
||||||
|
<name>Claude Code on a Spring Boot 4 project: CLAUDE.md, rules, skills, hooks, MCP</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- Spring Boot 4.2.0 GA, verified on Maven Central 2026-11-21 -->
|
||||||
|
<boot42.version>4.2.0</boot42.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
|
<version>${boot42.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webmvc-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Executable
+26
@@ -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 <label> <command...> -> average wall milliseconds over N runs
|
||||||
|
local label="$1"; shift
|
||||||
|
local start end
|
||||||
|
start=$(date +%s%N)
|
||||||
|
for _ in $(seq $N); do echo "$JSON" | "$@" >/dev/null 2>&1; done
|
||||||
|
end=$(date +%s%N)
|
||||||
|
printf '%-34s %6d ms per call (average of %d)\n' "$label" $(( (end - start) / N / 1000000 )) $N
|
||||||
|
}
|
||||||
|
{
|
||||||
|
echo "java: $(java -version 2>&1 | grep -m1 'openjdk version')"
|
||||||
|
echo "jq : $(jq --version)"
|
||||||
|
time_ms "guard-bash.sh (bash + jq)" "$MODULE/.claude/hooks/guard-bash.sh"
|
||||||
|
time_ms "java GuardBash.java (source launcher)" java "$MODULE/.claude/hooks/GuardBash.java"
|
||||||
|
echo
|
||||||
|
echo "both produce the same decision:"
|
||||||
|
echo "$JSON" | "$MODULE/.claude/hooks/guard-bash.sh" | jq -r '.hookSpecificOutput.permissionDecision'
|
||||||
|
echo "$JSON" | java "$MODULE/.claude/hooks/GuardBash.java" 2>/dev/null | jq -r '.hookSpecificOutput.permissionDecision'
|
||||||
|
} > "$OUT"
|
||||||
|
cat "$OUT"
|
||||||
Executable
+96
@@ -0,0 +1,96 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Feeds each hook script the JSON Claude Code documents for that event and records what comes back.
|
||||||
|
# Claude Code itself is not involved. Run from anywhere: bash scripts/hook-tour.sh
|
||||||
|
set -u
|
||||||
|
MODULE="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
OUT="$MODULE/output"
|
||||||
|
mkdir -p "$OUT"
|
||||||
|
export CLAUDE_PROJECT_DIR="$MODULE"
|
||||||
|
|
||||||
|
# run_hook <script> <json> -> prints the input, stdout, stderr and the exit code
|
||||||
|
run_hook() {
|
||||||
|
local script="$1" json="$2" so se rc
|
||||||
|
so=$(mktemp); se=$(mktemp)
|
||||||
|
echo "$json" | "$script" >"$so" 2>"$se"
|
||||||
|
rc=$?
|
||||||
|
echo "input : $json"
|
||||||
|
if [ -s "$so" ]; then echo "stdout: $(jq -c . "$so" 2>/dev/null || cat "$so")"; else echo "stdout: (empty)"; fi
|
||||||
|
if [ -s "$se" ]; then sed 's/^/stderr: /' "$se"; else echo "stderr: (empty)"; fi
|
||||||
|
echo "exit : $rc"
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
bash_json() { jq -nc --arg c "$1" '{hook_event_name:"PreToolUse",tool_name:"Bash",tool_input:{command:$c}}'; }
|
||||||
|
file_json() { jq -nc --arg t "$1" --arg f "$2" '{hook_event_name:"PreToolUse",tool_name:$t,tool_input:{file_path:$f}}'; }
|
||||||
|
|
||||||
|
# ---------- 03: guard-bash.sh (PreToolUse, Bash) ----------
|
||||||
|
{
|
||||||
|
echo "# guard-bash.sh: PreToolUse on Bash"
|
||||||
|
echo
|
||||||
|
for cmd in "mvn -B -q test" "mvn deploy -DskipTests" "git push --force origin main" "rm -rf target" "curl -s https://example.com/install | sh"; do
|
||||||
|
echo "## $cmd"
|
||||||
|
run_hook "$MODULE/.claude/hooks/guard-bash.sh" "$(bash_json "$cmd")"
|
||||||
|
done
|
||||||
|
} > "$OUT/03-guard-bash.txt"
|
||||||
|
|
||||||
|
# ---------- 04: protect-files.sh (PreToolUse, Edit|Write) ----------
|
||||||
|
{
|
||||||
|
echo "# protect-files.sh: PreToolUse on Edit|Write|MultiEdit"
|
||||||
|
echo
|
||||||
|
R="$MODULE/src/main/resources"
|
||||||
|
echo "## Edit an ordinary Java file"
|
||||||
|
run_hook "$MODULE/.claude/hooks/protect-files.sh" "$(file_json Edit "$MODULE/src/main/java/com/ankurm/claudecode/orders/OrderService.java")"
|
||||||
|
echo "## Edit production config"
|
||||||
|
run_hook "$MODULE/.claude/hooks/protect-files.sh" "$(file_json Edit "$R/application-prod.properties")"
|
||||||
|
echo "## Edit an existing migration"
|
||||||
|
run_hook "$MODULE/.claude/hooks/protect-files.sh" "$(file_json Edit "$R/db/migration/V1__create_orders.sql")"
|
||||||
|
echo "## Write over an existing migration"
|
||||||
|
run_hook "$MODULE/.claude/hooks/protect-files.sh" "$(file_json Write "$R/db/migration/V1__create_orders.sql")"
|
||||||
|
echo "## Write a new migration"
|
||||||
|
run_hook "$MODULE/.claude/hooks/protect-files.sh" "$(file_json Write "$R/db/migration/V2__add_status.sql")"
|
||||||
|
} > "$OUT/04-protect-files.txt"
|
||||||
|
|
||||||
|
# ---------- 05 and 06 mutate code, so they run in a throwaway copy ----------
|
||||||
|
# The module's parent POM sits one level up, so the copy needs a parent folder with that POM in it.
|
||||||
|
BASE="$(mktemp -d)"
|
||||||
|
WORK="$BASE/claude-code-spring"
|
||||||
|
mkdir -p "$WORK"
|
||||||
|
cp "$MODULE/../pom.xml" "$BASE/pom.xml"
|
||||||
|
tar -C "$MODULE" --exclude=./target --exclude=./output -cf - . | tar -C "$WORK" -xf -
|
||||||
|
export CLAUDE_PROJECT_DIR="$WORK"
|
||||||
|
SVC="$WORK/src/main/java/com/ankurm/claudecode/orders/OrderService.java"
|
||||||
|
post_json() { jq -nc --arg f "$1" '{hook_event_name:"PostToolUse",tool_name:"Edit",tool_input:{file_path:$f},tool_response:{success:true}}'; }
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "# test-after-edit.sh: PostToolUse on Edit|Write (run in a throwaway copy)"
|
||||||
|
echo
|
||||||
|
echo "## Edited OrderService.java, code is correct"
|
||||||
|
run_hook "$WORK/.claude/hooks/test-after-edit.sh" "$(post_json "$SVC")"
|
||||||
|
echo "## Edited README.md (not Java)"
|
||||||
|
run_hook "$WORK/.claude/hooks/test-after-edit.sh" "$(post_json "$WORK/README.md")"
|
||||||
|
echo "## Edited OrderService.java after changing >= to > in total()"
|
||||||
|
sed -i 's/order.quantity() >= BULK_THRESHOLD/order.quantity() > BULK_THRESHOLD/' "$SVC"
|
||||||
|
grep -n 'BULK_THRESHOLD)' "$SVC" | sed 's/^/changed: /'
|
||||||
|
run_hook "$WORK/.claude/hooks/test-after-edit.sh" "$(post_json "$SVC")"
|
||||||
|
echo "## Edited OrderService.java into a compile error"
|
||||||
|
sed -i 's/BigDecimal gross = /BigDecimal gross = ;/' "$SVC"
|
||||||
|
run_hook "$WORK/.claude/hooks/test-after-edit.sh" "$(post_json "$SVC")"
|
||||||
|
} > "$OUT/05-test-after-edit.txt"
|
||||||
|
|
||||||
|
# restore the >= bug for the Stop hook run, keep it red
|
||||||
|
tar -C "$MODULE" -cf - ./src/main/java/com/ankurm/claudecode/orders/OrderService.java | tar -C "$WORK" -xf -
|
||||||
|
stop_json() { jq -nc --argjson a "$1" '{hook_event_name:"Stop",stop_hook_active:$a,last_assistant_message:"Done."}'; }
|
||||||
|
{
|
||||||
|
echo "# stop-gate.sh: Stop (run in a throwaway copy)"
|
||||||
|
echo
|
||||||
|
echo "## Suite green, stop_hook_active=false"
|
||||||
|
run_hook "$WORK/.claude/hooks/stop-gate.sh" "$(stop_json false)"
|
||||||
|
sed -i 's/order.quantity() >= BULK_THRESHOLD/order.quantity() > BULK_THRESHOLD/' "$SVC"
|
||||||
|
echo "## Suite red (>= changed to >), stop_hook_active=false"
|
||||||
|
run_hook "$WORK/.claude/hooks/stop-gate.sh" "$(stop_json false)"
|
||||||
|
echo "## Suite still red, stop_hook_active=true (Claude was already pushed back once)"
|
||||||
|
run_hook "$WORK/.claude/hooks/stop-gate.sh" "$(stop_json true)"
|
||||||
|
} > "$OUT/06-stop-gate.txt"
|
||||||
|
# Keep this machine's paths out of the committed transcripts.
|
||||||
|
sed -i "s#$MODULE#<project>#g; s#$WORK#<project>#g" "$OUT"/03-*.txt "$OUT"/04-*.txt "$OUT"/05-*.txt "$OUT"/06-*.txt
|
||||||
|
echo "wrote $OUT/03..06 (throwaway copy: $WORK)"
|
||||||
Executable
+48
@@ -0,0 +1,48 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Runs the real `claude mcp` CLI in a throwaway directory with a throwaway HOME, so nothing touches your
|
||||||
|
# own configuration. Needs the `claude` CLI on PATH; it does not need to be signed in.
|
||||||
|
MODULE="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
OUT="$MODULE/output/08-mcp-cli.txt"
|
||||||
|
WORK="$(mktemp -d)"
|
||||||
|
export HOME="$WORK/home"; mkdir -p "$HOME"
|
||||||
|
cd "$WORK" && mkdir project && cd project && git init -q .
|
||||||
|
unset GITEA_TOKEN DB_URL
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "claude --version: $(claude --version)"
|
||||||
|
echo
|
||||||
|
echo '$ 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'
|
||||||
|
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 2>&1
|
||||||
|
echo
|
||||||
|
echo '$ claude mcp add --scope project --transport stdio db -- npx -y @bytebase/[email protected] --transport stdio --dsn ${DB_URL}'
|
||||||
|
claude mcp add --scope project --transport stdio db -- npx -y @bytebase/[email protected] --transport stdio --dsn '${DB_URL}' 2>&1
|
||||||
|
echo
|
||||||
|
echo '$ cat .mcp.json'
|
||||||
|
cat .mcp.json; echo
|
||||||
|
echo
|
||||||
|
echo "committed .mcp.json identical to the generated one: $(cmp -s .mcp.json "$MODULE/.mcp.json" && echo yes || echo NO)"
|
||||||
|
echo
|
||||||
|
echo '$ claude mcp list (GITEA_TOKEN and DB_URL unset)'
|
||||||
|
claude mcp list 2>&1 | sed '/^$/d'
|
||||||
|
echo
|
||||||
|
echo '$ claude mcp get gitea'
|
||||||
|
claude mcp get gitea 2>&1 | sed '/^$/d'
|
||||||
|
echo
|
||||||
|
echo '$ GITEA_TOKEN=x DB_URL=x claude mcp list'
|
||||||
|
GITEA_TOKEN=x DB_URL=x claude mcp list 2>&1 | sed '/^$/d'
|
||||||
|
echo
|
||||||
|
echo '--- a hand-written entry that has a url but no "type"'
|
||||||
|
mkdir ../bad && cd ../bad && git init -q .
|
||||||
|
echo '{"mcpServers":{"remote":{"url":"https://example.invalid/mcp"}}}' > .mcp.json
|
||||||
|
echo '$ claude mcp list'
|
||||||
|
claude mcp list 2>&1 | sed '/^$/d'
|
||||||
|
echo
|
||||||
|
echo '--- scope precedence: the same server name in user and local scope'
|
||||||
|
claude mcp add --scope user --transport http docs https://user-scope.invalid/mcp 2>&1 | head -1
|
||||||
|
claude mcp add --scope local --transport http docs https://local-scope.invalid/mcp 2>&1 | head -1
|
||||||
|
echo '$ claude mcp get docs (Scope and URL lines only)'
|
||||||
|
claude mcp get docs 2>&1 | grep -E 'Scope:|URL:'
|
||||||
|
} > "$OUT"
|
||||||
|
sed -i "s#$WORK#<tmp>#g" "$OUT"
|
||||||
|
cat "$OUT"
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Regenerates every file in output/. Needs JDK 25 on PATH (JAVA_HOME set), Maven, jq and the claude CLI.
|
||||||
|
set -e
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mvn -B -q test # output/01, output/02
|
||||||
|
bash scripts/hook-tour.sh # output/03 .. output/06
|
||||||
|
bash scripts/hook-latency.sh # output/07
|
||||||
|
bash scripts/mcp-tour.sh # output/08
|
||||||
|
ls output
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/** One order line. Money is BigDecimal, never double (see CLAUDE.md). */
|
||||||
|
public record Order(long id, String customer, int quantity, BigDecimal unitPrice) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/orders")
|
||||||
|
public class OrderController {
|
||||||
|
|
||||||
|
public record NewOrder(String customer, int quantity, BigDecimal unitPrice) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private final OrderService service;
|
||||||
|
|
||||||
|
public OrderController(OrderService service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<Map<String, Object>> create(@RequestBody NewOrder body) {
|
||||||
|
Order order = service.create(body.customer(), body.quantity(), body.unitPrice());
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED).body(view(order));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<Map<String, Object>> get(@PathVariable long id) {
|
||||||
|
return service.find(id).map(o -> ResponseEntity.ok(view(o))).orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<Map<String, Object>> list() {
|
||||||
|
return service.all().stream().map(this::view).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
|
public ResponseEntity<Map<String, String>> badRequest(IllegalArgumentException e) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> view(Order o) {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("id", o.id());
|
||||||
|
m.put("customer", o.customer());
|
||||||
|
m.put("quantity", o.quantity());
|
||||||
|
m.put("total", service.total(o));
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class OrderService {
|
||||||
|
|
||||||
|
/** Ten or more units earn a 10 percent discount. */
|
||||||
|
static final int BULK_THRESHOLD = 10;
|
||||||
|
|
||||||
|
private final ConcurrentHashMap<Long, Order> orders = new ConcurrentHashMap<>();
|
||||||
|
private final AtomicLong ids = new AtomicLong();
|
||||||
|
|
||||||
|
public Order create(String customer, int quantity, BigDecimal unitPrice) {
|
||||||
|
if (quantity < 1) {
|
||||||
|
throw new IllegalArgumentException("quantity must be at least 1");
|
||||||
|
}
|
||||||
|
Order order = new Order(ids.incrementAndGet(), customer, quantity, unitPrice);
|
||||||
|
orders.put(order.id(), order);
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Order> find(long id) {
|
||||||
|
return Optional.ofNullable(orders.get(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Order> all() {
|
||||||
|
return orders.values().stream().sorted(java.util.Comparator.comparingLong(Order::id)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal total(Order order) {
|
||||||
|
BigDecimal gross = order.unitPrice().multiply(BigDecimal.valueOf(order.quantity()));
|
||||||
|
if (order.quantity() >= BULK_THRESHOLD) {
|
||||||
|
gross = gross.multiply(new BigDecimal("0.90"));
|
||||||
|
}
|
||||||
|
return gross.setScale(2, RoundingMode.HALF_UP);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class OrdersApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(OrdersApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
spring.datasource.url=jdbc:postgresql://prod-db.internal/orders
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
spring.application.name=orders
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- V1: applied migrations are immutable. Add V2, never edit this file.
|
||||||
|
create table orders (id bigint primary key, customer varchar(80) not null, quantity int not null, unit_price numeric(12,2) not null);
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import tools.jackson.databind.JsonNode;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lints the Claude Code configuration this project ships, the way a CI job could. A broken settings file or a
|
||||||
|
* hook path that does not exist is otherwise found only when a session starts. Writes output/01-config-lint.txt.
|
||||||
|
*/
|
||||||
|
class ClaudeConfigTest {
|
||||||
|
|
||||||
|
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||||
|
private static final Path ROOT = Path.of(".");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shippedConfigurationIsConsistent() throws IOException {
|
||||||
|
Transcript t = new Transcript("01-config-lint.txt");
|
||||||
|
|
||||||
|
// CLAUDE.md: the docs recommend under 200 lines, and they strip block-level HTML comments.
|
||||||
|
List<String> claudeMd = Files.readAllLines(ROOT.resolve("CLAUDE.md"));
|
||||||
|
t.line("CLAUDE.md lines: " + claudeMd.size() + " (guidance: under 200)");
|
||||||
|
assertThat(claudeMd.size()).isLessThan(200);
|
||||||
|
// Strip `code spans` first: annotations such as @Autowired are not imports. This is this lint's own rule.
|
||||||
|
String withoutCodeSpans = String.join("\n", claudeMd).replaceAll("`[^`]*`", "");
|
||||||
|
Matcher imports = Pattern.compile("@([\\w./-]+)").matcher(withoutCodeSpans);
|
||||||
|
while (imports.find()) {
|
||||||
|
Path target = ROOT.resolve(imports.group(1));
|
||||||
|
t.line("CLAUDE.md import @" + imports.group(1) + " exists: " + Files.exists(target));
|
||||||
|
assertThat(target).exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
// settings.json: valid JSON, every hook command points at a real, executable file.
|
||||||
|
JsonNode settings = JSON.readTree(Files.readString(ROOT.resolve(".claude/settings.json")));
|
||||||
|
JsonNode hooks = settings.get("hooks");
|
||||||
|
List<String> events = new ArrayList<>();
|
||||||
|
hooks.propertyNames().forEach(events::add);
|
||||||
|
t.line("settings.json hook events: " + events);
|
||||||
|
for (String event : events) {
|
||||||
|
for (JsonNode group : hooks.get(event)) {
|
||||||
|
String matcher = group.has("matcher") ? group.get("matcher").asString() : "(none, matches everything)";
|
||||||
|
for (JsonNode h : group.get("hooks")) {
|
||||||
|
String command = h.get("command").asString().replace("${CLAUDE_PROJECT_DIR}", ".");
|
||||||
|
Path script = ROOT.resolve(command);
|
||||||
|
boolean exec = Files.isExecutable(script);
|
||||||
|
t.line(String.format(" %-11s matcher=%-22s %s executable=%s timeout=%s", event, matcher,
|
||||||
|
command, exec, h.has("timeout") ? h.get("timeout").asInt() : "default"));
|
||||||
|
assertThat(script).exists();
|
||||||
|
assertThat(exec).isTrue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<String> deny = new ArrayList<>();
|
||||||
|
settings.get("permissions").get("deny").forEach(n -> deny.add(n.asString()));
|
||||||
|
t.line("permissions.deny: " + deny);
|
||||||
|
|
||||||
|
// Skills: frontmatter between --- markers, name matches the directory.
|
||||||
|
try (var dirs = Files.list(ROOT.resolve(".claude/skills"))) {
|
||||||
|
for (Path dir : dirs.sorted().toList()) {
|
||||||
|
String text = Files.readString(dir.resolve("SKILL.md"));
|
||||||
|
assertThat(text).startsWith("---\n");
|
||||||
|
String front = text.substring(4, text.indexOf("\n---", 4));
|
||||||
|
Map<String, String> kv = new java.util.LinkedHashMap<>();
|
||||||
|
for (String line : front.split("\n")) {
|
||||||
|
int i = line.indexOf(':');
|
||||||
|
kv.put(line.substring(0, i).trim(), line.substring(i + 1).trim());
|
||||||
|
}
|
||||||
|
t.line("skill " + dir.getFileName() + ": keys=" + kv.keySet());
|
||||||
|
assertThat(kv.get("name")).isEqualTo(dir.getFileName().toString());
|
||||||
|
assertThat(kv).containsKey("description");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// .mcp.json: every server has a type, and no literal secret is committed.
|
||||||
|
String mcpText = Files.readString(ROOT.resolve(".mcp.json"));
|
||||||
|
JsonNode servers = JSON.readTree(mcpText).get("mcpServers");
|
||||||
|
servers.propertyNames().forEach(name -> {
|
||||||
|
JsonNode s = servers.get(name);
|
||||||
|
t.line("mcp server " + name + ": type=" + s.get("type").asString()
|
||||||
|
+ (s.has("command") ? " command=" + s.get("command").asString() : "")
|
||||||
|
+ (s.has("url") ? " url=" + s.get("url").asString() : ""));
|
||||||
|
assertThat(s.has("type")).isTrue();
|
||||||
|
});
|
||||||
|
t.line("secrets in .mcp.json: " + Pattern.compile("[\"'][A-Za-z0-9_-]{30,}[\"']").matcher(mcpText).find());
|
||||||
|
assertThat(Pattern.compile("[\"'][A-Za-z0-9_-]{30,}[\"']").matcher(mcpText).find()).isFalse();
|
||||||
|
assertThat(mcpText).contains("${GITEA_TOKEN}");
|
||||||
|
|
||||||
|
t.write();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CLAUDE.md is advice, not enforcement. The Boot 4 import rules in it are cheap to enforce with a test, so a
|
||||||
|
* Boot 3 import that slips in fails the build whether a human or a model wrote it. Writes output/02-conventions.txt.
|
||||||
|
*/
|
||||||
|
class ConventionsTest {
|
||||||
|
|
||||||
|
private static final List<String> BANNED = List.of(
|
||||||
|
"com.fasterxml.jackson.databind",
|
||||||
|
"org.springframework.boot.test.autoconfigure.web.servlet");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noBoot3ImportsAndNoFieldInjectionInMain() throws IOException {
|
||||||
|
Transcript t = new Transcript("02-conventions.txt");
|
||||||
|
List<String> violations = new ArrayList<>();
|
||||||
|
int files = 0;
|
||||||
|
try (Stream<Path> walk = Files.walk(Path.of("src"))) {
|
||||||
|
for (Path p : walk.filter(f -> f.toString().endsWith(".java")).sorted().toList()) {
|
||||||
|
files++;
|
||||||
|
List<String> lines = Files.readAllLines(p);
|
||||||
|
for (int i = 0; i < lines.size(); i++) {
|
||||||
|
String line = lines.get(i);
|
||||||
|
for (String banned : BANNED) {
|
||||||
|
if (line.startsWith("import ") && line.contains(banned)) {
|
||||||
|
violations.add(p + ":" + (i + 1) + " imports " + banned);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boolean mainSource = p.toString().startsWith("src/main");
|
||||||
|
if (mainSource && line.trim().equals("@Autowired")) {
|
||||||
|
violations.add(p + ":" + (i + 1) + " field/setter @Autowired in src/main");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.line("java files scanned: " + files);
|
||||||
|
t.line("violations: " + violations.size());
|
||||||
|
violations.forEach(v -> t.line(" " + v));
|
||||||
|
t.write();
|
||||||
|
assertThat(violations).isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
class OrderControllerTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
MockMvc mvc;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createThenFetch() throws Exception {
|
||||||
|
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"customer\":\"asha\",\"quantity\":10,\"unitPrice\":10.00}"))
|
||||||
|
.andExpect(status().isCreated())
|
||||||
|
.andExpect(jsonPath("$.total").value(90.00));
|
||||||
|
mvc.perform(get("/orders/1")).andExpect(status().isOk()).andExpect(jsonPath("$.customer").value("asha"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownOrderIs404() throws Exception {
|
||||||
|
mvc.perform(get("/orders/999")).andExpect(status().isNotFound());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badQuantityIs400() throws Exception {
|
||||||
|
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"customer\":\"x\",\"quantity\":0,\"unitPrice\":1}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class OrderServiceTest {
|
||||||
|
|
||||||
|
private final OrderService service = new OrderService();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nineUnitsPayFullPrice() {
|
||||||
|
Order o = service.create("asha", 9, new BigDecimal("10.00"));
|
||||||
|
assertThat(service.total(o)).isEqualByComparingTo("90.00");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void tenUnitsGetTenPercentOff() {
|
||||||
|
Order o = service.create("asha", 10, new BigDecimal("10.00"));
|
||||||
|
assertThat(service.total(o)).isEqualByComparingTo("90.00");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twentyUnitsGetTenPercentOff() {
|
||||||
|
Order o = service.create("ravi", 20, new BigDecimal("10.00"));
|
||||||
|
assertThat(service.total(o)).isEqualByComparingTo("180.00");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void zeroQuantityIsRejected() {
|
||||||
|
assertThatThrownBy(() -> service.create("asha", 0, BigDecimal.ONE))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage("quantity must be at least 1");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.ankurm.claudecode.orders;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Collects lines and writes them to output/NN-name.txt so the post quotes what the test asserted. */
|
||||||
|
final class Transcript {
|
||||||
|
|
||||||
|
private final Path file;
|
||||||
|
private final List<String> lines = new ArrayList<>();
|
||||||
|
|
||||||
|
Transcript(String name) {
|
||||||
|
this.file = Path.of("output", name);
|
||||||
|
}
|
||||||
|
|
||||||
|
Transcript line(String s) {
|
||||||
|
lines.add(s);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void write() throws IOException {
|
||||||
|
Files.createDirectories(file.getParent());
|
||||||
|
Files.write(file, lines);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user