docs(core): core·조립·빌드·플랫폼 모듈 문서를 한국어로 옮긴다

문제: core 계층(application·domain·shared-contract), app-bootstrap,
composition, registry, build-logic, optional 빌드의 모듈 문서가 영어다.
세션이 처음 읽는 지역 규칙인데 소유자는 2026-11-07에 살아 있는 문서를
모두 한국어로 쓰기로 정했다. leaf CLAUDE.md 셋은 Spring Boot 버전을
4.0.0으로 복사해 두었는데 실제 버전(libs.versions.toml)과 다르다.

방법: 뜻을 그대로 옮기고 코드·명령·경로·식별자·표 구조는 원문으로
둔다. 버전은 `src/gradle/libs.versions.toml`을 가리키는 말로 바꾼다.
다른 문서·코드가 제목으로 가리키는 절(application-core의
Naming convention·Package ownership·Canonical use case shape·Allowed
transactional shapes, shared-contract의 Responsibility·Forbidden,
messaging의 발행 재시도 절)은 영어 원제를 괄호로 남겨 그 참조가
계속 찾아지게 한다. 참조하는 쪽을 고치는 것은 이 작업 범위 밖이다.
코드와 어긋난 주장은 코드에 맞춘다: TransactionPort 구현을
`adapter-persistence`에서 `adapter:outbound:persistence-jpa`의
`SpringTransaction`으로, registry README의 빈 의존 목록 예를
persistence-mongo(실제 목록은 application-core·shared-contract)에서
domain-core·shared-contract·messaging-core-api로 고친다.
TemplatePackageOwnershipDocumentTest는 표 머리 문자열로 표를 찾으므로
머리 상수를 한국어 머리(`| 패키지 (...) |`)로 맞춘다. 표와 기계 사본을
대조하는 계약은 그대로다.

위험: 영어 원제를 괄호로 남긴 제목은 참조하는 문서가 한국어 제목으로
바뀌면 괄호를 지울 수 있다. 본문의 짧은 이력 번호(07-08, 06-01,
11-M9)는 뜻을 바꾸지 않으려고 그대로 옮겼다.

