chore(rules): remove Java rules

Delete the Java and Spring rule set under shared/rules/java and its
routing entry in the global instructions. No other rule or skill
referenced it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian LechnerandClaude Opus 5.5 committed 2026-11-18 10:17:20 +01:00
1 parent df09ddeaa9
commit 29632ff0ce
11 files changed
+1 -126

No files matched your search

-15
View File
@@ -1,15 +0,0 @@
# Java Rules
For Java or JVM work, open only the topic rules relevant to the task. Follow the project's target Java release, compiler settings, and conventions. Load applicable shared security rules as well. Avoid preview APIs unless the project explicitly enables them.
| Topic | Codex rule | Claude skill |
| --- | --- | --- |
| Language style and code organization | `references/modern-java.md` | `rules-java-modern-java` |
| Types, collections, and null-safe contracts | `references/types-and-collections.md` | `rules-java-types-and-collections` |
| Architecture and API boundaries | `references/architecture-and-apis.md` | `rules-java-architecture-and-apis` |
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
| Performance | `references/performance.md` | `rules-java-performance` |
| Security | `references/security.md` | `rules-java-security` |
| Spring Boot and Spring Security | `references/spring.md` | `rules-java-spring` |
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
@@ -1,11 +0,0 @@
# Java Architecture and APIs
Apply these rules when designing public APIs, service boundaries, or application structure.
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant format checks through trusted internal code; authorization, ownership, and tenant scoping are never such redundant checks.
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
* Keep domain decisions separate from transport, persistence, and framework wiring. Make dependencies explicit; use dependency injection for real lifecycle or substitution needs.
* Use small contracts at real boundaries. Avoid service locators.
* Preserve existing API and serialization behavior unless the task requires a change. Treat changes to nullability, ordering, exception types, and collection mutability as compatibility changes.
@@ -1,15 +0,0 @@
# Java Async and Concurrency
Apply these rules when changing executors, threads, futures, background work, or shared state.
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
* Create one virtual thread per task (`Executors.newVirtualThreadPerTaskExecutor()`); never pool virtual threads. Limit downstream concurrency with a `Semaphore`, not with a fixed pool size.
* On JDK 21 to 23, blocking inside `synchronized` pins the carrier thread; prefer `ReentrantLock` on hot blocking paths there. JDK 24+ (JEP 491) removes that pinning, but native frames and class initialization still pin.
* Do not cache expensive objects in `ThreadLocal` when running on virtual threads. On JDK 25+, prefer `ScopedValue` (final, JEP 506) for request-scoped context.
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
* Use preview concurrency APIs only when the project explicitly enables them for its target release; `StructuredTaskScope` is still a preview API in JDK 25.
@@ -1,12 +0,0 @@
# Java Coding Style
Apply these rules when editing Java syntax, class structure, and everyday code organization.
* Match the project's Java release, style, and framework conventions. Use newer syntax only when supported and clearer.
* Prefer direct control flow and descriptive domain names. Use streams when they clarify a transformation; loops are often clearer for stateful work or error handling.
* Use local `var` only when the initializer makes the type obvious. Keep public contracts explicitly typed.
* Use records for transparent immutable carriers and sealed types for genuinely closed variants when the target release supports them. Do not force them onto mutable entities or framework-managed types.
* Prefer composition and focused classes over inheritance, broad base classes, reflection, wrappers, global mutable state, or speculative interfaces.
* Make ownership, mutation, and side effects visible. Use `final` where it clarifies invariants; do not add it mechanically to every local variable.
* Prefer supported `java.time` APIs and standard library facilities over obsolete APIs or custom helpers when they fit the contract.
* Remove dead code. Add comments only for non-obvious decisions or public contracts that code cannot express clearly.
@@ -1,14 +0,0 @@
# Java Performance
Apply these rules when optimizing Java runtime, memory, or throughput.
* Measure a representative workload on the target JDK and deployment configuration before optimizing. Profile first; distinguish startup, steady-state latency, tail latency, throughput, allocation, GC, and memory costs.
* Prioritize algorithmic complexity, database and network round trips, I/O, contention, allocation and GC, then instruction-level work. Fix the dominant cost rather than tuning by intuition.
* Choose collections and algorithms for actual access patterns and data growth. Avoid repeated scans, needless sorting or copying, unbounded results, and N+1 data access.
* Filter and project in the data source when appropriate; avoid materializing rows or fields that the caller does not use. Bound page sizes and query work.
* Stream or process data in bounded chunks when whole-input buffering can exhaust memory. Bound queues, caches, thread pools, and parallel work to the capacity of downstream systems.
* Reduce allocation and boxing in profiled hot paths. Avoid premature object pooling, custom caches, and low-level tricks; pooling can retain memory or leak mutable state.
* Cache only when repeated work is measured and key, lifetime, invalidation, size limit, and sensitive-data handling are explicit.
* Use concurrency only when it improves measured end-to-end throughput or latency. Account for ordering, cancellation, backpressure, contention, and failure handling; virtual threads do not make CPU work faster.
* Use JMH for JVM microbenchmarks when isolating small operations; prevent dead-code elimination and account for warmup, forks, and measurement variance. Use production-like profiling for system behavior.
* Re-run the same workload after a change and compare correctness, CPU, allocation, GC, memory, latency, and throughput. Keep the simplest implementation that meets the measured goal.
@@ -1,11 +0,0 @@
# Java Safety and Error Handling
Apply these rules when handling external input, failures, resources, or logs.
* Validate size, range, format, and allowed values before expensive parsing, allocation, or side effects. Keep validation consistent with business and security constraints.
* Reject null where a value is required, with clear argument or boundary validation. Do not hide invalid state behind default values that change behavior.
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. Pass untrusted values as parameters, never as the log format string, and strip or encode CR/LF in them unless the log format is structured.
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
-13
View File
@@ -1,13 +0,0 @@
# Java Security
Apply these rules to security-sensitive Java code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only Java specifics, and the Spring rule covers Spring Boot and Spring Security.
* Use parameterized database APIs such as `PreparedStatement`. Select dynamic identifiers or sort expressions from a fixed allowlist; never concatenate untrusted data into SQL.
* Resolve file paths with `root.resolve(input).normalize()` and check containment with `Path.startsWith(root)`, never `String.startsWith`, which accepts `/data/app2` for `/data/app`. `normalize()` does not resolve symlinks; use `toRealPath()` when links matter and the file exists, and account for replacement races. Check every `ZipEntry` name the same way. Limit file size and processing work.
* Use `ProcessBuilder` with an absolute executable path and separate arguments; avoid shell interpretation. On Windows, the argument list is flattened into one command line that the target re-parses, and `.bat` or `.cmd` targets run through `cmd.exe`; never pass untrusted arguments to them, and validate attacker-controlled arguments against an allowlist.
* Parse untrusted XML with DTDs disabled (`http://apache.org/xml/features/disallow-doctype-decl` set to `true`), or, where DTDs are required, with external entities and external DTD and schema access disabled (`XMLConstants.ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_SCHEMA` set to `""`, `XMLConstants.FEATURE_SECURE_PROCESSING` enabled). Apply this to every factory that reads untrusted XML: `DocumentBuilderFactory`, `SAXParserFactory`, `XMLInputFactory`, `TransformerFactory`, `SchemaFactory`, and JAXB unmarshallers.
* Deserialize into explicit allowed types and bound input size and nesting. Avoid native Java serialization for untrusted data; where it is unavoidable, install an `ObjectInputFilter` allowlist. With Jackson, never enable default typing (`activateDefaultTyping`) or `@JsonTypeInfo(use = Id.CLASS)` for untrusted input; use `Id.NAME` with registered subtypes or a strict `PolymorphicTypeValidator`. Spring Boot 4 uses Jackson 3 (`tools.jackson.*` packages; annotations stay in `com.fasterxml.jackson.annotation`). Load YAML with SnakeYAML 2.x or a `SafeConstructor`. Never evaluate untrusted SpEL, OGNL, or JNDI names.
* Use the platform's maintained TLS, cryptographic, and secure-random APIs with the parameters in the shared cryptography rule. Always specify the full `Cipher` transformation, for example `AES/GCM/NoPadding`, because `Cipher.getInstance("AES")` means ECB. Use `SecureRandom`, never `java.util.Random`, for security values, and `MessageDigest.isEqual` for constant-time comparison. Never install trust-all `X509TrustManager` or `HostnameVerifier` implementations. Do not rely on the Security Manager; JDK 24+ disables it permanently.
* For outbound URLs, parse with `java.net.URI` (the `URL` constructors are deprecated since JDK 20) and check every resolved `InetAddress` (`isLoopbackAddress`, `isLinkLocalAddress`, `isSiteLocalAddress`, `isAnyLocalAddress`, `isMulticastAddress`); these miss IPv6 unique-local `fc00::/7`, carrier-grade NAT `100.64.0.0/10`, and IPv4-mapped IPv6, so check those explicitly. Keep `java.net.http.HttpClient` on its default `Redirect.NEVER` or revalidate every hop.
* For regular expressions on untrusted input, bound the input length first and avoid nested or overlapping quantifiers, because `java.util.regex` has no timeout; use RE2/J for untrusted patterns.
* Encode output with the template engine's automatic escaping or the OWASP Java Encoder for the exact context; never build HTML, XML, LDAP, or JPQL from untrusted strings.
-12
View File
@@ -1,12 +0,0 @@
# Java Spring Boot and Spring Security
Apply these rules when changing Spring Boot configuration, Spring Security, Spring MVC or WebFlux endpoints, Spring Data repositories, or Actuator exposure. Follow the project's Spring Boot and Spring Security versions; Spring Boot 4 and Spring Framework 7 are current.
* Deny by default: end the `authorizeHttpRequests` chain with `.anyRequest().authenticated()` (or `denyAll()`) and list public routes explicitly with `permitAll`.
* Keep CSRF protection enabled for browser clients that authenticate with cookies or sessions. Disable it only for stateless token-authenticated APIs, and say why in the configuration.
* Expose only `health` and `info` Actuator endpoints publicly. Never expose `env`, `heapdump`, `threaddump`, `configprops`, `loggers`, `mappings`, or `beans` without authentication; `heapdump` and `env` leak secrets. Prefer a separate management port.
* Enforce method security (`@PreAuthorize` with `@EnableMethodSecurity`) on service methods reachable from non-HTTP entry points such as messaging, schedulers, or batch jobs.
* Bind requests to dedicated DTOs, never directly to JPA entities with `@RequestBody` or `@ModelAttribute`, to prevent mass assignment. Validate DTOs with Bean Validation (`@Valid`).
* Use parameter binding in JPQL, HQL, and `@Query` native SQL; never concatenate untrusted input into query strings. Select dynamic sort properties from an allowlist before building `Sort` objects.
* Store passwords through a `DelegatingPasswordEncoder` with an encoder that meets the shared cryptography rule, for example `Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()`, and upgrade legacy hashes on login.
* Keep secrets out of `application.yml` and profiles in the repository; bind them from environment variables or a secret store.
@@ -1,11 +0,0 @@
# Java Testing and Dependencies
Apply these rules when changing tests, build files, dependencies, or diagnostics.
* Write deterministic behavior-based tests for public contracts and failure paths. Avoid assertions tied to private call order, wall-clock timing, or uncontrolled external services.
* Test null and empty cases, malformed input, resource cleanup, interruption, and concurrency behavior when those risks are affected. Use integration tests for actual persistence, framework, or serialization boundaries.
* Keep production code testable through clear contracts and ownership. Do not add abstraction layers or production hooks solely for tests without a concrete need.
* Prefer the JDK and existing supported libraries when they solve the problem. Keep dependencies minimal, maintained, and compatible with the configured Java release.
* Respect the repository's Maven or Gradle dependency and plugin management. Review transitive changes, build plugins, and lockfiles; do not hand-edit generated dependency state.
* Treat compiler warnings and configured static-analysis findings as actionable. Suppress a diagnostic only with a specific reason and narrow scope.
* Run the focused tests and checks for the changed path; broaden verification when shared behavior, compatibility, or security is affected.
@@ -1,11 +0,0 @@
# Java Types and Collections
Apply these rules when defining type contracts, choosing collections, or handling nullable values.
* Write null-safe code. State whether each boundary value may be absent, validate required values before dereferencing, and use the project's nullability annotations and analysis tools when available. Do not assume an annotation enforces runtime validation.
* Prefer non-null return values and empty collections for valid empty results. Use `Optional<T>` mainly for a return value that may have no result; do not return a null `Optional` or use it for fields and parameters by default.
* Distinguish a missing map key from a key mapped to null when the contract permits both. Do not use `get()` alone when that distinction matters.
* Keep public contracts strongly typed. Avoid raw types, unchecked casts, and stringly typed maps; document and narrowly suppress unavoidable generic warnings.
* Choose `List`, `Set`, `Map`, or a more specific type according to ordering, uniqueness, lookup, and mutation needs. Expose only the capabilities callers need; do not leak mutable internal collections.
* Distinguish an unmodifiable view from an independent copy. Make defensive copies at ownership boundaries when later mutation would violate the contract.
* Prefer immutable data for values with stable identity and ownership, while respecting framework and serialization requirements. Avoid unnecessary boxing and copies in measured hot paths.