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:
Ankur Mhatre
2026-11-22 02:05:35 +05:30
co-authored by Claude Sonnet 5.5
parent a620d91d0a
commit 3aa20a1dce
40 changed files with 1175 additions and 0 deletions
@@ -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();
}
}
@@ -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);
}
}