검증: python3 scripts/check-docs.py rc=0(번역한 파일의 language 줄 8개,
number 줄 3개 지움), check-work-docs.py rc=0, --links(gates.md 범위)
깨진 링크 0, unittest discover scripts/tests 43개 통과.
This commit is contained in:
DongHyeonka
2026-11-07 17:07:16 +09:00
parent 03a313ed65
commit c91cc3fb10
13 changed files with 540 additions and 583 deletions
-11
View File
@@ -169,15 +169,7 @@ language src/adapter/outbound/persistence-notification/CLAUDE.md
language src/adapter/outbound/redis-sdk/README.md
language src/adapter/outbound/redis-sdk/compose/README.md
language src/adapter/outbound/support/CLAUDE.md
language src/app-bootstrap/CLAUDE.md
language src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md
language src/application-core/CLAUDE.md
language src/build-logic/README.md
language src/composition/outbox-relay/CLAUDE.md
language src/config/architecture/README.md
language src/domain-core/CLAUDE.md
language src/platforms/optional-build/README.md
language src/shared-contract/CLAUDE.md
# 참조: 지금 트리·registry에 없는 경로. 고치거나 「> 이력」 인용 블록으로 옮기면 지운다.
reference AGENTS.md src/build-tools/
@@ -214,6 +206,3 @@ number src/adapter/outbound/objectstorage/CLAUDE.md Spring Boot 4.0.0
number src/adapter/outbound/persistence-jpa/CLAUDE.md Spring Boot 4.0.0
number src/adapter/outbound/persistence-mongo/CLAUDE.md Spring Boot 4.0.0
number src/adapter/outbound/support/CLAUDE.md Spring Boot 4.0.0
number src/app-bootstrap/CLAUDE.md Spring Boot 4.0.0
number src/domain-core/CLAUDE.md Spring Boot 4.0.0
number src/shared-contract/CLAUDE.md Spring Boot 4.0.0
+99 -106
View File
@@ -1,125 +1,118 @@
# app-bootstrap — application entry point & composition root
# app-bootstrap — 애플리케이션 진입점과 조립 루트
## Registered identity
## 등록 정보
- Module ID: `app-bootstrap`
- Gradle path: `:app-bootstrap`
- Focused test (derived from Gradle path): `./gradlew :app-bootstrap:test --console=plain`
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
- Registry SSOT: `src/config/architecture/modules.json`.
- 모듈 ID: `app-bootstrap`
- Gradle 경로: `:app-bootstrap`
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :app-bootstrap:test --console=plain`
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
- registry 정본: `src/config/architecture/modules.json`.
Package root: `dev.caskeleton.bootstrap`.
패키지 루트: `dev.caskeleton.bootstrap`.
## Responsibility
## 책임
- Spring Boot entrypoint (`CaSkeletonApplication`).
- Runtime settings and logging bootstrap.
- Final cross-module wiring.
- Architecture tests that inspect all modules.
- Spring Boot 진입점(`CaSkeletonApplication`).
- 런타임 설정과 로깅 시작.
- 모듈을 가로지르는 마지막 배선.
- 모든 모듈을 들여다보는 아키텍처 시험.
## Allowed
## 허용
- Runtime leaves explicitly declared by this module's Gradle dependencies and permitted by the
architecture registry. The resolved Gradle runtime graph is the runtime SSOT; do not duplicate a
membership list in metadata.
- Spring Boot startup/runtime dependencies.
- ArchUnit in tests.
- 이 모듈의 Gradle 의존성이 분명히 선언하고 아키텍처 registry가 허용한 런타임 leaf. 해석된 Gradle
runtime 그래프가 런타임의 정본이다. 구성원 목록을 metadata에 다시 적지 않는다.
- Spring Boot 시작·런타임 의존성.
- 시험에서 ArchUnit.
## Forbidden
## 금지
- Concrete business policy.
- Controllers, use cases, repository adapters, or mappers authored directly under bootstrap.
- Settings classes that implement business logic.
- Implementing an `application-core` or `domain-core` port. A class that implements one is an
outbound adapter and belongs in an `adapter/outbound/*` leaf, however its dependencies are
configured — `CompositionRootBoundaryArchitectureTest` enforces this, with no exceptions.
- Raising a startup failure with `throw new IllegalStateException(...)`. Use `StartupFailures`
(`adapter:outbound:support`, package `support.startup`: `envValidation` / `profileMismatch` /
`requiredAdapterDisabled` / `migrationFailed`), so the
failure carries its sysexits exit code and structured log fields —
`StartupFailureContractArchitectureTest` enforces this.
- Answering "is this production?" locally. `dev.caskeleton.shared.runtime.RuntimeEnvironment` owns
the profile vocabulary for the whole repository.
- Depending on `org.testcontainers` from `src/test`. Real-service tests belong to
`src/integrationTest`; see `docs/testing/TESTING_STRATEGY.md`.
- 구체적인 업무 정책.
- bootstrap 아래에 직접 쓴 controller, 유스케이스, repository 어댑터, mapper.
- 업무 로직을 구현하는 설정 클래스.
- `application-core`나 `domain-core` 포트를 구현하기. 포트를 구현하는 클래스는 의존성을 어떻게
설정했든 outbound 어댑터이고 `adapter/outbound/*` leaf에 둔다 —
`CompositionRootBoundaryArchitectureTest`가 예외 없이 강제한다.
- 기동 실패를 `throw new IllegalStateException(...)`으로 내기. `StartupFailures`
(`adapter:outbound:support`, 패키지 `support.startup`: `envValidation` / `profileMismatch` /
`requiredAdapterDisabled` / `migrationFailed`)를 써서 실패가 sysexits 종료 코드와 구조화된 로그
필드를 싣게 한다 — `StartupFailureContractArchitectureTest`가 강제한다.
- 「운영 환경인가?」를 이 모듈 안에서 답하기. 저장소 전체의 profile 어휘는
`dev.caskeleton.shared.runtime.RuntimeEnvironment`가 가진다.
- `src/test`에서 `org.testcontainers`에 의존하기. 실제 서비스를 쓰는 시험은 `src/integrationTest`에
둔다. `docs/testing/TESTING_STRATEGY.md`를 본다.
## Package layout
## 패키지 배치
The rules below exist because their absence is what produced the drift this module was reviewed for
(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). Half the
capabilities lived under `autoconfigure/` and half at the package root; `Settings` classes were split
between a `settings/` package and their feature packages with no stated rule; and the same
decomposition problem was solved two different ways in the same leaf — Notification as nine focused
configurations, Redis as one 376-line class.
아래 규칙은 그것이 없어서 이 모듈의 리뷰 대상이 된 어긋남이 생겼기 때문에 있다
(`docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`). capability의 절반은 `autoconfigure/`
아래, 절반은 패키지 루트에 있었다. `Settings` 클래스는 규칙 없이 `settings/` 패키지와 각 기능
패키지에 나뉘어 있었다. 그리고 같은 분해 문제를 같은 leaf에서 두 가지로 풀었다 — Notification은 작은
설정 아홉 개로, Redis는 376줄 클래스 하나로.
- **A capability's assembly lives in the capability's own module**, registered by that module's
`AutoConfiguration.imports`, with its settings in the module's `config/module-defaults/*.yml`.
JPA (startup guards, Flyway strategy, lock decorator, readiness and full-off handling in
`JpaActivationEnvironmentPostProcessor`) is `adapter:outbound:persistence-jpa`; Redis (readiness) is
`adapter:outbound:cache-redis`; notification is `composition:notification-platform`. Every
capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web,
observability, the cores, support and identifier. This leaf keeps no list of capabilities: no
switch registry, no cross-capability dependency validator, no activation endpoint. Component scan
covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) and support
(`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure/<name>/` is application
composition every application needs: `common` (the clock). The outbox relay, the idempotency
executor and the durable operations (use cases and `/operations` endpoints, 07-08) are
`composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected
by one `runtimeOnly` line each and building nothing until their ports exist. A capability's role→permission mapping ships in its own
`config/module-defaults` file, not in `config/security.yml`. The runtime wiring every composition root needs —
tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization
(`PrivacySettings`) and the actuator chain — is `composition:service-runtime`.
- **`<Capability>Settings` lives beside its capability**, not in `settings/`. The `settings/` package
holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` —
bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record:
`logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values
Logback cannot use.
- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail
exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`).
A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo
connection-source rule, the GraphQL deployment-mode rule) ships with that capability's module, so
it exists exactly when the capability does.
- **The startup failure vocabulary lives in `adapter:outbound:support`** (`support.startup`: phases,
error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`,
`ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on
this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`.
- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations,
and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a
`static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider`
of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each
`RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of
them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/
`@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a
`@ConfigurationProperties` binding — those are created before the post-processors and would stay
unset). A guard that needs another bean stays a bean. A
capability's production secrets are the capability's: its module contributes a
`RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing
which roles exist.
- **capability의 조립은 그 capability 자신의 모듈에 있다.** 그 모듈의 `AutoConfiguration.imports`가
등록하고, 설정은 그 모듈의 `config/module-defaults/*.yml`에 둔다. JPA(기동 guard, Flyway 전략,
lock decorator, readiness, `JpaActivationEnvironmentPostProcessor`의 완전히 끄기 처리)는
`adapter:outbound:persistence-jpa`, Redis(readiness)는 `adapter:outbound:cache-redis`, 알림은
`composition:notification-platform`이다. 모든 capability는 `build.gradle`에서 주석 처리한
`runtimeOnly` 한 줄이다. 기본 조립은 web, 관측, core들, support, identifier다. 이 leaf는 capability
목록을 두지 않는다: 스위치 registry도, capability 사이 의존 검증기도, 켜기 endpoint도 없다.
component scan은 `dev.caskeleton.bootstrap`만 본다. web(`WebAdapterAutoConfiguration`,
`WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`)과 support
(`OutboundSupportConfig`)는 자기 `AutoConfiguration.imports`로 들어온다. `autoconfigure/<name>/`에
남는 것은 모든 애플리케이션에 필요한 애플리케이션 조립인 `common`(시계)뿐이다. outbox relay,
멱등성 executor, durable operation(유스케이스와 `/operations` endpoint, 07-08)은
`composition:outbox-relay`, `composition:idempotency`, `composition:durable-operation`이다. 각각
`runtimeOnly` 한 줄로 고르고, 자기 포트가 생기기 전에는 아무것도 만들지 않는다. capability의
role → permission 대응은 `config/security.yml`이 아니라 그 capability의 `config/module-defaults`
파일에 담긴다. 모든 조립 루트에 필요한 런타임 배선 — tracing, metric 계약 filter, domain-context
전파, 사용자 principal 가명화(`PrivacySettings`), actuator chain — 은 `composition:service-runtime`이다.
- **`<Capability>Settings`는 `settings/`가 아니라 그 capability 옆에 둔다.** `settings/` 패키지는
어느 capability에도 속하지 않는 설정 — `BootstrapSettings`, `RuntimeSafetySettings` — 만 담는다.
이 설정은 `StrictSettingsBinder`로 엄격하게 바인딩하고 scan하지 않는다. 로깅에는 settings record가
없다. `logback-spring.xml`이 `app.logging.*`을 직접 읽고 `LoggingConfigurationRule`이 Logback이 쓸
수 없는 값을 거절한다.
- **`runtime/`은 애플리케이션 자체에 대한 guard를 담는다** — 비밀 값, 숫자 한계, 오류 상세 노출,
여러 인스턴스 조율, runtime profile 검사(`RuntimeEnvironmentProfileValidator`). capability 설정에
대한 guard(JPA OSIV·DDL·pool·TLS·vendor guard, Mongo 연결 출처 규칙, GraphQL 배포 모드 규칙)는 그
capability의 모듈과 함께 나간다. 그래야 capability가 있을 때만 정확히 존재한다.
- **기동 실패 어휘는 `adapter:outbound:support`에 있다**(`support.startup`: phase, 오류 코드, 예외,
`StartupFailures`, `StartupValidationContext`, `StartupOrder`, `ReadinessGroup`, `RuntimeWarnings`).
그래서 capability 모듈은 이 leaf에 의존하지 않고 같은 방식으로 실패한다. `runtime/startup/`에는
`StartupFailureExceptionReporter`만 남는다.
- **환경만 보는 guard는 `StartupRule` bean이다**(`support.startup`). 위반을 돌려주고, 유일한
`StartupRuleRunner`가 다른 singleton이 생기기 전에 그것을 올린다(`Environment`, bean factory, 정적
`RequiredProductionSecrets`의 `ObjectProvider`만 받는 `static` `@Bean` 메서드로 선언한다. 모든
profile에서 runner는 어떤 규칙을 돌리기 전에 규칙마다, 그리고 `RequiredProductionSecrets`마다 하나씩
만든다. 그중 하나가 만드는 다른 bean이 있으면 그 이름을 대며 기동을 실패시킨다. runtime 클래스에
`@Value`/`@Autowired`/`@Inject`/`@Resource` 멤버, `@PostConstruct`/`@PreDestroy` 콜백,
`@ConfigurationProperties` 바인딩이 있는 것도 이름을 대며 실패시킨다 — 그런 것은 post-processor보다
먼저 만들어져 값이 비어 있게 된다). 다른 bean이 필요한 guard는 bean으로 남는다. capability의 운영
비밀 값은 그 capability의 것이다: 그 모듈이 `RequiredProductionSecrets` bean을 내놓고,
`SecretSourceValidator`는 어떤 role이 있는지 모르는 채로 이름을 검사한다.
## Decomposition threshold
## 분해 기준
State it rather than leaving it to taste, because "it felt long enough" is what produced two
different answers for the same question.
취향에 맡기지 않고 적어 둔다. 「충분히 길다고 느꼈다」가 같은 질문에 두 가지 답을 낳았기 때문이다.
- One `@Configuration` holds one assembly concern. Split when it passes roughly **eight `@Bean`
methods**, or as soon as it assembles two unrelated port families — whichever comes first.
- One `@ConfigurationProperties` class owns one capability namespace.
- A capability that needs more than one configuration gets a root class holding its `enabled`
condition, `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan
nothing: `@Import` from a gated root is what keeps `enabled=false` load-bearing rather than advisory.
`cache-redis`'s `capability/RedisCapabilityConfig` is the reference example. Optional adapter
capabilities that own reusable Spring composition publish their own root instead. Notification
uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration` plus
`composition:notification-platform`'s `NotificationApplicationCompositionAutoConfiguration`; JPA uses the
package-private `PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig` and
`startup.JpaStartupAutoConfiguration` from `adapter:outbound:persistence-jpa`, which is not in the
default composition (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` in
`build.gradle`).
Mongo follows the same rule: the persistence-mongo leaf owns MongoRootAutoConfiguration and its internal health bridge; bootstrap owns no Mongo-specific production health configuration.
- Shared helpers of a split capability get their own type named for what they are, not a `*Util`
bucket — `cache-redis`'s `capability/RedisKeys` is the reference.
- `@Configuration` 하나는 조립 관심사 하나를 담는다. 대략 **`@Bean` 메서드 여덟 개**를 넘거나, 서로
관계없는 포트 묶음 둘을 조립하게 되면 — 둘 중 먼저 오는 때에 — 나눈다.
- `@ConfigurationProperties` 클래스 하나는 capability namespace 하나를 가진다.
- 설정이 둘 이상 필요한 capability는 루트 클래스를 둔다. 루트가 `enabled` 조건,
`@EnableConfigurationProperties`, 관심사별 클래스의 `@Import`를 가진다. 아무것도 scan하지 않는다:
조건이 걸린 루트에서 `@Import`해야 `enabled=false`가 권고가 아니라 실제로 끄는 스위치가 된다.
`cache-redis`의 `capability/RedisCapabilityConfig`가 참조 예다. 다시 쓸 Spring 조립을 가진 optional
어댑터 capability는 자기 루트를 내놓는다. 알림은 `adapter:outbound:notification`의
`NotificationPlatformAutoConfiguration`과 `composition:notification-platform`의
`NotificationApplicationCompositionAutoConfiguration`을 쓴다. JPA는
`adapter:outbound:persistence-jpa`의 package-private `PersistenceJpaAutoConfiguration`,
`PersistenceJpaRuntimeConfig`, `startup.JpaStartupAutoConfiguration`을 쓰고, 이 모듈은 기본 조립에
없다(`build.gradle`의 `// runtimeOnly project(':adapter:outbound:persistence-jpa')`).
Mongo도 같은 규칙을 따른다: persistence-mongo leaf가 MongoRootAutoConfiguration과 그 내부 health
bridge를 가지고, bootstrap은 Mongo 전용 운영 health 설정을 가지지 않는다.
- 나눈 capability의 공용 도우미는 `*Util` 바구니가 아니라 하는 일을 이름으로 단 자기 타입을 가진다 —
`cache-redis`의 `capability/RedisKeys`가 참조 예다.
## Test
## 테스트
```bash
cd src
@@ -31,8 +31,8 @@ class TemplatePackageOwnershipDocumentTest {
private static final String RULE_BOOK = "src/application-core/CLAUDE.md";
private static final String REGISTRY = "src/config/architecture/modules.json";
private static final String APPLICATION_TABLE = "| Package (`dev.caskeleton.application.*`) |";
private static final String DOMAIN_TABLE = "| Package (`dev.caskeleton.domain.*`) |";
private static final String APPLICATION_TABLE = "| 패키지 (`dev.caskeleton.application.*`) |";
private static final String DOMAIN_TABLE = "| 패키지 (`dev.caskeleton.domain.*`) |";
private static final Pattern PACKAGE_NAME = Pattern.compile("`([a-z][a-z0-9]*)`");
private final Path root = RepositoryContractResources.fromSystemProperty().repositoryRoot();
@@ -83,7 +83,7 @@ class TemplatePackageOwnershipDocumentTest {
// then
assertThat(missing)
.as(
"packages %s lists are not in the leaf its \"Owning leaf\" column names; a package was"
"packages %s lists are not in the leaf its \"소유 leaf\" column names; a package was"
+ " moved or removed without the table (and TemplatePackageOwnership) following it",
RULE_BOOK)
.isEmpty();
+230 -245
View File
@@ -1,180 +1,173 @@
# application-core — application use cases
# application-core — 애플리케이션 유스케이스
## Registered identity
## 등록 정보
- Module ID: `application-core`
- Gradle path: `:application-core`
- Focused test (derived from Gradle path): `./gradlew :application-core:test --console=plain`
- Runtime baseline: Java 21; repository framework baseline: the Spring Boot 4.x version pinned by the shared version catalog.
- Registry SSOT: `src/config/architecture/modules.json`.
- 모듈 ID: `application-core`
- Gradle 경로: `:application-core`
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :application-core:test --console=plain`
- 실행 기준: Java 21. 프레임워크 기준은 공용 버전 카탈로그(`src/gradle/libs.versions.toml`)가 고정한 Spring Boot 4.x다.
- registry 정본: `src/config/architecture/modules.json`.
Package root: `dev.caskeleton.application`.
패키지 루트: `dev.caskeleton.application`.
코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT).
## Responsibility
## 책임 (Responsibility)
- Use case inbound ports (`CommandUseCase`, `QueryUseCase`) and their command / query contracts.
- Outbound ports (`*Port` interfaces) the use cases depend on.
- Application exceptions and policy types.
- Coordinate domain models through ports.
- Own application transaction boundaries through the `TransactionPort` abstraction.
- Expose framework-free invocation context through ports such as `CorrelationIdPort`; adapters own
MDC or other concrete storage.
- Own the framework-free semantic integration-event draft, validated-event value contract and
exact typed payload contribution SPI. This is the messaging semantic contract R1 boundary only.
- 유스케이스 inbound 포트(`CommandUseCase`, `QueryUseCase`)와 그 command·query 계약.
- 유스케이스가 의존하는 outbound 포트(`*Port` 인터페이스).
- 애플리케이션 예외와 정책 타입.
- 포트를 거쳐 도메인 모델을 조율한다.
- `TransactionPort` 추상화로 애플리케이션 트랜잭션 경계를 가진다.
- `CorrelationIdPort` 같은 포트로 프레임워크 없는 호출 문맥을 내놓는다. MDC 같은 실제 저장소는
어댑터가 가진다.
- 프레임워크 없는 integration event 초안(semantic draft), 검증된 이벤트의 값 계약, 정확한 타입의
payload를 내놓는 SPI를 가진다. 메시징 semantic contract R1 경계까지만이다.
## Allowed
## 허용
- `:domain-core`
- `:shared-contract`
- Java standard library types.
- Java 표준 라이브러리 타입.
## Forbidden
## 금지 (Forbidden)
- `adapter-*` implementation classes.
- `adapter-*` 구현 클래스.
- `app-bootstrap`.
- Controller request/response DTOs.
- JPA entities and Spring Data repositories.
- HTTP status, transport types (`org.springframework.web..`).
- `org.springframework.transaction.annotation.Transactional` (use `TransactionPort` instead).
- `org.springframework.context.ApplicationContext` — direct dependency forbidden
(`getBean(Class)` reflection-style bypass blocked by the ArchUnit rule `application_does_not_depend_on_application_context`). String-key
bean lookup / `Class.forName(String)` / `BeanFactory#getBeansOfType` remain
ArchUnit's static-analysis blind spot — guard via code review checklist.
- Lombok (`lombok..`) — also forbidden in `domain-core`. Within `application-core`,
Lombok is currently not in scope for the contract; if you intend to use it,
weigh the bytecode opacity cost first.
- Persistence-layer transaction annotations of any kind inside this module.
- Diagnostic frameworks (`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). Express
diagnostic intent through a specific outbound `*Port`; adapters own rendering.
- Messaging provider/runtime types: physical topic, Kafka record or metadata, JSON tree/raw JSON
payload, serializer/schema-validator implementation, security topology and publication epoch.
- controller의 요청·응답 DTO.
- JPA 엔티티와 Spring Data repository.
- HTTP 상태, 전송 타입(`org.springframework.web..`).
- `org.springframework.transaction.annotation.Transactional`(대신 `TransactionPort`를 쓴다).
- `org.springframework.context.ApplicationContext` — 직접 의존 금지
(`getBean(Class)` 같은 리플렉션식 우회는 ArchUnit 규칙 `application_does_not_depend_on_application_context`가 막는다). 문자열 키로
bean을 찾기, `Class.forName(String)`, `BeanFactory#getBeansOfType`은 ArchUnit 정적 분석이
보지 못하는 곳이다. 코드 리뷰 체크리스트로 막는다.
- Lombok(`lombok..`) — `domain-core`에서도 금지다. `application-core`에서는 지금 Lombok이
계약 범위에 없다. 쓰려면 바이트코드가 불투명해지는 비용을 먼저 따진다.
- 이 모듈 안의 영속 계층 트랜잭션 애너테이션은 종류를 가리지 않고 금지다.
- 진단 프레임워크(`org.slf4j`, `java.util.logging`, Logback, Log4j, Micrometer). 진단 의도는
전용 outbound `*Port`로 나타내고, 어떻게 남길지는 어댑터가 정한다.
- 메시징 provider·런타임 타입: 물리 topic, Kafka record나 metadata, JSON tree·raw JSON payload,
serializer·schema validator 구현, 보안 토폴로지, publication epoch.
## Contract types
## 계약 타입
| Type | Purpose |
| 타입 | 용도 |
|---|---|
| `usecase.UseCase<I, O>` | Base type for inbound ports. Concrete inbound ports MUST extend `CommandUseCase` or `QueryUseCase`. |
| `usecase.CommandUseCase<C extends Command, R>` | Inbound port for write use cases. Implementations MUST be annotated `@UseCaseCapability`. |
| `usecase.QueryUseCase<Q extends Query, R>` | Inbound port for read-only use cases. Implementations MUST declare `transactionMode = READ_ONLY` and `repositoryAccess = READ_REPOSITORY`. |
| `command.Command` | Marker for write intents. Plain immutable types built from domain values. |
| `query.Query` | Marker for read intents. Plain immutable types built from domain values. |
| `transaction.TransactionPort` | Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by `adapter-persistence`. |
| `secret.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. |
| `transaction.NestedRootTransactionRejectedException` | Fail-fast signal raised before action/provider side effects when `inRootWrite` detects an actual ambient transaction. |
| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED` and `NEVER` are intentionally absent. |
| `transaction.Isolation` | `READ_COMMITTED` (pinned default) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED` is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through `TransactionPort` is a `planned` joint change with `feature-application-port-usecase-contract`; the shipped call path pins `READ_COMMITTED`. |
| `capability.UseCaseCapability` | Mandatory annotation on every concrete use case: declares `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`. |
| `usecase.UseCase<I, O>` | inbound 포트의 기반 타입. 구체 inbound 포트는 반드시 `CommandUseCase`나 `QueryUseCase`를 상속한다. |
| `usecase.CommandUseCase<C extends Command, R>` | 쓰기 유스케이스의 inbound 포트. 구현은 반드시 `@UseCaseCapability`를 단다. |
| `usecase.QueryUseCase<Q extends Query, R>` | 읽기 전용 유스케이스의 inbound 포트. 구현은 반드시 `transactionMode = READ_ONLY`와 `repositoryAccess = READ_REPOSITORY`를 선언한다. |
| `command.Command` | 쓰기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. |
| `query.Query` | 읽기 의도의 표지. 도메인 값으로 만든 평범한 불변 타입이다. |
| `transaction.TransactionPort` | 합류할 수 있는 쓰기·읽기, 물리 루트에서만 하는 쓰기, 독립 쓰기 경계를 내놓는 outbound 포트. `adapter:outbound:persistence-jpa`의 `SpringTransaction`이 구현한다. |
| `secret.SecretSourcePort` | 프레임워크 없는 outbound 비밀 해석 이음매. 배포가 app-bootstrap에서 backend를 고른다. 실제 환경 변수·클라우드·vault 리더는 outbound 어댑터 leaf에 둔다. |
| `transaction.NestedRootTransactionRejectedException` | `inRootWrite`가 실제로 열린 바깥 트랜잭션을 찾았을 때, action이나 provider 부작용 전에 바로 던지는 실패 신호. |
| `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED`와 `NEVER`는 일부러 없다. |
| `transaction.Isolation` | `READ_COMMITTED`(고정 기본값) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED`는 금지다(선언하지 않았다). vendor 기본값은 쓰지 않는다(엔진마다 기본값이 다르다 — PostgreSQL은 READ COMMITTED, MySQL InnoDB는 REPEATABLE READ). 더 엄격한 수준을 `TransactionPort`로 넘기는 일은 `feature-application-port-usecase-contract`와 함께 바꿀 `planned` 항목이다. 지금 호출 경로는 `READ_COMMITTED`로 고정한다. |
| `capability.UseCaseCapability` | 모든 구체 유스케이스에 반드시 다는 애너테이션: `transactionMode`, `idempotency`, `repositoryAccess`, `externalOutboundAllowed`를 선언한다. |
| `capability.Idempotency` | `IDEMPOTENT` / `KEYED` / `NOT_IDEMPOTENT`. |
| `capability.RepositoryAccess` | `NONE` / `READ_REPOSITORY` / `WRITE_REPOSITORY`. |
| `messaging.contract.IntegrationEventContractContribution<P>` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. |
| `messaging.event.IntegrationEventDraft<P>` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through `IntegrationEventDrafts` (`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). |
| `messaging.event.IntegrationEventDrafts` | The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), `SINGLE_TENANT_SCOPE` for a feature without tenants. |
| `messaging.event.IntegrationIdentity` | The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with `isCanonical(value, bound)`; never copy the pattern. |
| `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. |
| `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). |
| `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. |
| `tenant.TenantId` | The tenant identifier and its one grammar (`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`); the web and GraphQL transport contexts both carry it. Built by a transport from verified authentication data only. |
| `messaging.contract.IntegrationEventContractContribution<P>` | 닫힌 정확한 record payload 타입, 정해진 component 순서, 로컬 schema identity·hash, provider 중립 descriptor 기여. |
| `messaging.event.IntegrationEventDraft<P>` | 로컬 인코딩 전의 타입 있는 semantic 이벤트. JSON·Kafka·영속 상태가 아니다. `IntegrationEventDrafts`로만 만든다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). |
| `messaging.event.IntegrationEventDrafts` | 기능이 초안을 만드는 유일한 길: contract id·version·destination은 contract에서, correlation은 요청 값이 정규형이면 그 값(아니면 event id), 테넌트가 없는 기능은 `SINGLE_TENANT_SCOPE`. |
| `messaging.event.IntegrationIdentity` | event id, correlation·causation id, aggregate id의 유일한 문법과 길이 한계. 값은 `isCanonical(value, bound)`로 시험한다. 패턴을 복사하지 않는다. |
| `messaging.event.ValidatedIntegrationEvent` | 안정된 semantic identity와 바뀌지 않는 정확한 인코딩 바이트·hash. 뒤의 durable append 경계로 넘길 준비가 된 값이다. |
| `messaging.event.IntegrationEventEncoderPort` | 프레임워크 없는 로컬 경계(초안 → 검증된 이벤트). outbound 어댑터가 구현한다(템플릿은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`). |
| `outbox.OutboxAppendPort` | 유일한 outbox append: `ValidatedIntegrationEvent` 하나를 호출자의 쓰기 트랜잭션 안에서 넣는다. |
| `tenant.TenantId` | 테넌트 식별자와 그 유일한 문법(`[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`). web과 GraphQL 전송 문맥이 모두 이 값을 싣는다. 전송 계층이 검증된 인증 데이터로만 만든다. |
## Notification (NOTIF-ADR-005)
## 알림 (NOTIF-ADR-005)
None of the notification types are in this leaf. `..notification.platform..` and the simple
`NotificationPort`, `Notification` and `NotificationChannel` directly under
`dev.caskeleton.application.notification` all belong to leaf `application-notification`; the shared
package prefix is the only link. The R1 orchestration types were removed on 2026-09-25.
알림 타입은 이 leaf에 하나도 없다. `..notification.platform..`과
`dev.caskeleton.application.notification` 바로 아래의 단순한 `NotificationPort`, `Notification`,
`NotificationChannel`은 모두 leaf `application-notification`의 것이다. 패키지 접두어가 같은 것이
유일한 연결이다. R1 조율 타입은 2026-09-25에 지웠다.
## Naming convention
## 이름 규칙 (Naming convention)
This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap
architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks
them against this table. A new feature follows the "new code" column; the "existing exceptions" are
named so nobody copies them by accident.
이 절이 저장소의 이름 규칙 정본이다. 기계로 볼 수 있는 행은 `NamingConventionTest`(app-bootstrap
architectureTest)가 강제한다. 나머지는 리뷰 규칙이고, 리뷰가 이 표와 대조한다. 새 기능은 「새 코드」
열을 따른다. 「이미 있는 예외」는 누가 실수로 따라 하지 않게 이름을 적어 둔 것이다.
| Role | Name | Where | Existing exceptions (do not copy) |
| 역할 | 이름 | 위치 | 이미 있는 예외(따라 하지 않는다) |
|---|---|---|---|
| Use case (inbound port implementation) | `<Verb><Noun>UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) |
| Command / query record | `*Command` / `*Query` | next to its use case | — |
| Aggregate persistence (stores and returns whole aggregates) | `<Aggregate>Repository` | **domain** package of the aggregate, owned by the domain | — |
| Technical store the application owns (outbox, idempotency, operation rows) | `<Thing>StorePort` | application package | `*WritePort` (old onboarding fixture, removed) |
| Read model that returns projections, not aggregates | `<Thing>QueryPort` | application package; returns projections only (ArchUnit) | — |
| Any other outbound port | `<Capability>Port` | application package | — |
| Server-assigned id generation | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain package; the id record `implements ResourceId<Self>` | `OutboxEventIdFactory` (sample; event ids are not resource ids) |
| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — |
| Throwable | `*Exception`, enforced by ArchUnit | — | — |
| Contract test kit for a port | abstract `<Port>Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now |
| 유스케이스(inbound 포트 구현) | `<Verb><Noun>UseCase`, ArchUnit이 강제 | 기능의 `application` 패키지 | `*ApplicationUseCase`(application-fileserver, application-notification), `*Service`(notification, fileserver) |
| command·query record | `*Command` / `*Query` | 그 유스케이스 옆 | — |
| aggregate 영속(aggregate 전체를 저장하고 돌려준다) | `<Aggregate>Repository` | aggregate의 **domain** 패키지, 도메인이 가진다 | — |
| 애플리케이션이 가진 기술 저장소(outbox, 멱등성, operation 행) | `<Thing>StorePort` | application 패키지 | `*WritePort`(옛 onboarding fixture, 지움) |
| aggregate가 아니라 projection을 돌려주는 읽기 모델 | `<Thing>QueryPort` | application 패키지. projection만 돌려준다(ArchUnit) | — |
| 그 밖의 outbound 포트 | `<Capability>Port` | application 패키지 | — |
| 서버가 정하는 id 생성 | `<Aggregate>IdFactory extends IdFactory<<Aggregate>Id>` | domain 패키지. id record는 `implements ResourceId<Self>` | `OutboxEventIdFactory`(샘플. event id는 resource id가 아니다) |
| 설정 바인딩 | `*Settings`(운영) 또는 `*Policy`(인가·도메인 정책), ArchUnit이 강제 | 그것을 바인딩하는 leaf | — |
| Throwable | `*Exception`, ArchUnit이 강제 | — | — |
| 포트의 계약 시험 키트 | 포트 소유자의 testFixtures에 둔 추상 `<Port>Contract`. fake의 시험과 각 어댑터의 시험이 상속한다 | testFixtures | 값 타입 시험의 이름이 한때 `*ContractTest`였다. 지금은 `*ValueTypesTest`다 |
The one-line rule for stores: **if the domain would recognise the thing it stores, it is a
`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the
application.**
저장소의 한 줄 규칙: **도메인이 알아볼 만한 것을 저장하면 도메인의 `Repository`다. 애플리케이션에
필요한 배관이면 application의 `StorePort`다.**
## Package ownership
## 패키지 소유 (Package ownership)
This section is the rule book for **which packages the template owns** and where a business feature
goes. `docs/manual/03-placement.md` points here.
이 절은 **템플릿이 어떤 패키지를 가지는지**와 업무 기능이 어디로 가는지의 정본이다.
`docs/manual/03-placement.md`가 이곳을 가리킨다.
- A business feature is `dev.caskeleton.application.<feature>` (and `dev.caskeleton.domain.<feature>`,
`...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`): one package per feature
directly under each root, no `command`/`usecase`/`port` sub-packages.
- `<feature>` is **not** one of the template package names below. A feature beside a template
package of the same name lands in the same package tree, and every upstream template update merges
into it.
- Template packages never import a feature package. Business code does not go into a template
package, even when the name fits.
- Everything under the two roots that is not listed here is a feature. A derived service adds
features without editing this list; the template edits it when it adds, renames or removes one of
its own packages.
- 업무 기능은 `dev.caskeleton.application.<feature>`다(그리고 `dev.caskeleton.domain.<feature>`,
`...adapter.inbound.web.<feature>`, `...bootstrap.autoconfigure.<feature>`). 루트마다 바로 아래에
기능 하나당 패키지 하나를 두고, `command`·`usecase`·`port` 하위 패키지를 두지 않는다.
- `<feature>`는 아래 템플릿 패키지 이름 중 하나가 **아니다**. 같은 이름의 템플릿 패키지 옆에 둔
기능은 같은 패키지 트리에 들어가고, upstream 템플릿 갱신이 올 때마다 그 기능에 섞여 들어간다.
- 템플릿 패키지는 기능 패키지를 import하지 않는다. 이름이 맞아도 업무 코드를 템플릿 패키지에 넣지
않는다.
- 두 루트 아래에서 여기 적히지 않은 것은 모두 기능이다. 파생 서비스는 이 목록을 고치지 않고 기능을
더한다. 템플릿은 자기 패키지를 더하거나, 이름을 바꾸거나, 지울 때 이 목록을 고친다.
| Package (`dev.caskeleton.application.*`) | Owning leaf | Holds |
| 패키지 (`dev.caskeleton.application.*`) | 소유 leaf | 담는 것 |
|---|---|---|
| `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers |
| `capability` | application-core | `@UseCaseCapability` and its enums |
| `transaction` | application-core | `TransactionPort` and its modes |
| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` |
| `usecase`, `command`, `query` | application-core | inbound 포트 기반 타입과 command·query 표지 |
| `capability` | application-core | `@UseCaseCapability`와 그 enum |
| `transaction` | application-core | `TransactionPort`와 그 모드 |
| `security` | application-core | 인가 포트, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` |
| `tenant` | application-core | `TenantId` |
| `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` |
| `secret` | application-core | `SecretSourcePort`, `SecretReference` |
| `messaging` | application-core | the integration-event semantic contract |
| `outbox` | application-core | transactional outbox append and relay |
| `idempotency` | application-core | keyed idempotency executor and store port |
| `operation` | application-core | durable (long-running) operations |
| `lease`, `lock` | application-core | distributed lease and lock ports |
| `cache` | application-core | cache region port |
| `realtime` | application-core | live event replay port |
| `notification` | application-notification | notification capability |
| `fileserver` | application-fileserver | file server capability |
| `objectstorage` | application-objectstorage | object storage capability (its `content.CallBudget` is the call deadline it carries) |
| `messaging` | application-core | integration event semantic contract |
| `outbox` | application-core | 트랜잭션 outbox append와 relay |
| `idempotency` | application-core | 키 기반 멱등성 executor와 store 포트 |
| `operation` | application-core | durable(오래 걸리는) operation |
| `lease`, `lock` | application-core | 분산 lease·lock 포트 |
| `cache` | application-core | cache region 포트 |
| `realtime` | application-core | live event 재생 포트 |
| `notification` | application-notification | 알림 capability |
| `fileserver` | application-fileserver | 파일 서버 capability |
| `objectstorage` | application-objectstorage | 오브젝트 스토리지 capability(`content.CallBudget`은 그것이 싣는 호출 기한이다) |
| Package (`dev.caskeleton.domain.*`) | Owning leaf | Holds |
| 패키지 (`dev.caskeleton.domain.*`) | 소유 leaf | 담는 것 |
|---|---|---|
| `identifier` | domain-core | `ResourceId`, `IdFactory` |
| `stereotype` | domain-core | `@AggregateRoot`, `@DomainEvent`, `@ValueObject` |
Enforcement:
강제하는 곳:
- `scripts/new-feature.sh` refuses a feature name that is already a package under any of the five
roots, in any leaf — every template package included.
- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: a feature package
under either root does not take a name from these tables. Every feature has a domain package, so a
feature named `operation` is caught at `dev.caskeleton.domain.operation`.
- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: a feature class written
into a template package keeps the template's name but imports its own domain, and that import is
what fails.
- These tables are the rule book; the machine copy the rules read is `TemplatePackageOwnership`
(app-bootstrap `src/test`, so both the architecture suite and the document-contract lane see it).
`TemplatePackageOwnershipDocumentTest` (document-contract lane, `mainCheck`) fails when the tables
and that class differ in a package name or owning leaf, or when a listed package is not in the
leaf the table names; `TemplatePackageOwnershipRuleTest` (architectureTest) fails when a listed
name exists in no production class. A new template package joins both in the same change.
- Not caught: a new template package that nobody lists. Features are generated into the same leaves
(`scripts/new-feature.sh`), so an unlisted package is indistinguishable from a feature. Listing it
is part of adding it.
- Rejected alternatives: allowing only the listed top-level packages (every derived feature would
have to edit the template's list — a merge conflict per feature), and a separate
`application-platform` leaf for the platform packages (weighed in the 2026-11-01 maturity review: clearer
boundary, but more registry edges than a naming rule needs).
- `scripts/new-feature.sh`는 다섯 루트 중 어디든, 어느 leaf든 이미 패키지로 있는 기능 이름을
거절한다. 템플릿 패키지도 모두 여기 걸린다.
- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: 두 루트 아래의 기능
패키지는 이 표의 이름을 쓰지 않는다. 기능마다 domain 패키지가 있으므로 `operation`이라는 기능은
`dev.caskeleton.domain.operation`에서 걸린다.
- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: 템플릿 패키지 안에 쓴
기능 클래스는 템플릿 이름을 지니지만 자기 도메인을 import한다. 실패하는 것은 그 import다.
- 이 표가 정본이다. 규칙이 읽는 기계용 사본은 `TemplatePackageOwnership`이다(app-bootstrap
`src/test`에 있어서 architecture suite와 document-contract lane이 모두 본다).
`TemplatePackageOwnershipDocumentTest`(document-contract lane, `mainCheck`)는 표와 그 클래스의
패키지 이름이나 소유 leaf가 다르거나, 표에 적힌 패키지가 표가 말한 leaf에 없으면 실패한다.
`TemplatePackageOwnershipRuleTest`(architectureTest)는 적힌 이름이 운영 클래스 어디에도 없으면
실패한다. 새 템플릿 패키지는 같은 변경에서 둘 모두에 들어간다.
- 못 잡는 것: 아무도 적지 않은 새 템플릿 패키지. 기능은 같은 leaf에 생성되므로
(`scripts/new-feature.sh`) 적히지 않은 패키지는 기능과 구별되지 않는다. 적는 것까지가 패키지를
더하는 일이다.
- 버린 대안: 적힌 최상위 패키지만 허용하기(파생 기능마다 템플릿 목록을 고쳐야 한다 — 기능마다
병합 충돌이 난다), 플랫폼 패키지용 `application-platform` leaf를 따로 두기(2026-11-01 성숙도
리뷰에서 따졌다: 경계는 더 분명하지만, 이름 규칙에 필요한 것보다 registry edge가 많아진다).
## Canonical use case shape
## 정해진 유스케이스 모양 (Canonical use case shape)
```java
@RequiresPermission("user:register")
@@ -201,135 +194,127 @@ public class RegisterUserUseCase implements CommandUseCase<RegisterUserCommand,
}
```
The class is plain Java. A composition root constructs it with its ports and configuration values;
application-core never self-registers with a DI framework. It is **not final**: a mutating use case
declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot
subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the
same reason — a use case built with `new` is never checked. A use case only the system calls (a
scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a
permission and is not a bean: it is a write with no permission check, so no user request may reach
it. Its system caller constructs it — a composition module for a scheduler, a
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..`, or a
`@SystemCaller` scheduled job in the service's own `..adapter.inbound.scheduler..` package. Manual
07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is
enforced — a `@SystemInvoked` bean fails startup, an inbound adapter that depends on one without
being a `@SystemCaller` fails `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`,
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` keeps the mark (and classes nested in a marked
one) off user transports, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` keeps a user transport
from calling a system caller (by its class or by a project interface it implements), and
`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` keeps a system caller from being a `Runnable` or any
other type outside the project, which no dependency rule could follow. Paths that name no type (a
bean looked up by name, a function a configuration hands over) are not seen; manual 07 lists them
and what holds them. A composition with `@RequiresPermission`
beans but no enforcing advisor fails startup too (`composition:service-runtime`
`PermissionEnforcementGuard`, both checks).
이 클래스는 평범한 Java다. 조립 루트가 포트와 설정 값을 넣어 만든다. application-core는 DI
프레임워크에 스스로 등록하지 않는다. 클래스는 **final이 아니다**: 상태를 바꾸는 유스케이스는
`@RequiresPermission`을 선언하고, web 어댑터는 CGLIB proxy로 그것을 강제하는데, CGLIB는 final
클래스를 상속하지 못한다(`RequiresPermissionProxyabilityTest`). 같은 이유로 bean으로 등록한다.
`new`로 만든 유스케이스는 검사를 받지 않는다. 시스템만 부르는 유스케이스(스케줄러, relay, 메시지
소비자)는 권한 대신 `@SystemInvoked(reason = ...)`를 달고 bean이 아니다. 권한 검사가 없는 쓰기라서
사용자 요청이 닿으면 안 되기 때문이다. 그 시스템 호출자가 유스케이스를 만든다: 스케줄러는 조립
모듈, 메시지 핸들러는 `..adapter.inbound.messaging..` 안의 `@SystemCaller(reason = ...)`, 예약
작업은 서비스 자신의 `..adapter.inbound.scheduler..` 패키지 안의 `@SystemCaller`다. 이 셋과 각각의
위치는 `docs/manual/07-authorization.md` 「시스템이 부르는 쓰기」가 정본 목록이다. 모두 강제된다:
`@SystemInvoked` bean은 기동에 실패한다. `@SystemCaller`가 아닌 inbound 어댑터가 그 유스케이스에
의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 실패한다.
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`는 그 표지(그리고 표지가 붙은 클래스 안에 든
클래스)를 사용자 전송 계층에 두지 못하게 한다. `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`는 사용자
전송 계층이 시스템 호출자를 부르지 못하게 한다(그 클래스로든, 그것이 구현한 프로젝트 인터페이스로든).
`SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`는 시스템 호출자가 `Runnable`이나 프로젝트 밖의 다른
타입이 되지 못하게 한다. 그런 타입은 어떤 의존 규칙도 따라가지 못한다. 타입 이름이 드러나지 않는
경로(이름으로 찾는 bean, 설정이 넘겨주는 함수)는 보지 못한다. 매뉴얼 07장이 그 경로와 그것을 막는
곳을 적는다. `@RequiresPermission` bean이 있는데 강제할 advisor가 없는 조립도 기동에 실패한다
(`composition:service-runtime`의 `PermissionEnforcementGuard`, 두 검사 모두).
## Allowed transactional shapes
## 허용하는 트랜잭션 모양 (Allowed transactional shapes)
| Use case shape | `transactionMode` | TransactionPort call | When |
| 유스케이스 모양 | `transactionMode` | TransactionPort 호출 | 언제 |
|---|---|---|---|
| Write command | `WRITE` | `tx.inWrite(...)` | Default for `CommandUseCase`. |
| Physical-root write command | `WRITE` | `tx.inRootWrite(...)` | Only when orchestration must prove there is no ambient transaction and expose a result after commit. |
| Read-only query | `READ_ONLY` | `tx.inRead(...)` | Default for `QueryUseCase`. |
| Outbox / audit / compensation | `REQUIRES_NEW` | `tx.inNew(...)` | Only when the use case MUST commit independently of the caller. |
| 쓰기 command | `WRITE` | `tx.inWrite(...)` | `CommandUseCase`의 기본. |
| 물리 루트 쓰기 command | `WRITE` | `tx.inRootWrite(...)` | 바깥 트랜잭션이 없음을 증명하고 커밋 뒤에 결과를 내놓아야 하는 조율일 때만. |
| 읽기 전용 query | `READ_ONLY` | `tx.inRead(...)` | `QueryUseCase`의 기본. |
| outbox·감사·보상 | `REQUIRES_NEW` | `tx.inNew(...)` | 유스케이스가 반드시 호출자와 따로 커밋해야 할 때만. |
`NESTED` and `NEVER` propagation are forbidden.
`inRootWrite` MUST reject an actual ambient transaction before invoking its action or
`PlatformTransactionManager`; it MUST NOT emulate root-only behavior with `REQUIRES_NEW`.
Both `inWrite` and `inRootWrite` satisfy the direct boundary fitness rule for a
`WRITE_REPOSITORY + WRITE` use case. READ and REQUIRES_NEW mappings remain exclusive.
`NESTED`와 `NEVER` 전파는 금지다.
`inRootWrite`는 action이나 `PlatformTransactionManager`를 부르기 전에 실제로 열린 바깥 트랜잭션을
반드시 거절한다. 루트 전용 동작을 `REQUIRES_NEW`로 흉내 내면 안 된다.
`WRITE_REPOSITORY + WRITE` 유스케이스의 직접 경계 적합성 규칙은 `inWrite`와 `inRootWrite`가 모두
만족한다. READ와 REQUIRES_NEW의 대응은 계속 서로 배타적이다.
### Callback signature contract
### 콜백 시그니처 계약
`TransactionPort` callbacks are `Supplier<T>` / `Runnable` and cannot throw checked
exceptions. This matches Spring's `TransactionCallback<T>` constraint. Wrap domain
checked exceptions into `RuntimeException` subclasses
(`DomainException extends RuntimeException`); `IOException` → `UncheckedIOException`;
`SQLException` is auto-translated by Spring's `DataAccessException` hierarchy.
`TransactionPort` 콜백은 `Supplier<T>` / `Runnable`이라 checked 예외를 던지지 못한다. Spring
`TransactionCallback<T>`의 제약과 같다. 도메인의 checked 예외는 `RuntimeException` 하위 클래스로
감싼다(`DomainException extends RuntimeException`). `IOException`은 `UncheckedIOException`으로
감싼다. `SQLException`은 Spring의 `DataAccessException` 계층이 자동으로 번역한다.
### `inNew` pool-sizing constraint
### `inNew` 풀 크기 제약
`inNew` acquires a new physical JDBC connection. Pool size MUST satisfy:
`inNew`는 새 물리 JDBC 연결을 얻는다. 풀 크기는 반드시 다음을 만족한다.
```
hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1
```
**Forbidden**: calling `tx.inNew(...)` inside a loop over many records — pool
exhaustion + deadlock risk. Batch records inside ONE `inNew` call, or move the
loop outside the transaction boundary.
**금지**: 많은 레코드를 도는 반복문 안에서 `tx.inNew(...)`를 부른다 — 풀이 바닥나고 교착이 생길
수 있다. 레코드를 `inNew` 호출 **하나** 안에서 묶어 처리하거나, 반복문을 트랜잭션 경계 밖으로 뺀다.
## Idempotency (KEYED) — feature-rate-limit-idempotency-contract
## 멱등성 (KEYED) — feature-rate-limit-idempotency-contract
`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps
its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe
generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
`@UseCaseCapability(idempotency = Idempotency.KEYED)`는 **지원한다**. KEYED 유스케이스는 자기 일을
`dev.caskeleton.application.idempotency.IdempotencyExecutor`로 감싼다. 소유자를 안전하게 지키는
유일한 세대다. V1 `IdempotencyScope`/`tryBegin` API는 없어졌다.
- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of
principal + client key + operation code, computed before the executor sees it. The raw
`Idempotency-Key` never reaches this layer or the store.
- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with
`app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` →
`persistence-jpa`; default `disabled`). In-memory prod storage is forbidden.
- **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from
`IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h and not
shorter than the lease, failure retention 24h and not shorter than the replay TTL). Do not
construct it in a use case or a service's own config.
- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` /
`EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409
`IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`;
`IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store
could not prove the outcome, so do not blindly retry.
- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never
takes it over; only a claim that never started or a retryable failure is taken over. The answer
leaves the record to its holder: the holder's first late `complete`/`markFailed` is recorded, a
lease that ran out is not renewed and a claim whose lease ran out is not started — both answer
`LEASE_EXPIRED`, not `NOT_OWNER`, and the executor turns a refused start into "not applied"
(owner decision 2026-11-04). A record lives for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on
real servers; the in-memory fake models no time, so it runs only the contract's time-free cases.
- Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`).
Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that
brings the owner token under another operation (owner decision 2026-11-06).
- A transition already applied is confirmed ("already …") only to the handle it was applied from —
the record one revision past it, moved there by that kind of transition. Any other handle is
`NOT_OWNER`, the same attempt's handle from before a takeover included, and so is a start through
the handle a renewal was applied from; a start through a released handle is `ABSENT` or
`NOT_OWNER` by whether the store keeps the released record (owner decision 2026-11-06,
- **범위(scope)**: 호출자가 `IdempotencyScopeDigest`를 넘긴다. principal + client key + operation
code의 버전 있는 HMAC이고, executor가 받기 전에 계산한다. 원본 `Idempotency-Key`는 이 계층에도
store에도 닿지 않는다.
- **store**: `IdempotencyStorePort`. `app.capabilities.idempotency.provider`로 고른 provider 정확히
하나가 내놓는다(`redis` → `cache-redis`, `postgresql` → `persistence-jpa`, 기본값 `disabled`).
운영에서 메모리 저장소는 금지다.
- **executor**: `composition:idempotency`의 `IdempotencyAutoConfiguration`이 `IdempotencySettings`로
한 번 만든다(처리 lease 30s, 재생 TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h이고 lease보다 짧지 않다, 실패
보존 24h이고 재생 TTL보다 짧지 않다). 유스케이스나 서비스 자신의 설정에서 만들지 않는다.
- action은 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)을
돌려준다. 던진 예외는 효과를 모름(effect-unknown)으로 센다. 처리 중이면 409
`IDEMPOTENT_IN_FLIGHT`, fingerprint(SHA-256)가 다르면 422 `IDEMPOTENT_REQUEST_MISMATCH`다.
`IdempotencyUnavailableException`과 `IdempotencyRecoveryRequiredException`은 store가 결과를
증명하지 못했다는 뜻이니 무턱대고 다시 시도하지 않는다.
- 모든 store는 처리 lease가 끝난 실행에 `RecoveryRequired`로 답하고 그 실행을 넘겨받지 않는다.
넘겨받는 것은 시작하지 않은 claim이나 다시 시도할 수 있는 실패뿐이다. 이 답은 레코드를 가진
쪽에게 남긴다: 가진 쪽이 늦게 보낸 첫 `complete`/`markFailed`는 기록한다. lease가 끝난 것은
갱신하지 않고, lease가 끝난 claim은 시작하지 않는다. 둘 다 `NOT_OWNER`가 아니라 `LEASE_EXPIRED`로
답하고, executor는 거절된 시작을 「적용 안 됨」으로 바꾼다(소유자 결정 2026-11-04). 레코드는
lease에 재생 TTL을 더한 만큼 산다. `IdempotencyStoreContract`가 Redis와 PostgreSQL을 실제 서버에서
둘 모두에 맞춘다. 메모리 fake는 시간을 모델링하지 않으니 계약 중 시간이 없는 경우만 돈다.
- 모든 전이는 그 레코드를 claim한 operation을 이름으로 댄다(`IdempotencyOwner.claimOperationId()`).
다른 operation이면 모든 store에서 `OPERATION_CONFLICT`이고 아무것도 바꾸지 않는다. owner token을
다른 operation으로 가져온 조회도 같다(소유자 결정 2026-11-06).
- 이미 적용된 전이는 그것을 적용한 handle에게만 「already …」로 확인해 준다. 그 handle은 그 전이로
옮겨 간, 한 revision 뒤의 레코드다. 다른 handle은 모두 `NOT_OWNER`다. 넘겨받기 전의 같은 시도의
handle도, 갱신을 적용한 handle로 하는 시작도 그렇다. 놓아준 handle로 하는 시작은 store가 놓아준
레코드를 남기느냐에 따라 `ABSENT`나 `NOT_OWNER`다(소유자 결정 2026-11-06,
`IdempotencyStoreContract`).
- The applying handle resending `markFailed` with another disposition is `OPERATION_CONFLICT` and
the recorded failure stays; with only another retention it is `ALREADY_MARKED_SAME_OPERATION` and
the first retention stays — retention, like a completion's replay TTL, is not compared (owner
decision 2026-11-07).
- 적용한 handle이 다른 disposition으로 `markFailed`를 다시 보내면 `OPERATION_CONFLICT`이고 기록된
실패가 남는다. retention만 다르면 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다 —
retention은 완료의 재생 TTL처럼 비교하지 않는다(소유자 결정 2026-11-07).
The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency`
and its fixture were removed when this branch merged.
예전 ArchUnit 동결 규칙 `inbound_port_implementations_do_not_declare_keyed_idempotency`와 그 fixture는
이 브랜치가 병합될 때 지웠다.
## Read / query path (feature-application-query-bypass-contract)
## 읽기·query 경로 (feature-application-query-bypass-contract)
The read side has two equally-valid shapes; pick per read, do not force one:
읽기 쪽에는 똑같이 유효한 모양이 둘 있다. 읽기마다 고르고, 하나를 강요하지 않는다.
| Shape | Returns | When | How |
| 모양 | 돌려주는 것 | 언제 | 어떻게 |
|---|---|---|---|
| **Through-aggregate** (default for simple reads) | domain aggregate via a `*Repository` port | read shape == write aggregate **and** the aggregate is the minimal invariant boundary (no lazy collections needed) | `QueryUseCase` → repository port → `Order` |
| **Projection (CQRS-lite)** | application-layer projection DTO via a `*QueryPort` | read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | `QueryUseCase` → `*QueryPort` → `OrderSummary` (record); query via JPQL `SELECT new` / JdbcTemplate |
| **aggregate를 거쳐서**(단순 읽기의 기본) | `*Repository` 포트로 받은 도메인 aggregate | 읽기 모양 == 쓰기 aggregate **이고** aggregate가 최소 불변식 경계일 때(지연 컬렉션이 필요 없음) | `QueryUseCase` → repository 포트 → `Order` |
| **projection (CQRS-lite)** | `*QueryPort`로 받은 애플리케이션 계층 projection DTO | 읽기 모양 ≠ 쓰기, 또는 aggregate 수화·지연 컬렉션 join을 건너뛰려 할 때 | `QueryUseCase` → `*QueryPort` → `OrderSummary`(record). query는 JPQL `SELECT new` / JdbcTemplate |
- **Purity guardrail (core, machine-enforced):** a read port whose simple name ends
with `QueryPort` MUST return application-layer projection DTOs only — never a domain
aggregate, JPA entity, or web type, **including through generic type arguments**
(`List<DomainType>`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`.
Projection usage itself is **opt-in**, not a forced default.
- **Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin
web→read-port path — that would bypass the mandatory `@UseCaseCapability` fitness function.
- **Transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read
is an opt-in only when `spring.jpa.open-in-view=false` is confirmed **and** the read is
projection-only (no lazy access) **and** a single statement; otherwise keep `inRead`.
- **Capability:** a repository-backed projection read is still
`repositoryAccess = READ_REPOSITORY`. "Projection vs aggregate" is the return *shape* axis,
orthogonal to the repository-access *level* axis — no new enum. Outbound-HTTP reads (no
repository) stay `RepositoryAccess.NONE`.
- Full CQRS with a separate physical read store is out of scope — escalation only.
- **순수성 가드레일(core, 기계로 강제):** 단순 이름이 `QueryPort`로 끝나는 읽기 포트는 반드시
애플리케이션 계층 projection DTO만 돌려준다 — 도메인 aggregate, JPA 엔티티, web 타입은 **제네릭
타입 인자를 거쳐서도**(`List<DomainType>`) 안 된다. ArchUnit
`query_ports_do_not_leak_domain_jpa_or_web_types`가 강제한다. projection 사용 자체는 강요된 기본이
아니라 **선택**이다.
- **엄격한 절차:** 모든 읽기는 `QueryUseCase` bean을 거친다. web → 읽기 포트로 바로 가는 얇은
경로는 없다. 그런 경로는 필수인 `@UseCaseCapability` 적합성 검사를 건너뛴다.
- **트랜잭션:** 읽기의 기본은 `TransactionPort.inRead`다. 트랜잭션 없는(autocommit) 읽기는
`spring.jpa.open-in-view=false`가 확인됐고 **그리고** 읽기가 projection만 쓰고(지연 접근 없음)
**그리고** 문장 하나일 때만 고를 수 있다. 아니면 `inRead`를 쓴다.
- **capability:** repository를 쓰는 projection 읽기도 `repositoryAccess = READ_REPOSITORY`다.
「projection이냐 aggregate냐」는 돌려주는 *모양* 축이고, repository 접근 *수준* 축과 따로다 — 새
enum이 없다. outbound HTTP 읽기(repository 없음)는 `RepositoryAccess.NONE`이다.
- 물리적으로 따로 둔 읽기 저장소를 쓰는 완전한 CQRS는 범위 밖이다. 올려서 정할 일이다.
## ArchUnit guardrails (enforced)
## ArchUnit 가드레일(강제됨)
- `application_does_not_depend_on_adapters_or_transport`
- `application_does_not_use_spring_transactional_annotation`
@@ -337,9 +322,9 @@ The read side has two equally-valid shapes; pick per read, do not force one:
- `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK`
- `inbound_port_implementations_end_with_use_case`
- `inbound_port_implementations_declare_capability`
- `query_ports_do_not_leak_domain_jpa_or_web_types` (`*QueryPort` return purity)
- `query_ports_do_not_leak_domain_jpa_or_web_types`(`*QueryPort` 반환 순수성)
## Test
## 테스트
```bash
cd src
@@ -347,5 +332,5 @@ cd src
./gradlew :app-bootstrap:architectureTest
```
The messaging types above establish semantic contract R1 only. They do not claim JSON Schema
qualification, Kafka publication, durable outbox persistence or any messaging R2 capability.
위 메시징 타입은 semantic contract R1까지만 세운다. JSON Schema 검증, Kafka 발행, durable outbox
영속, 그 밖의 메시징 R2 capability를 주장하지 않는다.
File diff suppressed because one or more lines are too long
+15 -17
View File
@@ -1,21 +1,19 @@
# composition:outbox-relay
- Module ID `composition-outbox-relay`, Gradle path `:composition:outbox-relay`. Registry SSOT:
- 모듈 ID `composition-outbox-relay`, Gradle 경로 `:composition:outbox-relay`. registry 정본:
`src/config/architecture/modules.json`.
- Responsibility: assemble and drive the application's outbox relay. It builds
`PublishPendingOutboxEventsUseCase` by hand from `app.outbox.*` (`OutboxSettings`, strict binding),
runs it from `OutboxRelayScheduler` (fixed-delay ticks, a `SmartLifecycle` that stops above the
messaging platform's admission phase), and owns the outbox metrics (`OutboxMetrics`: gauges on a
thread of their own, the cycle-outcome counter from the relay).
- Boundaries: it names ports only — `OutboxStorePort`, `OutboxMessagePublishPort`,
`OutboxRelayFailureReportPort`, `TransactionPort` — never a module type, so removing the
persistence or messaging line removes the relay. No business rule, no SQL, no broker type. The
relay use case is never a bean (`@SystemInvoked`, no permission gate). Allowed edges come only from
the registry entry.
- Startup refusals live here because only here do the settings meet the ports: a batch whose worst
case (`batch-size` × the publish port's `longestAttempt`) reaches `in-flight-timeout` fails startup.
- Tests: `./gradlew :composition:outbox-relay:check`. The shutdown order is pinned against the
platform's own phase constant (`OutboxRelayShutdownOrderTest`); the end-to-end relay → bridge → real
Kafka path is `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`.
- Design and rejected alternatives: `README.md`. Operations: `docs/runbooks/outbox-publish-failed.md`,
- 책임: 애플리케이션의 outbox relay를 조립하고 돌린다. `app.outbox.*`(`OutboxSettings`, 엄격한
바인딩)로 `PublishPendingOutboxEventsUseCase`를 손으로 만들고, `OutboxRelayScheduler`(고정 지연
tick, 메시징 플랫폼의 admission phase보다 위에서 멈추는 `SmartLifecycle`)에서 돌리며, outbox metric
(`OutboxMetrics`: 자기 스레드에서 도는 gauge, relay가 내는 cycle 결과 counter)을 가진다.
- 경계: 포트만 이름으로 댄다 — `OutboxStorePort`, `OutboxMessagePublishPort`,
`OutboxRelayFailureReportPort`, `TransactionPort`. 모듈 타입은 대지 않으니 persistence나 messaging
줄을 지우면 relay도 빠진다. 업무 규칙, SQL, broker 타입이 없다. relay 유스케이스는 bean이 아니다
(`@SystemInvoked`, 권한 검사 없음). 허용 edge는 registry 항목에서만 온다.
- 기동 거절은 여기 있다. 설정과 포트가 만나는 곳이 여기뿐이기 때문이다: 최악의 경우
(`batch-size` × 발행 포트의 `longestAttempt`)가 `in-flight-timeout`에 닿는 batch는 기동에 실패한다.
- 시험: `./gradlew :composition:outbox-relay:check`. 종료 순서는 플랫폼 자신의 phase 상수에 맞춰
고정한다(`OutboxRelayShutdownOrderTest`). relay → bridge → 실제 Kafka로 가는 끝에서 끝까지 경로는
`:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`다.
- 설계와 버린 대안: `README.md`. 운영: `docs/runbooks/outbox-publish-failed.md`,
`docs/runbooks/outbox-dead-letter.md`.
+11 -10
View File
@@ -1,13 +1,14 @@
# Architecture module registry
# 아키텍처 모듈 registry
`modules.json` records Gradle project identity and the exact production project edges each leaf may
see. An empty `allowed_dependencies` list is meaningful: it means the leaf is intentionally
project-standalone, not that the registry entry is unfinished.
`modules.json`은 Gradle 프로젝트의 정체(id, Gradle 경로, 소스 경로)와 각 leaf가 볼 수 있는 운영
프로젝트 edge를 정확히 적는다. 빈 `allowed_dependencies` 목록에도 뜻이 있다: 그 leaf가 일부러 다른
프로젝트에 기대지 않는다는 뜻이지, registry 항목을 덜 채웠다는 뜻이 아니다.
`adapter-outbound-persistence-mongo` is the important example. That leaf owns the Mongo provider
implementation without importing application/domain project types; composition into application
ports is owned by the bootstrap/autoconfiguration side. Its empty dependency list is therefore an
explicit boundary and must remain empty until a real project edge is introduced and reviewed.
`domain-core`, `shared-contract`, 들여온 메시징 제품의 `messaging-core-api`가 그 예다. 빈 목록은
분명한 경계이고, 실제 프로젝트 edge를 들여와 리뷰하기 전까지 비어 있어야 한다. 반대로 목록에 적힌
edge는 빌드가 실제로 쓰는 것과 맞아야 한다. 예를 들어 `adapter-outbound-persistence-mongo`의 목록은
`["application-core", "shared-contract"]`이고 `MongoRegistryPermissionParityTest`가 두 방향을 모두
본다.
Runtime composition membership is derived from resolved runtime classpaths by the build logic; it is
not duplicated as a per-module field in this registry.
런타임 조립 구성원은 빌드 로직이 해석된 runtime classpath에서 얻는다. 이 registry에 모듈마다 칸으로
다시 적지 않는다.
+21 -21
View File
@@ -1,36 +1,36 @@
# domain-core — pure domain layer
# domain-core — 순수 도메인 계층
## Registered identity
## 등록 정보
- Module ID: `domain-core`
- Gradle path: `:domain-core`
- Focused test (derived from Gradle path): `./gradlew :domain-core:test --console=plain`
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
- Registry SSOT: `src/config/architecture/modules.json`.
- 모듈 ID: `domain-core`
- Gradle 경로: `:domain-core`
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :domain-core:test --console=plain`
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
- registry 정본: `src/config/architecture/modules.json`.
Package root: `dev.caskeleton.domain`.
패키지 루트: `dev.caskeleton.domain`.
코드 주석에서 덜어낸 **설계 결정의 근거**는 [README.md](README.md) 가 모아둔다 (이 문서는 모듈 규칙 SSOT).
## Responsibility
## 책임
- Business concepts, entities, value objects, enums, domain events, domain services.
- Repository ports where this reference implementation still keeps domain-owned persistence contracts.
- Domain invariants and core rules.
- 업무 개념, 엔티티, 값 객체, enum, 도메인 이벤트, 도메인 서비스.
- 이 참조 구현이 아직 도메인 소유 영속 계약을 두는 곳의 repository 포트.
- 도메인 불변식과 핵심 규칙.
## Allowed
## 허용
- Java standard library.
- Value-only shared operational types only if truly needed.
- Java 표준 라이브러리.
- 값만 담은 공용 운영 타입은 정말 필요할 때만.
## Forbidden
## 금지
- Spring annotations.
- JPA annotations.
- Servlet/HTTP types.
- Adapter, application, bootstrap, or presentation DTO dependencies.
- Spring 애너테이션.
- JPA 애너테이션.
- Servlet·HTTP 타입.
- 어댑터, application, bootstrap, 표현 계층 DTO 의존.
## Test
## 테스트
```bash
cd src
+2 -2
View File
@@ -1,6 +1,6 @@
# grpc-advanced — local authority for the advanced gRPC capabilities
# grpc-advanced — 고급 gRPC capability의 지역 정본
이 문서는 `grpc-advanced:*` family의 **local authority**다. leaf 목록·gradle path·허용 의존성은
이 문서는 `grpc-advanced:*` family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은
`src/config/architecture/modules.json`이 SSOT다. Root 정책(`CLAUDE.md` / `AGENTS.md`)과 충돌하면
root가 이긴다.
+48 -51
View File
@@ -1,6 +1,6 @@
# grpc — local authority for the gRPC platform family
# grpc — gRPC 플랫폼 family의 지역 정본
이 문서는 `grpc:*` family의 **local authority**다. gRPC platform은 기본 application build와 분리된
이 문서는 `grpc:*` family의 **지역 정본(local authority)**이다. gRPC platform은 기본 application build와 분리된
`src/platforms/optional-build` build가 소유한다. 여기서 정하는 것은 family별 framework 규칙, 증거 등급,
Stable 범위의 경계와 application에 채택될 때 필요한 계약이다.
@@ -132,64 +132,61 @@ cd src
(`GrpcMetricCardinalityPolicy`가 거부한다).
### Adoption-time observability gate
### 채택할 때의 관측 게이트
The metric names implemented by `grpc-observability` are **not registered in
`docs/registries/metrics.yaml` yet** because this optional family is not a shipped runtime capability.
Do not present those names as repository-certified metrics until adoption adds registry entries with
the repository's `.seconds` / `.total` unit naming and the corresponding validation gate.
`grpc-observability`가 구현한 metric 이름은 **아직 `docs/registries/metrics.yaml`에 등록하지
않았다**. 이 optional family는 출하하는 런타임 capability가 아니기 때문이다. 채택하면서 저장소의
`.seconds` / `.total` 단위 이름 규칙에 맞는 registry 항목과 그에 맞는 검증 게이트를 더하기 전에는 그
이름을 저장소가 인증한 metric처럼 내세우지 않는다.
### Durable operation ledger adoption
### durable operation 원장 채택
`grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively (11-M9). A deployment that
needs durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, defines a
`GrpcOperationLedger` bean (`new JpaGrpcOperationLedger(repository)`), includes that adapter's Flyway
location `db/migration/grpc` (V001 table, V002 retention index, V003 claim attempt), and sets the flag below. A deployment
that does not adopt the ledger pays no Spring Data JPA classpath cost.
`grpc-spring-boot-starter`는 JPA 원장 어댑터를 전이 의존으로 끌어오지 않는다(11-M9). durable
operation 멱등성이 필요한 배포는 `:grpc:grpc-operation-ledger-jpa`를 직접 더하고,
`GrpcOperationLedger` bean(`new JpaGrpcOperationLedger(repository)`)을 정의하고, 그 어댑터의 Flyway
위치 `db/migration/grpc`(V001 테이블, V002 보존 index, V003 claim attempt)를 넣고, 아래 flag를 켠다.
원장을 채택하지 않는 배포는 Spring Data JPA classpath 비용을 내지 않는다.
| Key (`app.grpc.platform.*`) | Default | What it does |
| 키 (`app.grpc.platform.*`) | 기본값 | 하는 일 |
| --- | --- | --- |
| `operation-ledger-enabled` | `false` | `true`: the starter assembles `GrpcIdempotencyInterceptor` (bean `grpcIdempotencyInterceptor`) and `GrpcOperationLedgerRetention` (bean `grpcOperationLedgerRetention`) over the deployment's `GrpcOperationLedger` bean, and refuses startup when there is none. `false`: neither bean exists, and a method that is `IDEMPOTENCY_KEY_REQUIRED` refuses startup |
| `operation-ledger-claim-ttl` | `5m` | How long an `IN_PROGRESS` claim is trusted to have a live owner. After it, a retry of the same request takes the claim over (`GrpcOperationLedger.reclaimStale`). Refused at startup unless longer than every keyed method's deadline |
| `operation-ledger-retention` | `24h` | How long a finished (`COMMITTED`/`FAILED_TERMINAL`) record is kept before `GrpcOperationLedgerRetention.purgeExpired` may delete it. `IN_PROGRESS` rows are never purged |
| `operation-ledger-enabled` | `false` | `true`: starter가 배포의 `GrpcOperationLedger` bean 위에 `GrpcIdempotencyInterceptor`(bean `grpcIdempotencyInterceptor`)와 `GrpcOperationLedgerRetention`(bean `grpcOperationLedgerRetention`)을 조립하고, 원장 bean이 없으면 기동을 거절한다. `false`: 두 bean 모두 없고, `IDEMPOTENCY_KEY_REQUIRED`인 메서드가 있으면 기동을 거절한다 |
| `operation-ledger-claim-ttl` | `5m` | `IN_PROGRESS` claim의 주인이 살아 있다고 믿는 시간. 지나면 같은 요청의 재시도가 claim을 넘겨받는다(`GrpcOperationLedger.reclaimStale`). 키가 필요한 모든 메서드의 deadline보다 길지 않으면 기동에서 거절한다 |
| `operation-ledger-retention` | `24h` | 끝난(`COMMITTED`/`FAILED_TERMINAL`) 레코드를 `GrpcOperationLedgerRetention.purgeExpired`가 지울 수 있게 되기 전까지 두는 시간. `IN_PROGRESS` 행은 지우지 않는다 |
Defaults: the 5-minute TTL is the value the ledger contract and interceptor tests certify, far beyond
a unary deadline, and short enough that a key whose owner died unblocks within a client's retry
patience. The 24-hour retention matches the HTTP idempotency replay TTL
(`app.capabilities.idempotency.replay-ttl`). A retry of a key after its record was purged is a new
operation, so the retention must exceed the callers' retry window.
기본값: 5분 TTL은 원장 계약 시험과 interceptor 시험이 인증한 값이다. unary deadline보다 훨씬 길고,
주인이 죽은 키가 클라이언트의 재시도 인내 안에 풀릴 만큼 짧다. 24시간 보존은 HTTP 멱등성 재생 TTL
(`app.capabilities.idempotency.replay-ttl`)과 같다. 레코드를 지운 뒤 같은 키로 하는 재시도는 새
operation이므로, 보존 시간은 호출자의 재시도 창보다 길어야 한다.
These keys are not in `docs/registries/env-keys.yaml`: no `app.grpc.platform.*` key is, because the
optional build is not part of the shipped runtime. They join the registry when a composition root
adopts the platform.
이 키들은 `docs/registries/env-keys.yaml`에 없다. optional 빌드는 출하하는 런타임이 아니라서
`app.grpc.platform.*` 키는 하나도 없다. 조립 루트가 플랫폼을 채택할 때 registry에 들어간다.
**Why the starter assembles the interceptor (option (b)), and not (a).** The 2026-11-01 maturity review proposed (a):
delete the flag and judge by whether a ledger bean exists. (b) was chosen on 2026-11-03 and is recorded in
ADR-GRPC-004: the flag stays and means what it says — when true, the
decision function is assembled and its TTL comes from configuration. (a) would have removed the false promise but left every adopter to rebuild the same
assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no
`@ConditionalOnMissingBean` on purpose: a replacement would silently ignore `operation-ledger-claim-ttl`.
Duplicates of a running operation are refused (`REJECT_IN_PROGRESS`), not told to wait; a
wait-and-poll option becomes a key when a keyed method needs it.
**starter가 interceptor를 조립하는 이유(선택지 (b)), (a)가 아닌 이유.** 2026-11-01 성숙도 리뷰는
(a)를 제안했다: flag를 지우고 원장 bean이 있는지로 판단한다. 2026-11-03에 (b)를 골랐고 ADR-GRPC-004에
적었다: flag를 남기고 flag는 말 그대로의 뜻이다 — true이면 판정 함수를 조립하고 그 TTL은 설정에서
온다. (a)는 거짓 약속을 없앴겠지만 채택하는 쪽마다 같은 조립과 TTL 검증을 손으로 다시 만들게
했다. (b)는 그것을 한곳에 둔다. interceptor bean에는 일부러 `@ConditionalOnMissingBean`이 없다:
바꿔 넣은 bean은 `operation-ledger-claim-ttl`을 소리 없이 무시하게 된다. 돌고 있는 operation의
중복은 기다리라고 하지 않고 거절한다(`REJECT_IN_PROGRESS`). 기다렸다가 다시 묻는 선택지는 키가
필요한 메서드가 그것을 필요로 할 때 키가 된다.
**Server wiring is still the adopter's, and stays a separate decision.** The starter builds no
server, so assembling the decision does not wire the platform into `adapter:inbound:grpc` (see "배선은
별도 결정" above). `GrpcIdempotencyInterceptor` is a decision function, not an `io.grpc.ServerInterceptor`.
The adopter injects the bean by type and calls it from its own `IDEMPOTENCY` stage interceptor
(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`) or from
its typed service adapter: `decide(...)` before the mutation, `recordCommit(...)` inside the mutation's
transaction, `recordFailure(...)` on a terminal failure. Both record calls take the `GrpcClaimToken`
the `PROCEED` decision carried: a commit by an attempt whose claim was taken over is refused (its
transaction rolls back) and its failure is ignored, so a slow owner cannot write over the attempt that
took its claim (ADR-GRPC-004).
**서버 배선은 여전히 채택하는 쪽의 몫이고, 따로 정할 일로 남는다.** starter는 서버를 만들지
않으므로, 판정을 조립한다고 플랫폼이 `adapter:inbound:grpc`에 배선되지는 않는다(위 "배선은
별도 결정"을 본다). `GrpcIdempotencyInterceptor`는 판정 함수이고 `io.grpc.ServerInterceptor`가
아니다. 채택하는 쪽은 bean을 타입으로 주입받아 자기 `IDEMPOTENCY` 단계 interceptor
(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`)나 자기
typed service adapter에서 부른다: 변경 전에 `decide(...)`, 변경의 트랜잭션 안에서
`recordCommit(...)`, 끝난 실패에 `recordFailure(...)`. 두 기록 호출은 모두 `PROCEED` 판정이 실어 온
`GrpcClaimToken`을 받는다: claim을 넘겨준 시도의 커밋은 거절되고(그 트랜잭션은 롤백된다) 그 실패는
무시된다. 그래서 느린 주인이 claim을 가져간 시도를 덮어쓰지 못한다(ADR-GRPC-004).
**Purge scheduling is the adopter's.** `GrpcOperationLedgerRetention.purgeExpired(now)` deletes
expired finished rows in bounded batches (500 per statement) until a batch comes back short. The
starter does not schedule it: it owns no scheduler and cannot know which replica should run it, and a
scheduled bean would force a task scheduler onto every deployment. The adopter calls it from its own
scheduler (for example hourly); concurrent runs on several replicas are safe because the delete skips
locked rows. Running it never is safe but lets the table grow without bound.
**지우기 일정은 채택하는 쪽의 몫이다.** `GrpcOperationLedgerRetention.purgeExpired(now)`는 기한이 지난
끝난 행을 한계 있는 batch(문장 하나에 500)로 지우고, batch가 덜 차서 돌아오면 멈춘다. starter는 이것을
예약하지 않는다: scheduler를 가지지 않고 어느 replica가 돌려야 하는지 알 수 없으며, 예약된 bean은 모든
배포에 task scheduler를 강요하게 된다. 채택하는 쪽이 자기 scheduler에서 부른다(예: 한 시간마다).
지우기가 잠긴 행을 건너뛰므로 여러 replica에서 동시에 돌려도 안전하다. 한 번도 돌리지 않아도 안전하지만
테이블이 끝없이 커진다.
The commit must be recorded in the mutation's transaction and the TTL must be longer than the slowest
keyed method; both reasons are in ADR-GRPC-004.
커밋은 변경의 트랜잭션 안에서 기록해야 하고 TTL은 키가 필요한 가장 느린 메서드보다 길어야 한다. 두
이유는 모두 ADR-GRPC-004에 있다.
+3 -3
View File
@@ -1,6 +1,6 @@
# messaging — local authority for the messaging platform family
# messaging — 메시징 플랫폼 family의 지역 정본
이 문서는 messaging family의 **local authority**다. leaf 목록·gradle path·허용 의존성은
이 문서는 messaging family의 **지역 정본(local authority)**이다. leaf 목록·gradle path·허용 의존성은
`src/config/architecture/modules.json`이 SSOT이며 이 문서는 그것을 복제하지 않는다. 여기서 정하는
것은 registry가 표현할 수 없는 것들이다: family별 framework 규칙, public surface 정책, Stable 승격에
필요한 증거, runtime membership이 비어 있다는 사실의 의미.
@@ -40,7 +40,7 @@ JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMES
registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는
`shared-contract`의 정본과 같은 규칙인지 함께 본다.
### Publish retryability of authentication and authorization
### 인증·인가 거부의 발행 재시도 여부 (Publish retryability of authentication and authorization)
이 제품 안에는 같은 category에 대한 재시도 규칙이 둘 있다. 의도다.
+6 -6
View File
@@ -1,13 +1,13 @@
# Optional gRPC platforms
# optional gRPC 플랫폼
The default application does not depend on `grpc/*` or `grpc-advanced/*`, so those projects (the
registry entries with `"build": "optional-grpc"`) are kept out of the main multi-project build. This build preserves their existing project paths and
internal project dependencies while making their configuration opt-in.
기본 애플리케이션은 `grpc/*`나 `grpc-advanced/*`에 의존하지 않는다. 그래서 이 프로젝트들(registry에서
`"build": "optional-grpc"`인 항목)은 주 멀티 프로젝트 빌드에서 뺀다. 이 빌드는 그 프로젝트들의 원래
프로젝트 경로와 내부 프로젝트 의존을 그대로 두면서, 그 설정을 고를 때만 켜지게 한다.
```bash
./gradlew -p platforms/optional-build ci
./gradlew -p platforms/optional-build :grpc:grpc-testkit:grpcInProcessContractTest
```
`adapter:inbound:grpc` remains in the main application build because it is an application adapter;
the reusable gRPC platform libraries are optional capability code and live here.
`adapter:inbound:grpc`는 애플리케이션 어댑터라서 주 애플리케이션 빌드에 남는다. 다시 쓰는 gRPC
플랫폼 라이브러리는 optional capability 코드이고 여기 있다.
+56 -60
View File
@@ -1,72 +1,68 @@
# shared-contract — skeleton-wide operational contract
# shared-contract — 골격 전체가 쓰는 운영 계약
## Registered identity
## 등록 정보
- Module ID: `shared-contract`
- Gradle path: `:shared-contract`
- Focused test (derived from Gradle path): `./gradlew :shared-contract:test --console=plain`
- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0.
- Registry SSOT: `src/config/architecture/modules.json`.
- 모듈 ID: `shared-contract`
- Gradle 경로: `:shared-contract`
- 이 모듈만 시험(Gradle 경로에서 나온 명령): `./gradlew :shared-contract:test --console=plain`
- 실행 기준: Java 21. 프레임워크 기준인 Spring Boot 버전은 `src/gradle/libs.versions.toml`이 정한다.
- registry 정본: `src/config/architecture/modules.json`.
Package root: `dev.caskeleton.shared`.
패키지 루트: `dev.caskeleton.shared`.
Design decisions previously kept as code comments (error-code classification, response
envelope shape, metric cardinality bounds, tracing seam, domain-context propagation) live in
[README.md](README.md). This file stays the SSOT for module rules.
예전에 코드 주석에 두던 설계 결정(오류 코드 분류, 응답 envelope 모양, metric cardinality 한계,
tracing 이음매, domain-context 전파)은 [README.md](README.md)에 있다. 이 파일은 모듈 규칙의 정본으로
남는다.
## Responsibility
- Response envelope (`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`).
- Error code contract (`error/ApiErrorCode` interface, `error/OperationalError` enum,
`error/ApiErrorCarrier`) and the one client-facing wording table (`error/ClientErrorMessages`,
Korean, one message per `Category`, used by every transport).
- Cross-cutting mapper sentinel (`error/MappingException`).
- Request value contract (`request/Patch`).
- Tracing contract types (`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C
`traceparent` value type and the span-error-recording seam (feature-distributed-tracing-contract; the OTel
tracer runtime is a fork-activated seam, so these stay Java-stdlib-only).
- Stdlib helpers every leaf used to copy (moved here in the 2026-09-25 review follow-up): `digest/Sha256` (the
SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256`
(sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means
`U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend
on this module and keep their own copies; each family's CLAUDE.md says why (a different product,
decided after the 2026-08-14 messaging module review). Every template leaf that needs one of these has the `shared-contract` edge and uses them
instead of copying: identifier, persistence-mongo, application-objectstorage and redis-sdk took the
edge for exactly this (decided 2026-11-03), each with a test
that pins its output to a vector computed outside the JVM.
- `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`)
every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike.
- `ratelimit/`: the provider-neutral edge rate-limit port (`EdgeRateLimitPort`) and its value types,
between the web edge and the Redis adapter (README 「ratelimit」).
- `security/Permission`: the `resource:action` permission value `AuthorizationPort` is asked about
(README 「security」).
- `concurrency/`: the domain-context propagation port and its `ThreadLocal` default (README
「concurrency」).
- `runtime/RuntimeEnvironment`: the one runtime-profile vocabulary every leaf answers "is this
production?" with.
- `metrics/ForbiddenMetricTags`: the high-cardinality tag keys no metric may carry.
- These are the module's packages and the only ones it may have:
`ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES` refuses a
class in any other package below `dev.caskeleton.shared` or directly in the root, which holds only
its `package-info`. A new contract package goes into that test's `SHARED_CONTRACT_PACKAGES` and
into this list together; `SharedContractPackageRuleTest` fails when `SHARED_CONTRACT_PACKAGES` and
the module's packages differ.
- Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`:
## 책임 (Responsibility)
- 응답 envelope(`response/Envelope`, `response/ApiError`, `response/BulkEnvelope`, `response/BulkItemResult`).
- 오류 코드 계약(`error/ApiErrorCode` 인터페이스, `error/OperationalError` enum,
`error/ApiErrorCarrier`)과 클라이언트에 보여 줄 문구 표 하나(`error/ClientErrorMessages`.
한국어이고 `Category`마다 문구 하나이며 모든 전송 계층이 쓴다).
- 계층을 가로지르는 mapper 표지 예외(`error/MappingException`).
- 요청 값 계약(`request/Patch`).
- tracing 계약 타입(`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C `traceparent` 값 타입과
span 오류 기록 이음매(feature-distributed-tracing-contract. OTel tracer 런타임은 fork가 켜는
이음매라서 이 타입들은 Java 표준 라이브러리만 쓴다).
- 모든 leaf가 복사해 쓰던 표준 라이브러리 도우미(2026-09-25 리뷰 후속으로 여기로 옮겼다):
`digest/Sha256`(SHA-256 digest 값과 유일한 `MessageDigest.getInstance("SHA-256")`),
`digest/HmacSha256`(서명과 상수 시간 검증), `retry/Backoff`(상한 있는 지수 ceiling. "full jitter"는
`U[0, ceiling]`이고 다른 뜻이 아니다). 들여온 `messaging:*`와 optional gRPC 빌드는 이 모듈에
의존하지 않고 자기 사본을 둔다. 각 제품의 CLAUDE.md가 이유를 적는다(다른 제품이다. 2026-08-14 메시징
모듈 리뷰 뒤에 정했다). 이 도우미가 필요한 템플릿 leaf는 모두 `shared-contract` edge를 두고 복사하지
않고 쓴다. identifier, persistence-mongo, application-objectstorage, redis-sdk가 바로 이 때문에
edge를 받았고(2026-11-03에 정함), 각각 JVM 밖에서 계산한 벡터로 출력을 고정하는 시험이 있다.
- `observability/MdcKeys`: 모든 전송 계층(web, GraphQL, STOMP, gRPC)이 요청의 correlation을 넣는
snake_case MDC 키 이름(registry `docs/registries/mdc-keys.yaml`).
- `ratelimit/`: web edge와 Redis 어댑터 사이에 있는 provider 중립 edge rate-limit 포트
(`EdgeRateLimitPort`)와 그 값 타입(README 「ratelimit」).
- `security/Permission`: `AuthorizationPort`에 묻는 `resource:action` 권한 값(README 「security」).
- `concurrency/`: domain-context 전파 포트와 그 `ThreadLocal` 기본 구현(README 「concurrency」).
- `runtime/RuntimeEnvironment`: 모든 leaf가 「운영 환경인가?」에 답할 때 쓰는 유일한 runtime profile
어휘.
- `metrics/ForbiddenMetricTags`: 어떤 metric도 실으면 안 되는 high-cardinality tag 키.
- 이 모듈의 패키지는 위가 전부이고 다른 패키지는 둘 수 없다:
`ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가
`dev.caskeleton.shared` 아래 다른 패키지에 있는 클래스와 루트에 바로 있는 클래스를 거절한다. 루트에는
`package-info`만 있다. 새 계약 패키지는 그 시험의 `SHARED_CONTRACT_PACKAGES`와 이 목록에 함께
넣는다. `SharedContractPackageRuleTest`는 `SHARED_CONTRACT_PACKAGES`와 모듈의 패키지가 다르면
실패한다.
- 계약 시험만 읽는 registry 규칙 사본은 `main`이 아니라 `testFixtures`에 둔다:
`metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`,
`tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it.
- Generic messaging envelope schema resources under `contracts/messaging/envelope/`.
They own transport-neutral envelope metadata only; feature payload schemas remain in their
feature-owner modules. Resource presence is not runtime discovery or registration.
`tracing/BaggageAllowlist`. 운영 코드가 쓰게 될 때만 `main`으로 옮긴다.
- `contracts/messaging/envelope/` 아래의 범용 메시징 envelope schema 리소스. 전송 중립 envelope
metadata만 가진다. 기능 payload schema는 그 기능을 가진 모듈에 남는다. 리소스가 있다고 런타임에
찾아지거나 등록되는 것은 아니다.
## Allowed
- Java standard library ONLY. No Spring, no Jackson, no JPA imports.
## 허용
- Java 표준 라이브러리**만**. Spring, Jackson, JPA import는 없다.
## Forbidden
- business/domain concept (domain error codes belong in the consuming module).
- framework imports (HTTP status is expressed as transport-neutral `int`; the web module maps it).
- claiming Draft 2020-12 validator compatibility before the messaging adapter's Task 6 validator
qualification exists.
## 금지 (Forbidden)
- 업무·도메인 개념(도메인 오류 코드는 그것을 쓰는 모듈에 둔다).
- 프레임워크 import(HTTP 상태는 전송 중립 `int`로 나타내고 web 모듈이 대응시킨다).
- 메시징 어댑터의 Task 6 validator 검증이 생기기 전에 Draft 2020-12 validator 호환을 주장하기.
## Test
## 테스트
```bash
cd src
./gradlew :shared-contract:test